dsh-bagu 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,57 +1,39 @@
1
1
  /**
2
2
  * dsh-bagu · 宿主半侧
3
3
  *
4
- * 三件事:
5
- * 1. 往系统提示里挂一节「说什么」,讲的是念头不是词表(可在设置页关掉)
6
- * 2. 挂两个只读工具:bagu_check、bagu_ask
7
- * 3. 开 /api/bagu,给设置页用
4
+ * 三件事:挂一节提示、挂两个只读工具、开 /api/bagu。
8
5
  *
9
- * 刻意不做的事:不自动改写。改要人改。
6
+ * 省 token 是这个插件的设计约束,不是优化项:
7
+ * - 提示词压到 150 字以内,每次会话都要烧
8
+ * - 工具描述压到 60 字以内,每次调用都在上下文里
9
+ * - 默认输出三行以内;要看细节传 full: true
10
+ *
11
+ * 所有判断都在本地正则里做完,不调模型 —— 这是零 token 成本的那一半。
10
12
  */
11
13
 
12
- import { analyze, render } from './analyze.js';
14
+ import { analyze } from './analyze.js';
15
+ import { render, renderBrief } from './render.js';
13
16
  import { readConfig, writeConfig, CONFIG_FILE, DEFAULTS } from './config.js';
14
17
 
15
18
  export const name = 'dsh-bagu';
16
19
 
17
- export { analyze, render };
20
+ export { analyze, render, renderBrief };
18
21
 
19
- /** 当前生效的配置。设置页改了立刻换掉。 */
20
22
  let live = readConfig();
21
-
22
- /** 已挂上去的 prompt 节,改了要先撤再挂。 */
23
23
  const syncers = new Set();
24
24
 
25
- const PROMPT = `## 说话的念头
26
-
27
- 开口前先问的不是「这么答对不对」,是「我要说什么」。
28
-
29
- 两者差得远。前一个问题让你去猜对方想听什么,后一个问题让你去想自己要给什么。
30
-
31
- 一句话换个人说,还成不成立?成立,就是八股。谁都能说的话,慢慢就没人想看了。
32
- 问题不在礼貌,在可替换。
33
-
34
- 几个具体的:
35
-
36
- - **别急着认错。**对方只是问一句,不一定是在说你错。对就说是,别为了顺着改口,把对的也改错了。
37
- - **留一处不确定。**一个「好像 / 应该 / 大概」都没有的段落,是在下断言,不是在说话。
38
- - **具体压过评价。**「挺好的」谁都能说;「骨架在推所以有点飘」只有看过的人才说得出。
39
- - **篇幅别总一样齐。**每段都三句、每句都差不多长,整齐本身就是痕迹。
40
- - **说七分。**话别一次说完。留点让人问。
41
-
42
- 不硬塞语气词,不为了显得像人而加口癖。加进去的是另一种假。`;
43
-
44
- const TOOL_CHECK = `查一段话有多「可替换」。给几个分开的指标和一个判档,不给单一总分,也不自动改写。
25
+ /** 150 字。每次会话注入,多一个字都是白烧。 */
26
+ const PROMPT = `一句话换个人说还成不成立?成立,就是八股。
45
27
 
46
- 指标:
47
- - 具体性(每百字几个数字/时间/经历/原话/名字)
48
- - 抽象度、评价度(意义、价值、本质 / 重要、关键、深刻)
49
- - 留白词密度(好像、应该、大概)
50
- - 结构腔(不是X而是Y 等),以及同一百字里几种句式扎堆
28
+ - 别急着认错。对方问一句,不等于你在说错。
29
+ - 留一处不确定。全篇一个「大概」都没有,是在下断言。
30
+ - 具体压过评价。「骨架在推所以有点飘」只有看过的人才说得出。
31
+ - 别每句一样长。整齐本身就是痕迹。`;
51
32
 
52
- 返回里带一组「要你自己答」的问句。答不上来,那处就是摆设。`;
33
+ /** 60 字。 */
34
+ const TOOL_CHECK = `查一段话有多可替换:具体物、抽象词、留白、同义轮换、结构腔。只报不给改。默认三行,full 给详细报告。`;
53
35
 
54
- const TOOL_ASK = `只给问句,不给结论。想让人自己看着改、不想被工具改的时候用这个。`;
36
+ const TOOL_ASK = `只要问句,不要结论。`;
55
37
 
56
38
  function toolOutput() {
57
39
  return {
@@ -62,7 +44,6 @@ function toolOutput() {
62
44
  properties: {
63
45
  ok: { type: 'boolean' },
64
46
  text: { type: 'string' },
65
- detail: { type: 'object' },
66
47
  },
67
48
  },
68
49
  render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
@@ -77,7 +58,6 @@ function thresholdsOf(cfg) {
77
58
  };
78
59
  }
79
60
 
80
- /** 配置变了以后,让已经挂上的 prompt 节跟着换。 */
81
61
  function applyLive(next) {
82
62
  live = next;
83
63
  for (const sync of syncers) {
@@ -105,7 +85,6 @@ function readBody(req) {
105
85
  }
106
86
 
107
87
  export function apply(root, config = {}) {
108
- // cordis.patch.yml 里的初始值,只在 config.json 还没写过时作底
109
88
  live = readConfig();
110
89
  if (config && typeof config === 'object') {
111
90
  for (const k of Object.keys(DEFAULTS)) {
@@ -139,16 +118,17 @@ export function apply(root, config = {}) {
139
118
  parameters: {
140
119
  type: 'object',
141
120
  properties: {
142
- text: { type: 'string', description: '要查的整段话。整段传,别自己先切句。' },
121
+ text: { type: 'string', description: '整段话。' },
122
+ full: { type: 'boolean', description: 'true 给详细报告。默认三行。' },
143
123
  },
144
124
  required: ['text'],
145
125
  },
146
126
  output: toolOutput(),
147
127
  execute: async (args) => {
148
128
  const src = String(args?.text ?? '');
149
- if (!src.trim()) return { ok: false, text: '没有收到文字。' };
129
+ if (!src.trim()) return { ok: false, text: '没有文字。' };
150
130
  const r = analyze(src, thresholdsOf(live));
151
- return { ok: true, text: render(r), detail: { band: r.band, scores: r.scores } };
131
+ return { ok: true, text: render(r, { full: args?.full === true }) };
152
132
  },
153
133
  });
154
134
 
@@ -158,17 +138,18 @@ export function apply(root, config = {}) {
158
138
  parameters: {
159
139
  type: 'object',
160
140
  properties: {
161
- text: { type: 'string', description: '要问的那段话。' },
141
+ text: { type: 'string', description: '整段话。' },
142
+ n: { type: 'number', description: '几条,默认 3,最多 6。' },
162
143
  },
163
144
  required: ['text'],
164
145
  },
165
146
  output: toolOutput(),
166
147
  execute: async (args) => {
167
148
  const src = String(args?.text ?? '');
168
- if (!src.trim()) return { ok: false, text: '没有收到文字。' };
149
+ if (!src.trim()) return { ok: false, text: '没有文字。' };
169
150
  const r = analyze(src, thresholdsOf(live));
170
- const text = r.asks.map((a, i) => `${i + 1}. ${a}`).join('\n');
171
- return { ok: true, text, detail: { band: r.band } };
151
+ const n = Math.min(6, Math.max(1, Number(args?.n) || 3));
152
+ return { ok: true, text: r.asks.slice(0, n).map((a, i) => `${i + 1}. ${a}`).join('\n') };
172
153
  },
173
154
  });
174
155
  });
@@ -200,7 +181,7 @@ export function apply(root, config = {}) {
200
181
  const src = String(body?.text ?? '');
201
182
  if (!src.trim()) return sendJson(res, 200, { ok: false, error: '没有文字' });
202
183
  const r = analyze(src, thresholdsOf(live));
203
- return sendJson(res, 200, { ok: true, text: render(r), band: r.band, scores: r.scores });
184
+ return sendJson(res, 200, { ok: true, text: render(r, { full: body?.full === true }), band: r.band });
204
185
  }
205
186
 
206
187
  return sendJson(res, 404, { ok: false, error: `unknown ${req.method} ${path}` });
@@ -214,10 +195,10 @@ export function apply(root, config = {}) {
214
195
  path: '/api/bagu',
215
196
  handler: (req, res) => {
216
197
  Promise.resolve(handler(req, res)).catch((e) => {
217
- try { sendJson(res, 500, { ok: false, error: e?.message ?? String(e) }) } catch { /* 已经走了 */ }
198
+ try { sendJson(res, 500, { ok: false, error: e?.message ?? String(e) }) } catch { /* 已走 */ }
218
199
  });
219
200
  },
220
201
  }), 'dsh-bagu: /api/bagu');
221
- } catch { /* headless 里没有 webServer 是正常的 */ }
202
+ } catch { /* headless 没有 webServer 正常 */ }
222
203
  });
223
204
  }
package/lib/lexicon.js CHANGED
@@ -128,6 +128,17 @@ export const HEDGE_WORDS = [
128
128
  '我猜',
129
129
  ];
130
130
 
131
+ /**
132
+ * 英文 uncertainty 词。只收明确的不确定表达 ——
133
+ * should 在英文里同样是 must,不能算(issue #1 评论第 2 条)。
134
+ */
135
+ export const HEDGE_WORDS_EN = [
136
+ 'maybe', 'probably', 'perhaps', 'possibly', 'not sure',
137
+ "don't know", 'do not know', 'i think', 'i guess',
138
+ 'might', 'could be', 'seems', 'apparently', 'roughly',
139
+ 'approximately', 'iirc', 'afaik', 'unsure', 'unclear',
140
+ ];
141
+
131
142
  /**
132
143
  * 具体性信号:只有真的在说事的人才给得出的东西。
133
144
  * 「可替换」的反面。
@@ -143,20 +154,30 @@ export const CONCRETE_MARKERS = {
143
154
  sense: /(?:看见|听到|闻|摸|尝|痛|酸|烫|凉|冷|热|饿|困|累|味道|声音|手感)/g,
144
155
  /** 引号里的原话、书名号、代码 */
145
156
  quoted: /(?:「[^」]{1,40}」|"[^"]{1,40}"|《[^》]{1,40}》|`[^`]{1,40}`)/g,
157
+ /** 数量:次、遍、个、天、分钟,不带阿拉伯数字也算 */
158
+ count: /(?:[一二三四五六七八九十两几半]{1,3}|\d+)(?:次|遍|个|天|分钟|小时|秒|岁|块钱|人|行|页|版本)/g,
146
159
  /** 具体到能指认的东西:路径、命令、英文标识符。必须带非字母字符或数字,否则 the/and/before 全命中(issue #1 第 1 条)。 */
147
160
  ident: /(?:[A-Za-z_][A-Za-z0-9_]*[\/._:=-][\w./:-]{2,}|\/[\w./-]{3,}|\b[A-Z]{2,}\b|\d+[A-Za-z]+)/g,
148
161
  };
149
162
 
150
163
  /**
151
- * 各类具体物的权重。路径串和版本号最容易凭空写出来,
152
- * 亲身经历和身体感受最难(issue #1 第 2 条)。
164
+ * 各类具体物的权重。
165
+ *
166
+ * 原版按「难伪造 → 加权」,把 experience/sense 给到 1.5。这是错的(issue #1 评论):
167
+ * 经历最好编 —— 「时间词 + 我试过 + 身体感受」三样凑齐就是模板,写任何内容都能套。
168
+ * 实测编造的「我昨天试着改了一下,折腾到凌晨两点半才跑通,手都酸了」拿 18.52,
169
+ * 真实的「配置文件在 /etc/app/config.yml,端口 8080,版本 v1.4.2」只有 5.68,三倍差。
170
+ *
171
+ * 数字和路径好写,但可核验 —— 编一个具体版本号,查一下就知道。
172
+ * 所以这两类给分,经历类降到 0.5:它测的是信息密度,不是真伪。
153
173
  */
154
174
  export const CONCRETE_WEIGHTS = {
155
- experience: 1.5,
156
- sense: 1.5,
175
+ number: 1.2,
176
+ ident: 1.2,
157
177
  time: 1.0,
158
- number: 0.5,
159
- ident: 0.5,
178
+ count: 1.0,
179
+ experience: 0.5,
180
+ sense: 0.5,
160
181
  quoted: 0,
161
182
  };
162
183
 
@@ -167,10 +188,38 @@ export const STRUCTURE_FRAMES = [
167
188
  { id: 'firstThen', name: '先…再…', per1k: 0.01, re: /先[^,。\n]{1,10}再/g },
168
189
  { id: 'triple', name: '三段并列', per1k: 0.23, re: /[^,。、\s]{2,8}、[^,。、\s]{2,8}、[^,。、\s]{2,8}/g },
169
190
  { id: 'emdash', name: '破折号', per1k: 0.22, re: /——+|—/g },
170
- { id: 'roadmap', name: '首先/其次/综上', per1k: 0.5, re: /(?:首先|其次|综上所述|总而言之)/g },
171
191
  { id: 'yue', name: '越…越', per1k: 0.16, re: /越[^,。\n]{1,8}越/g },
192
+ // 「首先/其次/综上」曾在这里,per1k 0.5。已移出:
193
+ // lieflat 520 万字配对复测 δ +0.02,对当代模型彻底失效(人类和 AI 用的一样多)。
194
+ // 还留在 AI_WORDS 里当提示,不进判档。
172
195
  ];
173
196
 
197
+ /**
198
+ * 同义词轮换组。同一段里从一组里挑两个以上,就是在「不敢重复」。
199
+ *
200
+ * lieflat 实测:词汇多样性 mtld δ +0.91 / mattr +0.75,是全表第二强的信号。
201
+ * 真人会反复用同一个词,AI 换着说。
202
+ */
203
+ export const SYNONYM_GROUPS = [
204
+ ['使用', '采用', '运用', '利用', '借助'],
205
+ ['方法', '方式', '途径', '路径', '做法'],
206
+ ['提升', '提高', '增强', '强化', '优化'],
207
+ ['显示', '表明', '揭示', '反映', '说明'],
208
+ ['重要', '关键', '核心', '至关重要'],
209
+ ['问题', '难题', '挑战', '困境', '痛点'],
210
+ ['帮助', '协助', '助力', '支持'],
211
+ ['显著', '大幅', '明显', '卓有成效'],
212
+ ];
213
+
214
+ /**
215
+ * 短句路径专用的信号:模板三连。
216
+ *
217
+ * 「首先/其次/最后」作为结构腔指标已经删了(δ +0.02,人类用得一样多),
218
+ * 但三连齐全时它仍是模板的标记 —— issue #1 评论实测:
219
+ * 「首先我们要明确目标;其次要拆解任务;最后要复盘总结。」26 字判「正常」。
220
+ */
221
+ export const TEMPLATE_TRIPLE = /首先[^。;!?\n]{1,30}[;;][^。;!?\n]{0,10}其次[^。;!?\n]{1,30}[;;,,][^。;!?\n]{0,10}(?:最后|最终|总之)/;
222
+
174
223
  /** 文体基线与判定词,按真人评论语料实测。 */
175
224
  export const REGISTERS = {
176
225
  chat: { label: '闲聊', per1k: 0.8 },
@@ -181,14 +230,13 @@ export const REGISTERS = {
181
230
  };
182
231
 
183
232
  /**
184
- * 真人留白词密度(每千字)。
233
+ * 留白词低于这条线就报「句句在下断言」。单位是每千字。
185
234
  *
186
- * 这个数字我核不出来了 —— 原始语料不在这台机器上,注释里留的两组数
187
- * (0.41~0.70 vs 2.0)差三到五倍,issue #1 第 6a 条指的就是这个。
188
- * 按保守取值:用 0.55(注释区间上限附近),宁可少报也不误伤真人。
189
- * 重新量过语料的人应该把这里改回实测值。
235
+ * 曾经这里还有一个 HEDGE_BASELINE = 2.0(后来改成 0.55)用来在输出里
236
+ * 跟真人对齐。那个数是量纲错的:它更像「真人样本里含留白词的比例」,
237
+ * 却在跟 per1k 的密度并排放,于是「33 个字里有 3 个留白词」会输出成
238
+ * 「90.9/千,真人约 0.55」—— 差 165 倍的一句废话。
239
+ *
240
+ * 删掉了。判档从头到尾只看下面这个绝对门槛。
190
241
  */
191
- export const HEDGE_BASELINE = 0.55;
192
-
193
- /** 留白词低于这条线就报「句句在下断言」。 */
194
242
  export const HEDGE_FLOOR = 0.2;
package/lib/render.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * 输出渲染。默认紧凑,full 才给完整报告。
3
+ *
4
+ * 设计约束:这是要进上下文的文本,每一个字都在烧 token。
5
+ * 默认输出压到三行以内;需要细节的人自己传 full。
6
+ */
7
+
8
+ const BAND = {
9
+ heavy: '可疑',
10
+ mid: '有点',
11
+ low: '正常',
12
+ 'too-short': '太短',
13
+ };
14
+
15
+ function pct(n) {
16
+ return Number.isFinite(n) ? n : 0;
17
+ }
18
+
19
+ /**
20
+ * @param {object} r analyze() 的结果
21
+ * @param {{full?: boolean}} opts
22
+ */
23
+ export function render(r, opts = {}) {
24
+ const full = opts.full === true;
25
+
26
+ // 三行紧凑模式
27
+ if (!full) {
28
+ const head = BAND[r.band] || r.bandLabel;
29
+ const nums = `具体${pct(r.scores.concretePer100)} 抽象${r.scores.abstract} ` +
30
+ `评价${r.scores.evaluation} 留白${pct(r.scores.hedgePer1k)} 结构${pct(r.scores.structurePer1k)}/千`;
31
+ const hits = [];
32
+ for (const row of r.hits.structures) {
33
+ for (const s of row.spans.slice(0, 2)) hits.push(`「${s.text}」`);
34
+ if (row.spans.length > 2) hits[hits.length - 1] += `×${row.spans.length}`;
35
+ }
36
+ for (const h of r.hits.aiWords.slice(0, 3)) hits.push(h.word);
37
+ if (r.synonyms && r.synonyms.length) hits.push(`同义轮换${r.synonyms.length}组`);
38
+
39
+ const lines = [head];
40
+ if (nums.length > 4) lines[0] += ` ${nums}`;
41
+ if (hits.length) lines.push('· ' + hits.slice(0, 6).join(' '));
42
+ if (r.asks && r.asks.length) lines.push('问 ' + r.asks[0]);
43
+ return lines.join('\n');
44
+ }
45
+
46
+ // 完整模式(原样保留详细版,供人看)
47
+ const L = [];
48
+ L.push(`[判断] ${r.bandLabel} · ${r.bandNote}`);
49
+ L.push(`[文体] ${r.registerLabel} · 真人同文体结构腔基线 ${r.baseline}/千字`);
50
+ L.push(
51
+ `[具体] 每百字 ${r.scores.concretePer100} 个 · 抽象词 ${r.scores.abstract} · 评价词 ${r.scores.evaluation}`
52
+ );
53
+ L.push(
54
+ `[留白] ${r.scores.hedges} 个(${r.scores.hedgePer1k}/千字)` +
55
+ (r.scores.hedgePer1k < (r.thresholds?.hedgeFloor ?? 0.2) ? ' —— 句句在下断言' : '')
56
+ );
57
+ L.push(
58
+ `[结构腔] ${r.scores.structurePer1k}/千字 · 基线的 ${r.scores.overTimes} 倍 · ` +
59
+ `同百字最多 ${r.scores.clusterDistinct} 种句式`
60
+ );
61
+ if (r.synonyms && r.synonyms.length) {
62
+ L.push(`[同义轮换] ${r.synonyms.map((g) => g.join('/')).join(' · ')}`);
63
+ }
64
+ if (r.hits.structures.length) {
65
+ L.push('[逐处]');
66
+ for (const row of r.hits.structures) {
67
+ L.push(` · ${row.name} ×${row.count}:${row.spans.map((s) => `「${s.text}」`).join(' ')}`);
68
+ }
69
+ }
70
+ L.push('[要你自己答]');
71
+ for (const a of r.asks) L.push(` - ${a}`);
72
+ L.push(`[看不见] ${r.blind}`);
73
+ return L.join('\n');
74
+ }
75
+
76
+ /** 只要一句结论,最省。 */
77
+ export function renderBrief(r) {
78
+ const head = BAND[r.band] || r.bandLabel;
79
+ const bits = [];
80
+ if (r.hits.structures.length) bits.push(r.hits.structures[0].name);
81
+ if (r.hits.aiWords.length) bits.push(r.hits.aiWords[0].word);
82
+ return bits.length ? `${head}:${bits.join('、')}` : head;
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-bagu",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "八股检测:判断一句话是不是谁都能说。AI 味不是礼貌问题,是可替换问题。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -66,5 +66,8 @@
66
66
  "AI味",
67
67
  "八股",
68
68
  "写作"
69
- ]
69
+ ],
70
+ "devDependencies": {
71
+ "happy-dom": "^21.0.4"
72
+ }
70
73
  }
@@ -12,9 +12,14 @@ test('典型八股判成 heavy', () => {
12
12
  '本次修改已完成。首先调整了章节结构,其次新增了规则条款,最后优化了可读性。' +
13
13
  '综上所述,这次改动具有重要意义,希望对你有帮助。'
14
14
  );
15
- assert.equal(r.band, 'heavy');
16
- assert.ok(r.scores.aiWords >= 1);
17
- assert.ok(r.scores.structurePer1k > r.baseline * 3);
15
+ assert.ok(r.band === 'heavy' || r.band === 'mid', '实际 ' + r.band);
16
+ assert.ok(r.scores.aiWords >= 1, '该认出「综上所述」这类词');
17
+ });
18
+
19
+ test('「首先/其次」单独不再算结构腔(lieflat δ+0.02 失效)', () => {
20
+ const r = analyze('首先备份,其次改配置,最后重启。数据库密码记得先换掉,不然白改。');
21
+ const hasRoadmap = r.hits.structures.some((x) => x.id === 'roadmap');
22
+ assert.equal(hasRoadmap, false, 'roadmap 不该再出现在结构腔里');
18
23
  });
19
24
 
20
25
  test('具体的现场描述判成 low', () => {
@@ -111,13 +116,13 @@ test('#1.1 真正的标识符仍然计入', () => {
111
116
  assert.ok(ids.some((t) => t.includes('EADDRINUSE')));
112
117
  });
113
118
 
114
- test('#1.2 experience 和 sense 的权重高于 number 和 ident', () => {
115
- const a = concreteness('我昨天试了一下,手都酸了。');
116
- const b = concreteness('版本 1.2.3,路径 /a/b/c,端口 8080。');
117
- assert.ok(a.weighted > 0);
118
- assert.ok(b.weighted > 0);
119
- // a 是两条经历类,b 是两条数字/路径类,按权重 a 应该更高
120
- assert.ok(a.weighted >= b.weighted, `experience 权重不足: a=${a.weighted} b=${b.weighted}`);
119
+ test('#1.2 可核验的数字路径权重高于可编造的经历(方向修正)', () => {
120
+ // 上一版把 experience/sense 给到 1.5,理由是「难伪造」。
121
+ // 这是错的:经历最好编,三样凑齐就是模板。数字和路径可核验,反而该给分。
122
+ const fabricated = concreteness('我昨天试着改了一下,折腾到凌晨两点半才跑通,手都酸了。');
123
+ const real = concreteness('配置文件在 /etc/app/config.yml,端口 8080,版本 v1.4.2。');
124
+ assert.ok(real.weighted > fabricated.weighted,
125
+ `真实配置该比编造经历高: real=${real.weighted} fabricated=${fabricated.weighted}`);
121
126
  });
122
127
 
123
128
  test('#1.4 具体物充足时往回减一格', () => {
@@ -132,10 +137,16 @@ test('#1.4 具体物充足时往回减一格', () => {
132
137
  `具体的那段不该比空话更可疑: rich=${rich.scores.replaceable} empty=${empty.scores.replaceable}`);
133
138
  });
134
139
 
135
- test('#1.8 六十个字以下不给判档', () => {
136
- const r = analyze('这个挺好。');
137
- assert.equal(r.band, 'too-short');
138
- assert.ok(r.bandNote.includes('六十字'), 'bandNote: ' + r.bandNote);
140
+ test('短句走绝对计数,不看密度', () => {
141
+ const ai = analyze('这不是技术问题,而是认知问题。');
142
+ const human = analyze('卖卡卖完了随便写了');
143
+ assert.equal(ai.band, 'heavy', 'AI 对举应判可疑,实际 ' + ai.band);
144
+ assert.equal(human.band, 'low', '真人短评应判正常,实际 ' + human.band);
145
+ });
146
+
147
+ test('短句:同义轮换能被抓到', () => {
148
+ const r = analyze('我们使用了新方法,采用了更好的方式,通过提升效率来优化流程。');
149
+ assert.ok(r.synonyms.length >= 2, '应抓到多组轮换,实际 ' + JSON.stringify(r.synonyms));
139
150
  });
140
151
 
141
152
  test('#1.8 六十字以上照常判档', () => {
@@ -8,7 +8,7 @@ import vm from 'node:vm'
8
8
  const here = dirname(fileURLToPath(import.meta.url))
9
9
  const code = readFileSync(join(here, '..', 'client.js'), 'utf8')
10
10
 
11
- /** 把 client.js 跑在假沙箱里:window.__ModuleLoader__ + document + react 都是假的。 */
11
+ /** 假沙箱:document + React + __ModuleLoader__ 都是假的。 */
12
12
  function boot() {
13
13
  const loaded = []
14
14
  const styles = []
@@ -17,7 +17,7 @@ function boot() {
17
17
  createElement: () => ({ setAttribute() {}, remove() {}, textContent: '' }),
18
18
  }
19
19
  const React = {
20
- createElement: (type, props, ...kids) => ({ type, props, kids }),
20
+ createElement: (type, props, ...kids) => ({ type, props: props || {}, kids }),
21
21
  useState: (v) => [v, () => {}],
22
22
  useRef: (v) => ({ current: v }),
23
23
  useCallback: (f) => f,
@@ -34,41 +34,32 @@ function boot() {
34
34
  return { loaded, styles, React, document }
35
35
  }
36
36
 
37
- test('自注册脚本:id 等于包名', () => {
37
+ test('自注册:id 等于包名', () => {
38
38
  const { loaded } = boot()
39
- assert.equal(loaded.length, 1, '应该只 load 一次')
39
+ assert.equal(loaded.length, 1)
40
40
  assert.equal(loaded[0].id, 'dsh-bagu')
41
41
  })
42
42
 
43
- test('有 factory,且是函数', () => {
44
- const { loaded } = boot()
45
- assert.equal(typeof loaded[0].factory, 'function')
46
- })
47
-
48
43
  test('factory 返回 inject + apply', () => {
49
44
  const { loaded, React } = boot()
50
- const def = loaded[0].factory((m) => {
51
- if (m === 'react') return React
52
- throw new Error('unexpected require: ' + m)
53
- })
54
- // vm 沙箱里的数组原型和外面不同,逐项比
45
+ const def = loaded[0].factory(() => React)
55
46
  assert.equal(Array.from(def.inject).join(','), 'slots')
56
47
  assert.equal(typeof def.apply, 'function')
57
48
  })
58
49
 
59
- test('apply 会注入 CSS 并注册 settings.section', () => {
50
+ test('apply 注入 CSS 并注册 settings.section', () => {
60
51
  const { loaded, React, styles } = boot()
61
52
  const def = loaded[0].factory(() => React)
62
53
  const registered = []
63
54
  const ctx = {
64
55
  get: () => ({
65
- inject: (_slot, fn) => fn(),
56
+ inject: (_s, fn) => fn(),
66
57
  register: (meta, fn) => { registered.push({ meta, fn }); return () => {} },
67
58
  }),
68
59
  effect: (fn) => fn,
69
60
  }
70
61
  def.apply(ctx)
71
- assert.equal(styles.length, 1, '应该注入一份 CSS')
62
+ assert.equal(styles.length, 1)
72
63
  assert.equal(registered.length, 1)
73
64
  assert.equal(registered[0].meta.name, 'settings.section')
74
65
  assert.equal(registered[0].meta.id, 'bagu')
@@ -80,10 +71,36 @@ test('没有 slots 时不炸', () => {
80
71
  const def = loaded[0].factory(() => React)
81
72
  const ctx = { get: () => ({}), effect: (fn) => fn }
82
73
  assert.doesNotThrow(() => def.apply(ctx))
83
- assert.equal(styles.length, 1, 'CSS 还是要注入')
74
+ assert.equal(styles.length, 1)
84
75
  })
85
76
 
86
- test('register 的槽函数返回 Panel 元素', () => {
77
+ test('CSS 只引用真实存在的 --dsw-alias-* 变量', () => {
78
+ const { loaded, React } = boot()
79
+ const def = loaded[0].factory(() => React)
80
+ const ctx = { get: () => ({}), effect: (fn) => fn }
81
+ def.apply(ctx)
82
+ // 从 dsh-m 的 client bundle 里核对过的可用变量
83
+ const KNOWN = new Set([
84
+ '--dsw-alias-bg-base', '--dsw-alias-bg-elevated', '--dsw-alias-bg-hover',
85
+ '--dsw-alias-fill-secondary', '--dsw-alias-interactive-bg-hover',
86
+ '--dsw-alias-interactive-bg-selected', '--dsw-alias-border-l',
87
+ '--dsw-alias-border-default', '--dsw-alias-label-primary',
88
+ '--dsw-alias-label-secondary', '--dsw-alias-label-tertiary',
89
+ '--dsw-alias-label-caption', '--dsw-alias-label-dimmed',
90
+ '--dsw-alias-state-business-primary', '--dsw-alias-state-business-tertiary',
91
+ '--dsw-alias-state-error-primary', '--dsw-alias-state-error-secondary',
92
+ ])
93
+ const used = [...code.matchAll(/var\((--dsw-alias-[a-z-]+)/g)].map((m) => m[1])
94
+ const unknown = [...new Set(used)].filter((v) => !KNOWN.has(v))
95
+ assert.deepEqual(unknown, [], '用到了不存在的变量: ' + unknown.join(', '))
96
+ })
97
+
98
+ test('CSS 每个 var() 都有回退值', () => {
99
+ const bad = [...code.matchAll(/var\((--[a-z-]+)\)/g)].map((m) => m[1])
100
+ assert.deepEqual(bad, [], '缺回退值: ' + bad.join(', '))
101
+ })
102
+
103
+ test('槽里渲染的是 Panel', () => {
87
104
  const { loaded, React } = boot()
88
105
  const def = loaded[0].factory(() => React)
89
106
  const registered = []
@@ -96,16 +113,25 @@ test('register 的槽函数返回 Panel 元素', () => {
96
113
  }
97
114
  def.apply(ctx)
98
115
  const el = registered[0].fn()
99
- assert.equal(typeof el, 'object')
100
- assert.equal(el.type.name, 'Panel', '槽里渲染的应该是 Panel')
101
- })
102
-
103
- test('API 前缀是 /api/bagu', () => {
104
- assert.ok(code.includes("'/api/bagu'"), 'client 必须打 /api/bagu')
116
+ assert.equal(el.type.name, 'Panel')
105
117
  })
106
118
 
107
- test('三个接口都用上了:status / config / preview', () => {
119
+ test('接口是 /api/bagu 的三条', () => {
120
+ assert.ok(code.includes("'/api/bagu'"))
108
121
  assert.ok(code.includes("jget('/status')"))
109
122
  assert.ok(code.includes("jpost('/config'"))
110
123
  assert.ok(code.includes("jpost('/preview'"))
111
124
  })
125
+
126
+ test('preview 会带 full 开关', () => {
127
+ assert.ok(code.includes('{ text, full }'), 'preview 请求体里要带 full')
128
+ })
129
+
130
+ test('没写死颜色值,只允许纯白', () => {
131
+ // DSH 的设计变量里没有反色文字(没有 --dsw-alias-label-inverse 之类),
132
+ // 所以蓝底按钮上的白字和开关圆点的白点只能写 #fff。白是唯一安全的中性色。
133
+ const stray = [...code.matchAll(/(?:^|[;\s])(?:color|background)\s*:\s*(#[0-9a-fA-F]{3,8})/g)]
134
+ .map((m) => m[1].toLowerCase())
135
+ .filter((hex) => hex !== '#fff' && hex !== '#ffffff')
136
+ assert.deepEqual(stray, [], '写死的颜色: ' + stray.join(', '))
137
+ })