cortico-world-extra-actions 0.3.30 → 0.3.32

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.
@@ -44,7 +44,8 @@
44
44
  "c3": "#5fbfa0",
45
45
  "c4": "#9a9aa0"
46
46
  }
47
- }
47
+ },
48
+ "pick": {}
48
49
  }
49
50
  ],
50
51
  "vocab": [],
package/dist/webui.js CHANGED
@@ -199,6 +199,8 @@ const CSS = `<style>
199
199
  .ea-onboard-box{max-width:420px;background:var(--ea-bg);border:1px solid var(--ea-line2);padding:16px 18px;
200
200
  box-shadow:0 24px 48px -20px rgba(0,0,0,.5)}
201
201
  .ea-onboard-box b{display:block;font-size:14px;margin-bottom:6px}
202
+ /* 正文里的 <b> 是行内强调(段数/数字),别被上面那条撑成块级 */
203
+ .ea-onboard-box p b{display:inline;font-size:inherit;font-weight:600;margin:0}
202
204
  .ea-onboard-box p{margin:0 0 8px;font-size:12.5px;line-height:1.7;color:var(--ea-soft)}
203
205
  .ea-onboard-box p.ea-dim{color:var(--ea-dim);font-size:11.5px}
204
206
  .ea-onboard-acts{display:flex;gap:8px;justify-content:flex-end;margin-top:12px}
@@ -362,6 +364,7 @@ const panel = {
362
364
  <details class="ea-menu" data-role="libmenu">
363
365
  <summary class="ea-btn" title="动作库可以放在任意盘,路径会被记住">动作库</summary>
364
366
  <div class="ea-menu-body">
367
+ <button type="button" data-act="download-library" title="插件自己下载、自己装好(约 370 MB)">一键下载并安装</button>
365
368
  <button type="button" data-act="library" title="手动指一个已有的动作库目录">选择动作库位置…</button>
366
369
  <button type="button" data-act="find-libs" title="自动扫一遍本机像动作库的目录,列出来点一下就用">自动寻找动作库…</button>
367
370
  <button type="button" data-act="starter-library" title="在你会选的目录下建一个自带示例动作库(3 段)并设为当前库">用自带示例建库…</button>
@@ -369,7 +372,7 @@ const panel = {
369
372
  <div class="hint" data-role="libhint">当前库见右下方状态行</div>
370
373
  </div>
371
374
  </details>
372
- <button class="ea-btn" data-act="restore-pack" title="建一个空的角色包(只有身体状态),位置自己选">建立空的角色包(选位置)</button>
375
+ <button class="ea-btn" data-act="restore-pack" data-role="restore-btn" title="建一个空的角色包(只有身体状态),位置自己选">建立空的角色包(选位置)</button>
373
376
  <span class="ea-lib" data-role="lib"></span>
374
377
  </div>
375
378
  <div class="ea-pin">
@@ -414,7 +417,7 @@ const panel = {
414
417
  <div class="ea-onboard" data-role="onboard" hidden>
415
418
  <div class="ea-onboard-box">
416
419
  <b>完整动作库还没下载</b>
417
- <p>插件自带 <b data-role="onboard-have">若干</b> 段示例动作。完整库有 <b data-role="onboard-count">105</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。</p>
420
+ <p data-role="onboard-lead">插件自带 <b data-role="onboard-have">若干</b> 段示例动作。完整库有 <b data-role="onboard-count">105</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。</p>
418
421
  <p>下载之前,列表里那些<b>灰色的行</b>就是还没装进动作库的段 —— 灰色只代表「没下载」,不是坏了;下载完就会变成可勾选。</p>
419
422
  <p class="ea-dim" data-role="onboard-note">下载地址由维护者提供,拿到后这里会出现「去下载」按钮;也可以自己放好库,用「动作库」菜单里的「选择动作库位置…」指过去。</p>
420
423
  <div class="ea-onboard-acts">
@@ -580,6 +583,12 @@ const panel = {
580
583
  || (catalog?.actions ?? []).reduce((sum, a) => sum + (a.bytes || 0), 0);
581
584
  const setTxt = (sel, v) => { const node = wrap.querySelector(sel); if (node) node.textContent = String(v); };
582
585
  if (totalSeg) setTxt('[data-role=onboard-count]', totalSeg);
586
+ const lead = wrap.querySelector('[data-role=onboard-lead]');
587
+ if (lead) {
588
+ lead.innerHTML = haveSeg
589
+ ? `动作库里现在有 <b data-role="onboard-have">${haveSeg}</b> 段,完整的有 <b data-role="onboard-count">${totalSeg || 105}</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。`
590
+ : `<b>你还没设置动作库</b>,所以列表里一段都没有。完整的有 <b data-role="onboard-count">${totalSeg || 105}</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。`;
591
+ }
583
592
  setTxt('[data-role=onboard-have]', haveSeg);
584
593
  if (totalBytes) setTxt('[data-role=onboard-size]', Math.round(totalBytes / 1048576));
585
594
  onboardEl.hidden = false;
@@ -949,6 +958,22 @@ const panel = {
949
958
  }
950
959
  }
951
960
 
961
+ /** 已经有深深包时,这个按钮变成「修复」—— 避免用户以为可以再建一个新的。 */
962
+ function syncRestoreBtn() {
963
+ const btn = wrap.querySelector('[data-role=restore-btn]');
964
+ if (!btn) return;
965
+ const have = (Array.isArray(state?.figures) ? state.figures : []).find((f) => f && f.id === 'shenshen-actions');
966
+ if (have) {
967
+ btn.textContent = '修复深深形象包';
968
+ btn.title = `已经有深深的形象包了:${have.dir ?? ''}。点它会补齐缺的文件,不会重复创建。`;
969
+ btn.classList.remove('pri');
970
+ } else {
971
+ btn.textContent = '建立空的角色包(选位置)';
972
+ btn.title = '建一个空的角色包(只有身体状态),位置自己选';
973
+ btn.classList.add('pri');
974
+ }
975
+ }
976
+
952
977
  function renderNote() {
953
978
  const p = pack();
954
979
  noteEl.hidden = true;
@@ -969,11 +994,25 @@ const panel = {
969
994
  + '<span class="ea-dim">或者只补某一段:点那一行右侧的「↓ 下载」</span>'
970
995
  + '</div>';
971
996
  };
997
+ // 清单不合规:宿主根本不会加载这个包(界面上就是"形象列表里没有它")
998
+ if (p.problem) {
999
+ noteEl.hidden = false;
1000
+ noteEl.className = 'ea-note bad';
1001
+ noteEl.innerHTML = `<b>这个形象包装不上:</b>${esc(p.problem)}。<br>`
1002
+ + '宿主会因为这条不加载整个包 —— 点右边的「修复深深形象包」,插件会把能自动修的补上(会先备份)。';
1003
+ return;
1004
+ }
1005
+
972
1006
  if (!state.library.ok) {
973
1007
  noteEl.hidden = false;
1008
+ if (!state.library.dir) {
1009
+ // 从没设过库:这是"还没开始",不是出错
1010
+ noteEl.className = 'ea-note';
1011
+ noteEl.innerHTML = `<b>还没选动作库。</b>要全部 105 段:点上面「动作库 ▾」→<b>一键下载并安装</b>;已经有库就「动作库 ▾」→「选择动作库位置…」指过去。`;
1012
+ return;
1013
+ }
974
1014
  noteEl.className = 'ea-note bad';
975
- noteEl.innerHTML = `动作库目录没找到:<code>${esc(state.library.dir || '未设置')}</code> —— 点上面的「动作库」菜单:自动寻找,或手动选位置。`
976
- + `<br>清单里的 ${state.library.count ?? 105} 段现在都算「还没下载」—— 先在上面选好动作库位置,再下载。`;
1015
+ noteEl.innerHTML = `动作库目录读不到:<code>${esc(state.library.dir)}</code> —— 可能被移动或删了。用「动作库 ▾」重新指一下,或直接「一键下载并安装」。`;
977
1016
  return;
978
1017
  }
979
1018
  if (!p) {
@@ -1035,6 +1074,7 @@ const panel = {
1035
1074
  : '当前还没设置动作库 —— 选「自动寻找动作库…」或「选择动作库位置…」';
1036
1075
  }
1037
1076
  maybeOnboard();
1077
+ syncRestoreBtn();
1038
1078
  renderPack(); renderShowAll(); renderChips(); renderList(); renderInstalled(); renderSum(); renderNote(); fitFoot();
1039
1079
  }
1040
1080
 
@@ -1067,7 +1107,7 @@ const panel = {
1067
1107
  const act = btn.dataset.act;
1068
1108
  // 「动作库 ▾」里点完就收起来,别让菜单挂在打开对话框后面
1069
1109
  const libMenu = wrap.querySelector('[data-role=libmenu]');
1070
- if (libMenu && (act === 'library' || act === 'find-libs' || act === 'starter-library')) libMenu.open = false;
1110
+ if (libMenu && (act === 'library' || act === 'find-libs' || act === 'starter-library' || act === 'download-library')) libMenu.open = false;
1071
1111
  const busy = (on) => { for (const b of wrap.querySelectorAll('button')) b.disabled = on; };
1072
1112
  try {
1073
1113
  if (act === 'onboard-dismiss') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-extra-actions",
3
- "version": "0.3.30",
3
+ "version": "0.3.32",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "勾选动作库里的动作,写进形象包的「额外动作拓展」文件夹,让桌宠照着做。自带入门形象包(含控制台配色)与示例动作;完整 105 段可一键下载安装。",
package/src/pet.js CHANGED
@@ -1,6 +1,14 @@
1
1
  /** Coopanion 本地桌宠服务的最小客户端(127.0.0.1:7797-7806)。 */
2
2
 
3
- const PORTS = Array.from({ length: 10 }, (_, i) => 7797 + i);
3
+ const DEFAULT_PORTS = Array.from({ length: 10 }, (_, i) => 7797 + i);
4
+ /** 自测 / 隔离模拟:COOPANION_PET_OFF=1 彻底不探;COOPANION_PET_PORTS=7797,7798 指定端口。 */
5
+ const PORTS = (() => {
6
+ const raw = process.env.COOPANION_PET_PORTS;
7
+ if (!raw) return DEFAULT_PORTS;
8
+ const list = raw.split(',').map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0 && x < 65536);
9
+ return list.length ? list : DEFAULT_PORTS;
10
+ })();
11
+ const PET_OFF = process.env.COOPANION_PET_OFF === '1';
4
12
  let origin = null;
5
13
 
6
14
  const withTimeout = (p, ms) => Promise.race([
@@ -9,6 +17,7 @@ const withTimeout = (p, ms) => Promise.race([
9
17
  ]);
10
18
 
11
19
  export async function findPet() {
20
+ if (PET_OFF) throw new Error('COOPANION_PET_OFF=1(自测模式,不连桌宠)');
12
21
  if (origin) return origin;
13
22
  for (const port of PORTS) {
14
23
  try {
package/src/starter.js CHANGED
@@ -34,15 +34,104 @@ export function safePackName(name) {
34
34
  }
35
35
 
36
36
  /** 这个包里该有的东西齐不齐(`id` 是这个包应有的 id)。 */
37
+ /**
38
+ * 宿主能不能加载这份 figure.json。返回 null = 没问题,否则一句人话。
39
+ *
40
+ * 为什么插件自己也要判:宿主是「一条不合格 → 整个包不加载」,界面上就是
41
+ * "形象列表里没有它";这时候用户点「修复」必须真的能修好,而不是被判为健康。
42
+ * 只查最容易写错、且我们能自动修的那几条(其余交给 tools/manifest-check.mjs)。
43
+ */
44
+ /** 导出版:世界层要给每个形象包标「宿主会不会加载它」。 */
45
+ export function manifestProblem(fig) {
46
+ if (!fig || typeof fig !== 'object') return 'figure.json 读不出来';
47
+ if (![1, 2].includes(fig.manifest)) return 'manifest 不是 1/2';
48
+ if (![1, 2].includes(fig.api)) return 'api 不是 1/2';
49
+ if (typeof fig.id !== 'string' || !SAFE_ID.test(fig.id)) return 'id 不合法';
50
+ if (!fig.name || typeof fig.name !== 'object') return '缺 name';
51
+ if (typeof fig.entry !== 'string' || !fig.entry) return '缺 entry';
52
+ if (typeof fig.export !== 'string' || !fig.export) return '缺 export';
53
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
54
+ if (!p || typeof p !== 'object' || typeof p.id !== 'string') return 'preset 缺 id';
55
+ if (!p.pick || typeof p.pick !== 'object') return `preset "${p.id}" 缺 pick`;
56
+ }
57
+ const BREAK = /[,,、\s【】<><>]/;
58
+ const taken = new Set();
59
+ for (const w of Array.isArray(fig.vocab) ? fig.vocab : []) {
60
+ const id = String(w?.id ?? '');
61
+ if (!SAFE_ID.test(id)) return `vocab id 不合法: ${id}`;
62
+ for (const list of Object.values(w?.names ?? {})) {
63
+ for (const name of Array.isArray(list) ? list : []) {
64
+ if (typeof name !== 'string' || !name.trim() || name.length > 32 || BREAK.test(name)) return `vocab 名字不合法: ${id}`;
65
+ }
66
+ }
67
+ for (const name of [id, ...Object.values(w?.names ?? {}).flat()]) {
68
+ if (taken.has(name)) return `vocab 名字重复: ${name}`;
69
+ taken.add(name);
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /** 宿主要求的必备字段;缺了就补默认值(否则整包不加载)。 */
76
+ function ensureBasics(fig, id) {
77
+ let changed = 0;
78
+ const set = (k, v) => { if (fig[k] === undefined || fig[k] === null || fig[k] === '') { fig[k] = v; changed++; } };
79
+ set('manifest', 2);
80
+ set('api', 2);
81
+ set('version', '1.0.0');
82
+ set('entry', 'figure.js');
83
+ set('export', 'createActionBody');
84
+ if (!fig.name || typeof fig.name !== 'object') { fig.name = { zh: '深深 · 动作库', en: 'Shenshen · Action library' }; changed++; }
85
+ if (!fig.about || typeof fig.about !== 'object') { fig.about = { zh: '深深的动作库形象包' }; changed++; }
86
+ if (!Array.isArray(fig.axes)) { fig.axes = []; changed++; }
87
+ if (!Array.isArray(fig.presets)) { fig.presets = []; changed++; }
88
+ if (!Array.isArray(fig.vocab)) { fig.vocab = []; changed++; }
89
+ if (fig.id !== id) { fig.id = id; changed++; }
90
+ return changed;
91
+ }
92
+
93
+ /** 把已知能自动修的问题就地修掉:缺基本信息、preset 缺 pick、vocab 名字带禁字符。 */
94
+ function repairManifestLight(fig, id = PACK_ID) {
95
+ let changed = ensureBasics(fig, id);
96
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
97
+ if (p && typeof p === 'object' && (!p.pick || typeof p.pick !== 'object')) { p.pick = {}; changed++; }
98
+ }
99
+ // console 若有但缺色(早期写过空对象),用默认青绿补齐
100
+ const DEFAULT_HUES = {
101
+ light: { a: '#0b7a5a', a2: '#0f9d76', on: '#ffffff', t: '#0b6b4f', c3: '#3f8f78', c4: '#8a8a90' },
102
+ dark: { a: '#2fd3a0', a2: '#7fe6c2', on: '#062a20', t: '#8ae8c6', c3: '#5fbfa0', c4: '#9a9aa0' },
103
+ };
104
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
105
+ if (!p || typeof p !== 'object' || !p.console || typeof p.console !== 'object') continue;
106
+ for (const mode of ['light', 'dark']) {
107
+ if (!p.console[mode] || typeof p.console[mode] !== 'object') { p.console[mode] = { ...DEFAULT_HUES[mode] }; changed++; continue; }
108
+ for (const [k, v] of Object.entries(DEFAULT_HUES[mode])) {
109
+ if (typeof p.console[mode][k] !== 'string' || !/^#[0-9a-f]{6}$/i.test(p.console[mode][k])) { p.console[mode][k] = v; changed++; }
110
+ }
111
+ }
112
+ }
113
+ const BREAK = /[,,、\s【】<><>]/g;
114
+ for (const w of Array.isArray(fig.vocab) ? fig.vocab : []) {
115
+ for (const [lang, list] of Object.entries(w?.names ?? {})) {
116
+ if (!Array.isArray(list)) continue;
117
+ const next = list.map((raw) => String(raw ?? '').replace(BREAK, '').trim().slice(0, 32) || String(w.id ?? ''));
118
+ if (JSON.stringify(next) !== JSON.stringify(list)) { w.names[lang] = next; changed++; }
119
+ }
120
+ }
121
+ return changed;
122
+ }
123
+
37
124
  function packHealth(dir, id = PACK_ID) {
38
125
  const fig = readJson(join(dir, 'figure.json'), null);
39
126
  const states = ['state-idle', 'state-walk', 'state-drag', 'look-around']
40
127
  .filter((s) => existsSync(join(dir, 'actions', 'core', s, 'action.json')));
128
+ const problem = fig && fig.id === id ? manifestProblem(fig) : 'figure.json 缺失或 id 不对';
41
129
  return {
42
130
  figureJson: !!fig && fig.id === id,
43
131
  player: existsSync(join(dir, 'figure.js')),
44
132
  states,
45
- ok: !!fig && fig.id === id && existsSync(join(dir, 'figure.js')) && states.length === 4,
133
+ problem,
134
+ ok: !!fig && fig.id === id && existsSync(join(dir, 'figure.js')) && states.length === 4 && !problem,
46
135
  };
47
136
  }
48
137
 
@@ -69,6 +158,7 @@ function materialize(src, dst, id, log) {
69
158
  cpSync(src, dst, { recursive: true, force: false, errorOnExist: false });
70
159
  rmSync(join(dst, '额外动作拓展'), { recursive: true, force: true });
71
160
  const fig = readJson(join(dst, 'figure.json'), { id });
161
+ ensureBasics(fig, id);
72
162
  fig.id = id;
73
163
  fig.vocab = [];
74
164
  writeFileSync(join(dst, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
@@ -140,12 +230,21 @@ export function restorePack({ pkgDir, figuresDir, roots, target = '', name = PAC
140
230
  const duplicates = found.filter((p) => resolve(p.path) !== resolve(dst)).map((p) => p.path);
141
231
 
142
232
  if (existsSync(join(dst, 'figure.json'))) {
233
+ const healthyBefore = packHealth(dst, id).ok;
234
+ // 先去修「能自动修」的那类毛病(preset 缺 pick / 词表名字带禁字符),再判健康
235
+ {
236
+ const fig = readJson(join(dst, 'figure.json'), null);
237
+ if (fig && repairManifestLight(fig) > 0) {
238
+ writeFileSync(join(dst, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
239
+ log?.('修好了形象包清单里的小问题(宿主本来会拒绝加载)');
240
+ }
241
+ }
143
242
  const before = packHealth(dst, id);
144
243
  if (!before.ok) repairInto(src, dst, id, before, log);
145
244
  const after = packHealth(dst, id);
146
245
  log?.(`形象包已存在,未重复创建:${dst}`);
147
246
  return {
148
- ok: true, created: false, repaired: !before.ok && after.ok,
247
+ ok: true, created: false, repaired: !healthyBefore && after.ok,
149
248
  path: dst, dir: basename(dst), root: rootOf(dst), duplicates, health: after,
150
249
  };
151
250
  }
@@ -161,12 +260,21 @@ export function restorePack({ pkgDir, figuresDir, roots, target = '', name = PAC
161
260
  const canonical = found.find((p) => p.dir === id) ?? null;
162
261
  const others = found.filter((p) => p.dir !== id);
163
262
  const t = canonical ?? found[0];
164
- const before = t.bot;
263
+ const healthyBefore = t.bot.ok;
264
+ // 先修「清单里能自动补的」(基本信息 / preset.pick / 词表名字),再补缺文件
265
+ {
266
+ const fig = readJson(join(t.path, 'figure.json'), null);
267
+ if (fig && repairManifestLight(fig, id) > 0) {
268
+ writeFileSync(join(t.path, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
269
+ log?.('修好了形象包清单里的小问题(宿主本来会拒绝加载)');
270
+ }
271
+ }
272
+ const before = packHealth(t.path, id);
165
273
  if (!before.ok) repairInto(src, t.path, id, before, log);
166
274
  const after = packHealth(t.path, id);
167
275
  log?.(`形象包已存在,未重复创建:${t.path}`);
168
276
  return {
169
- ok: true, created: false, repaired: !before.ok && after.ok,
277
+ ok: true, created: false, repaired: !healthyBefore && after.ok,
170
278
  path: t.path, dir: t.dir, root: t.root ?? primary,
171
279
  duplicates: others.map((p) => p.path), health: after,
172
280
  };
@@ -293,7 +401,18 @@ export function ensureConsolePreset(packDir, log) {
293
401
  const fig = readJson(figFile, null);
294
402
  if (!fig || fig.id !== PACK_ID) return { changed: false, reason: 'not-our-pack' };
295
403
  const presets = Array.isArray(fig.presets) ? fig.presets : [];
296
- if (presets.some((p) => p && p.console)) return { changed: false, reason: 'already-has-console' };
404
+ // 预设必须带 pick(宿主 packs.ts:330),缺了整包不加载 → 先补
405
+ let repaired = 0;
406
+ for (const p of presets) {
407
+ if (p && typeof p === 'object' && (!p.pick || typeof p.pick !== 'object')) { p.pick = {}; repaired++; }
408
+ }
409
+ if (repaired) {
410
+ const bak = join(packDir, 'figure.json.bak-配色2');
411
+ if (!existsSync(bak)) writeFileSync(bak, readFileSync(figFile, 'utf8'), 'utf8');
412
+ writeFileSync(figFile, JSON.stringify(fig, null, 2) + '\n', 'utf8');
413
+ log?.('补上了形象包里缺失的 preset.pick(缺它整包都不会加载)');
414
+ }
415
+ if (presets.some((p) => p && p.console)) return { changed: repaired > 0, reason: repaired ? 'repaired-pick' : 'already-has-console' };
297
416
  if (presets.some((p) => p && p.id === CONSOLE_PRESET.id)) return { changed: false, reason: 'id-taken' };
298
417
 
299
418
  const backup = join(packDir, 'figure.json.bak-配色');
@@ -307,6 +426,7 @@ export function ensureConsolePreset(packDir, log) {
307
426
  /** 深深包的配色预设(对比度:浅色 on-accent 5.3:1、t/纸面 6.3:1;深色 8.1:1 / 11.4:1)。 */
308
427
  export const CONSOLE_PRESET = {
309
428
  "id": "teal",
429
+ "pick": {},
310
430
  "name": {
311
431
  "zh": "深深 · 青绿",
312
432
  "zh-Hant": "深深 · 青綠",
package/src/world.js CHANGED
@@ -13,7 +13,7 @@ import { basename, delimiter, dirname, isAbsolute, join, normalize, resolve } fr
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { EXTRA_DIR, clear, inspect, isInside, packLooksSupported, prunePack, readExtra, removeOne, save } from './writer.js';
15
15
  import { addModules, rebuildIndex, scanLibrary } from './importer.js';
16
- import { ensureConsolePreset, ensurePlayer, ensureStarter, ensureVocabNames, installStarterLibrary, libraryHealth, restorePack, safePackName } from './starter.js';
16
+ import { ensureConsolePreset, ensurePlayer, ensureStarter, ensureVocabNames, manifestProblem, installStarterLibrary, libraryHealth, restorePack, safePackName } from './starter.js';
17
17
  import { FALLBACK_ACTION_BASE, FALLBACK_LIBRARY, LIB_PARTS, actionUrl, flatActionUrl, installAction, installLibrary, installLibraryParts, libraryUrl } from './online.js';
18
18
  import { petFigures, petState } from './pet.js';
19
19
 
@@ -313,7 +313,11 @@ export class ExtraActionsWorld {
313
313
  const dirs = this.packDirs();
314
314
  for (const p of installed) {
315
315
  const hit = dirs.get(String(p.id));
316
- const packDir = hit?.dir ?? join(dir, String(p.id));
316
+ const guessed = hit?.dir ?? join(dir, String(p.id));
317
+ // 桌宠列出来、但本地根本没有这个目录(另一个数据目录 / 别的盘):不要凭空造条目,
318
+ // 否则面板会给出一个"可修复"的假包,点下去只会报错。
319
+ if (!hit && !existsSync(join(guessed, 'figure.json'))) continue;
320
+ const packDir = guessed;
317
321
  const supported = packLooksSupported(packDir);
318
322
  const extra = readExtra(packDir);
319
323
  out.push({
@@ -322,6 +326,8 @@ export class ExtraActionsWorld {
322
326
  current: p.id === current,
323
327
  builtin: p.removable === false,
324
328
  supported,
329
+ // 宿主对清单是一票否决:有问题它整包不加载,面板得说出来
330
+ problem: (() => { try { return packLooksSupported(packDir) ? manifestProblem(JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8').replace(/^\uFEFF/, ''))) : null; } catch { return null; } })(),
325
331
  dir: packDir,
326
332
  root: hit?.root ?? dir,
327
333
  extra: { ids: extra.ids, count: extra.ids.length, bytes: extra.bytes, updatedAt: extra.updatedAt },
@@ -337,6 +343,7 @@ export class ExtraActionsWorld {
337
343
  current: id === current,
338
344
  builtin: false,
339
345
  supported: packLooksSupported(hit.dir),
346
+ problem: (() => { try { return manifestProblem(hit.fig); } catch { return null; } })(),
340
347
  dir: hit.dir,
341
348
  root: hit.root,
342
349
  extra: { ids: extra.ids, count: extra.ids.length, bytes: extra.bytes, updatedAt: extra.updatedAt },
@@ -667,12 +674,19 @@ export class ExtraActionsWorld {
667
674
  }
668
675
  if (!info.libraryUrl) throw new Error('还没配置下载源');
669
676
  this._dl = { active: true, phase: 'zip', done: 0, total: 1, bytes: 0, totalBytes: 0, startedAt: Date.now() };
670
- const r = await installLibrary({
671
- url: info.libraryUrl,
672
- libraryDir: existing,
673
- dataDir: this.dataDir,
674
- log: (m) => this.host?.log?.info?.(m),
675
- });
677
+ let r;
678
+ try {
679
+ r = await installLibrary({
680
+ url: info.libraryUrl,
681
+ libraryDir: existing,
682
+ dataDir: this.dataDir,
683
+ log: (m) => this.host?.log?.info?.(m),
684
+ });
685
+ } catch (e) {
686
+ // 整包也失败:进度必须回到"不活跃",否则面板会一直显示"正在连接下载源…"
687
+ this._dl = { ...this._dl, active: false, phase: 'error', error: String(e?.message ?? e) };
688
+ throw e;
689
+ }
676
690
  this.saveSettings({ libraryDir: r.path });
677
691
  this.bustCatalog();
678
692
  this._dl = { ...(this._dl ?? {}), active: false, phase: 'done', modules: r.modules, bytes: r.bytes };
package/src/writer.js CHANGED
@@ -623,7 +623,19 @@ export function prunePack(packDir) {
623
623
  const dir = join(actionsDir, cat.name, mod.name);
624
624
  if (!isInside(actionsDir, dir)) continue;
625
625
  const meta = readJson(join(dir, 'action.json'), null);
626
- if (!meta) continue; // 没有 action.json 的不动
626
+ if (!meta) {
627
+ // 没有 action.json:只有在它确实是我们留下的素材目录(有 anim.webp / f_*.webp)时才清,
628
+ // 别的(用户自己放的东西)一律不动。
629
+ let names = [];
630
+ try { names = readdirSync(dir); } catch { continue; }
631
+ const ours = names.includes('anim.webp') || names.some((n) => /^f_\d{4}\.webp$/.test(n));
632
+ if (!ours) continue;
633
+ const bytes0 = dirBytes(dir);
634
+ rmSync(dir, { recursive: true, force: true });
635
+ removed.push(`${cat.name}/${mod.name}`);
636
+ freed += bytes0;
637
+ continue;
638
+ }
627
639
  const hasRole = Array.isArray(meta.roles) && meta.roles.length > 0;
628
640
  if (hasRole) { keep.add(meta.id ?? mod.name); continue; }
629
641
  const bytes = dirBytes(dir);
@@ -645,18 +657,21 @@ export function inspect({ packDir, libraryDir, catalog }) {
645
657
  const problems = [];
646
658
  if (!existsSync(join(packDir, 'figure.json'))) problems.push(`包里没有 figure.json:${packDir}`);
647
659
  if (!libraryDir || !existsSync(libraryDir)) problems.push(`动作库目录不存在:${libraryDir}`);
660
+ const extra = readExtra(packDir);
661
+ // 只检查"这个包里真的勾了的那些段":库不全(105 少几段)是库自己的事,
662
+ // 由 state.library.present / missing 单独报,不该把包判成不健康。
663
+ const byId = new Map(catalog.map((a) => [a.id, a]));
648
664
  const missing = [];
649
- for (const a of catalog) {
650
- // 身体状态段(idle / walk / drag / turn)没有触发词,它们不是"可加的动作"
651
- if (!a.word) continue;
652
- if (actionProblem(a)) { missing.push(a.id); continue; }
665
+ for (const id of extra.ids) {
666
+ const a = byId.get(id);
667
+ if (!a || !a.word) { missing.push(id); continue; }
668
+ if (actionProblem(a)) { missing.push(id); continue; }
653
669
  const dir = join(libraryDir || '', 'actions', a.category, a.id);
654
- if (!existsSync(dir)) { missing.push(a.id); continue; }
670
+ if (!existsSync(dir)) { missing.push(id); continue; }
655
671
  // 单文件动画模块(anim.webp):帧数在文件里,不能按 f_NNNN 数
656
672
  if (a.anim || existsSync(join(dir, 'anim.webp'))) continue;
657
- if (countFrames(dir) !== a.frames) missing.push(a.id);
673
+ if (countFrames(dir) !== a.frames) missing.push(id);
658
674
  }
659
- const extra = readExtra(packDir);
660
675
  return {
661
676
  ok: problems.length === 0 && missing.length === 0,
662
677
  problems,
@@ -0,0 +1,128 @@
1
+ /**
2
+ * 形象包清单体检:把 figure.json 按宿主 readManifest() 的规则过一遍。
3
+ * node manifest-check.mjs <形象包目录> [更多目录…]
4
+ *
5
+ * 宿主(cortico-world-desktop-pet/packs.ts)对清单是「一条不合格 → 整个包不加载」,
6
+ * 界面上就表现为"形象列表里没有这个包",还会让人以为可以再建一个。
7
+ * 这里把最容易踩的几条静态查出来:
8
+ * - manifest / api 的范围
9
+ * - id / entry / export / thumb
10
+ * - axes:id、name、options[].id 与 name
11
+ * - presets:**必须有 pick 对象**,且 pick 要覆盖每个 axis、值必须是该 axis 的某个 option
12
+ * - vocab / sounds 交给 doctor.mjs 的词表检查
13
+ */
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { join, resolve } from 'node:path';
16
+
17
+ const ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
18
+ const OPTION_ID = /^[a-z0-9][a-z0-9_-]{0,31}$/i;
19
+ const NAME_BREAK = /[,,、\s【】<><>]/;
20
+
21
+ const namesOf = (v) => (v && typeof v === 'object' ? Object.values(v).some((x) => typeof x === 'string' && x.trim()) : false);
22
+
23
+ export function checkManifest(dir) {
24
+ const file = join(dir, 'figure.json');
25
+ if (!existsSync(file)) return [`没有 figure.json`];
26
+ let raw;
27
+ try { raw = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); } catch (e) { return [`figure.json 不是合法 JSON:${e.message}`]; }
28
+ const out = [];
29
+ for (const [key, oldest, now] of [['manifest', 1, 2], ['api', 1, 2]]) {
30
+ const v = raw[key];
31
+ if (typeof v !== 'number' || !Number.isInteger(v)) { out.push(`${key} 不是整数:${JSON.stringify(v)}`); continue; }
32
+ if (v > now) out.push(`${key} 比宿主新(${v} > ${now})`);
33
+ if (v < oldest) out.push(`${key} 太老(${v} < ${oldest})`);
34
+ }
35
+ if (typeof raw.id !== 'string' || !ID.test(raw.id)) out.push(`id 不合法:${JSON.stringify(raw.id)}`);
36
+ if (!namesOf(raw.name)) out.push('缺 name');
37
+ if (!namesOf(raw.about)) out.push('缺 about');
38
+ if (typeof raw.entry !== 'string' || !raw.entry) out.push('缺 entry');
39
+ if (typeof raw.export !== 'string' || !raw.export) out.push('缺 export');
40
+ if (typeof raw.entry === 'string' && raw.entry) {
41
+ const entryFile = join(dir, raw.entry);
42
+ if (!existsSync(entryFile)) out.push(`entry 指向的文件不存在:${raw.entry}`);
43
+ else if (typeof raw.export === 'string' && raw.export) {
44
+ const js = readFileSync(entryFile, 'utf8');
45
+ const exported = new Set([
46
+ ...[...js.matchAll(/export\s+(?:async\s+)?function\s+([A-Za-z0-9_$]+)/g)].map((m) => m[1]),
47
+ ...[...js.matchAll(/export\s+(?:const|let|var)\s+([A-Za-z0-9_$]+)/g)].map((m) => m[1]),
48
+ ...[...js.matchAll(/export\s*\{([^}]*)\}/g)].flatMap((m) => m[1].split(',').map((x) => x.trim().split(/\s+as\s+/).pop())),
49
+ ].filter(Boolean));
50
+ if (!exported.has(raw.export)) out.push(`export="${raw.export}" 在 ${raw.entry} 里没有导出(宿主会加载失败)`);
51
+ }
52
+ }
53
+
54
+ // thumb 指的文件也要在(封面裂图就是这么来的)
55
+ if (raw.thumb !== undefined) {
56
+ if (typeof raw.thumb !== 'string' || !raw.thumb) out.push('thumb 不是字符串');
57
+ else if (!existsSync(join(dir, raw.thumb))) out.push(`thumb 指向的文件不存在:${raw.thumb}`);
58
+ }
59
+
60
+ const axes = [];
61
+ for (const a of Array.isArray(raw.axes) ? raw.axes : []) {
62
+ if (typeof a?.id !== 'string' || !ID.test(a.id)) { out.push(`axis id 不合法:${JSON.stringify(a?.id)}`); continue; }
63
+ if (!namesOf(a?.name)) { out.push(`axis "${a.id}" 缺 name`); continue; }
64
+ if (!Array.isArray(a?.options) || !a.options.length) { out.push(`axis "${a.id}" 没有 options`); continue; }
65
+ const ids = [];
66
+ for (const o of a.options) {
67
+ if (typeof o?.id !== 'string' || !OPTION_ID.test(o.id)) { out.push(`axis "${a.id}" 的 option id 不合法:${JSON.stringify(o?.id)}`); continue; }
68
+ if (!namesOf(o?.name)) out.push(`axis "${a.id}" 的 option "${o.id}" 缺 name`);
69
+ ids.push(o.id);
70
+ }
71
+ axes.push({ id: a.id, ids });
72
+ }
73
+
74
+ for (const p of Array.isArray(raw.presets) ? raw.presets : []) {
75
+ if (typeof p?.id !== 'string' || !ID.test(p.id)) { out.push(`preset id 不合法:${JSON.stringify(p?.id)}`); continue; }
76
+ // ← 这一条最容易被忽略:少了 pick,整个包都不加载
77
+ if (!p.pick || typeof p.pick !== 'object') { out.push(`preset "${p.id}" 缺 pick(宿主会拒绝整个包)`); continue; }
78
+ for (const a of axes) {
79
+ const v = p.pick[a.id];
80
+ if (!a.ids.includes(v)) out.push(`preset "${p.id}" 没给 axis "${a.id}" 选一个合法 option(现在是 ${JSON.stringify(v)})`);
81
+ }
82
+ if (p.name !== undefined && !namesOf(p.name)) out.push(`preset "${p.id}" 的 name 不合法`);
83
+ if (p.console !== undefined) {
84
+ if (typeof p.console !== 'object' || !p.console) out.push(`preset "${p.id}" 的 console 不是对象`);
85
+ else for (const mode of ['light', 'dark']) {
86
+ const pal = p.console[mode];
87
+ if (!pal || typeof pal !== 'object') { out.push(`preset "${p.id}" 的 console.${mode} 缺失`); continue; }
88
+ for (const k of ['a', 'a2', 'on', 't', 'c3', 'c4']) {
89
+ if (typeof pal[k] !== 'string' || !/^#[0-9a-f]{6}$/i.test(pal[k])) out.push(`preset "${p.id}" 的 console.${mode}.${k} 不是 #rrggbb`);
90
+ }
91
+ }
92
+ }
93
+ }
94
+ /* vocab:宿主的 readVocab 也是一票否决(一条不合格 → 整份词表作废 → bot 一个词都认不出) */
95
+ const NAME_BREAK_V = /[,,、\s【】<><>]/;
96
+ const taken = new Set();
97
+ for (const w of Array.isArray(raw.vocab) ? raw.vocab : []) {
98
+ const id = String(w?.id ?? '');
99
+ if (!ID.test(id)) { out.push(`vocab id 不合法:${JSON.stringify(w?.id)}`); continue; }
100
+ for (const list of Object.values(w?.names ?? {})) {
101
+ for (const n of Array.isArray(list) ? list : []) {
102
+ if (typeof n !== 'string' || !n.trim() || n.length > 32 || NAME_BREAK_V.test(n)) out.push(`vocab "${id}" 的名字不合法:${JSON.stringify(n)}`);
103
+ }
104
+ }
105
+ for (const n of [id, ...Object.values(w?.names ?? {}).flat()]) {
106
+ if (taken.has(n)) out.push(`vocab 名字重复:${n}(宿主会拒掉整份词表)`);
107
+ taken.add(n);
108
+ }
109
+ if (!w?.about || typeof w.about !== 'object' || !Object.values(w.about).some((v) => typeof v === 'string' && v.trim())) out.push(`vocab "${id}" 缺 about`);
110
+ if (typeof w?.seconds !== 'number' || !(w.seconds > 0)) out.push(`vocab "${id}" 的 seconds 不合法`);
111
+ }
112
+
113
+ return out;
114
+ }
115
+
116
+ /* CLI */
117
+ if (process.argv[1] && process.argv[1].endsWith('manifest-check.mjs')) {
118
+ const dirs = process.argv.slice(2).map((d) => resolve(d));
119
+ if (!dirs.length) { console.error('用法: node manifest-check.mjs <形象包目录> …'); process.exit(2); }
120
+ let bad = 0;
121
+ for (const d of dirs) {
122
+ const errs = checkManifest(d);
123
+ console.log(`\n${d}`);
124
+ if (!errs.length) console.log(' ✅ 清单合规');
125
+ else { bad++; for (const e of errs) console.log(' · ' + e); }
126
+ }
127
+ process.exit(bad ? 1 : 0);
128
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 全新用户端到端:从零铺一个深深包 → 保存动作 → 用宿主规则体检。
3
+ * node test_freshuser.mjs
4
+ *
5
+ * 这一步专门盯"新装的人"会遇到的问题:包铺出来合不合规、保存后词表会不会被拒、
6
+ * 播放器/配色预设有没有带、以及重复启动会不会反复写盘。
7
+ */
8
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { checkManifest } from './manifest-check.mjs';
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url));
14
+ const fails = [];
15
+ const check = (fn, msg) => { try { fn(); console.log('ok ' + msg); } catch (e) { fails.push(`${msg} → ${e.message}`); console.log('FAIL ' + msg); } };
16
+
17
+ const W = await import(pathToFileURL(join(here, '..', 'src', 'world.js')).href);
18
+
19
+ const root = join(here, '_tmp-fresh');
20
+ rmSync(root, { recursive: true, force: true });
21
+ const botDir = join(root, 'home', 'companion');
22
+ const dataDir = join(botDir, 'data');
23
+ mkdirSync(dataDir, { recursive: true });
24
+
25
+ const cfg = {};
26
+ const ctx = { dataDir, botDir, cfg, persist: (p) => Object.assign(cfg, p), packageDir: join(here, '..'), repoRoot: here };
27
+ const w = new W.ExtraActionsWorld({ ctx });
28
+
29
+ /* ① 首次启动:铺包 */
30
+ await w.start({ log: { info: () => {}, warn: () => {} } });
31
+ const packDir = join(botDir, 'data', 'figures', 'shenshen-actions');
32
+ check(() => { if (!existsSync(join(packDir, 'figure.json'))) throw new Error('没有铺出形象包'); }, '首启铺出形象包');
33
+
34
+ /* ② 铺出来的包必须过宿主清单校验(这是 0.3.30 翻车的地方) */
35
+ check(() => {
36
+ const errs = checkManifest(packDir);
37
+ if (errs.length) throw new Error(errs.join(';'));
38
+ }, '铺出来的 figure.json 符合宿主清单规则');
39
+
40
+ /* ③ 包里有配色预设、有 pick、播放器是新的 */
41
+ check(() => {
42
+ const fig = JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8'));
43
+ const p = (fig.presets ?? []).find((x) => x.console);
44
+ if (!p) throw new Error('没有 console 预设');
45
+ if (!p.pick || typeof p.pick !== 'object') throw new Error('预设缺 pick');
46
+ }, '带配色预设且 pick 合法');
47
+
48
+ check(() => {
49
+ const js = readFileSync(join(packDir, figEntry(packDir)), 'utf8');
50
+ if (!js.includes('REACTION_MAX')) throw new Error('播放器不是新版(没有 REACTION_MAX)');
51
+ }, '播放器是新版(点击回应有上限+兜底)');
52
+
53
+ function figEntry(dir) {
54
+ const fig = JSON.parse(readFileSync(join(dir, 'figure.json'), 'utf8'));
55
+ return fig.entry ?? 'figure.js';
56
+ }
57
+
58
+ /* ④ 建个 4 段的小库,勾两段保存 */
59
+ const lib = join(root, 'lib');
60
+ const hd = 'D:/Coopanion-data/深深-动作库-HD/actions';
61
+ for (const [cat, id] of [['core', 'cheer-hop'], ['eat', 'eat-dumplings']]) {
62
+ cpSync(join(hd, cat, id), join(lib, 'actions', cat, id), { recursive: true });
63
+ }
64
+
65
+ const state0 = await w.invoke('picker', 'state');
66
+ if (!state0.library.ok) {
67
+ await w.invoke('picker', 'set-library', [lib]);
68
+ }
69
+ const r = await w.invoke('picker', 'save', ['shenshen-actions', ['cheer-hop', 'eat-dumplings']]);
70
+ check(() => { if (!r || !r.count) throw new Error('保存没写入任何东西'); }, '保存两段动作成功:' + (r?.count ?? 0) + ' 段');
71
+
72
+ /* ⑤ 保存后:清单仍然合规、词表过宿主校验、模块在 index 里 */
73
+ check(() => {
74
+ const errs = checkManifest(packDir);
75
+ if (errs.length) throw new Error(errs.join(';'));
76
+ }, '保存后 figure.json 仍然合规');
77
+
78
+ check(() => {
79
+ const fig = JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8'));
80
+ const NAME_BREAK = /[,,、\s【】<><>]/;
81
+ const taken = new Set();
82
+ for (const w of fig.vocab ?? []) {
83
+ for (const n of [w.id, ...Object.values(w.names ?? {}).flat()]) {
84
+ if (taken.has(n)) throw new Error('名字重复:' + n);
85
+ taken.add(n);
86
+ }
87
+ for (const n of Object.values(w.names ?? {}).flat()) {
88
+ if (n.length > 32 || NAME_BREAK.test(n)) throw new Error('名字不合法:' + n);
89
+ }
90
+ }
91
+ }, '保存后的词表能过宿主校验(不会被整份拒掉)');
92
+
93
+ check(() => {
94
+ const idx = readFileSync(join(packDir, '额外动作拓展', 'index.js'), 'utf8');
95
+ for (const id of ['cheer-hop', 'eat-dumplings']) {
96
+ if (!idx.includes(id)) throw new Error('index 里没有 ' + id);
97
+ }
98
+ }, '额外动作拓展/index.js 里两段都在');
99
+
100
+ /* ⑥ 再启动一次:不该重复写、也不该改坏 */
101
+ {
102
+ const before = readFileSync(join(packDir, 'figure.json'), 'utf8');
103
+ const w2 = new W.ExtraActionsWorld({ ctx });
104
+ await w2.start({ log: { info: () => {}, warn: () => {} } });
105
+ const after = readFileSync(join(packDir, 'figure.json'), 'utf8');
106
+ check(() => { if (before !== after) throw new Error('第二次启动又改了 figure.json'); }, '重复启动不重复写 figure.json');
107
+ }
108
+
109
+ /* ⑦ 包健康度(插件自己的 inspect) */
110
+ check(() => {
111
+ const r2 = w.invoke('picker', 'state');
112
+ return r2;
113
+ }, 'state 可读');
114
+
115
+ rmSync(root, { recursive: true, force: true });
116
+ console.log(fails.length ? `\nFAIL (${fails.length})\n- ${fails.join('\n- ')}` : '\nall checks passed');
117
+ process.exit(fails.length ? 1 : 0);
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 清单(figure.json)合规测试:宿主对清单是「一条不合格 → 整个包不加载」。
3
+ *
4
+ * 真实踩过的坑:给深深包加控制台配色预设时漏了 `pick`,宿主 packs.ts:330 直接
5
+ * `presets 里有不合法的一项:"teal"` → 整个包不加载 → 形象列表里没有深深,
6
+ * 用户还以为可以再建一个(于是出现"重复创建"的错觉)。
7
+ *
8
+ * node test_manifest.mjs
9
+ */
10
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { dirname, join } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { checkManifest } from './manifest-check.mjs';
14
+
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+ const fails = [];
17
+ const check = (fn, msg) => { try { fn(); console.log('ok ' + msg); } catch (e) { fails.push(`${msg} → ${e.message}`); console.log('FAIL ' + msg); } };
18
+
19
+ const root = join(here, '_tmp-manifest');
20
+ rmSync(root, { recursive: true, force: true });
21
+
22
+ const writePack = (name, fig) => {
23
+ const dir = join(root, name);
24
+ mkdirSync(dir, { recursive: true });
25
+ writeFileSync(join(dir, 'figure.json'), JSON.stringify(fig, null, 2), 'utf8');
26
+ writeFileSync(join(dir, 'figure.js'), 'export function createActionBody() {}', 'utf8');
27
+ return dir;
28
+ };
29
+ const base = { manifest: 2, api: 2, id: 'shenshen-actions', name: { zh: '深深' }, about: { zh: 'x' }, entry: 'figure.js', export: 'createActionBody' };
30
+
31
+ /* ① 我们自带的 figure.json 必须合规 */
32
+ check(() => {
33
+ const errs = checkManifest(join(here, '..', 'assets', 'starter', 'figure'));
34
+ if (errs.length) throw new Error(errs.join(';'));
35
+ }, '插件自带 figure.json 符合宿主清单规则');
36
+
37
+ /* ② 没 pick 的预设会被抓出来(就是这次线上事故) */
38
+ check(() => {
39
+ const dir = writePack('no-pick', { ...base, presets: [{ id: 'teal', console: { light: {}, dark: {} } }] });
40
+ const errs = checkManifest(dir);
41
+ if (!errs.some((e) => /preset "teal" 缺 pick/.test(e))) throw new Error('没识别出缺 pick:' + errs.join(';'));
42
+ }, '缺 pick 的预设被判为不合法(线上事故的复现)');
43
+
44
+ /* ③ pick 要覆盖每个 axis,且值必须是该 axis 的 option */
45
+ check(() => {
46
+ const withAxis = {
47
+ ...base,
48
+ axes: [{ id: 'look', name: { zh: '样子' }, options: [{ id: 'a', name: { zh: 'A' } }, { id: 'b', name: { zh: 'B' } }] }],
49
+ };
50
+ const dir = writePack('pick-missing-axis', { ...withAxis, presets: [{ id: 'p1', pick: {} }] });
51
+ const errs = checkManifest(dir);
52
+ if (!errs.some((e) => /没给 axis "look"/.test(e))) throw new Error('没识别出 pick 缺 axis:' + errs.join(';'));
53
+
54
+ const okDir = writePack('pick-ok', { ...withAxis, presets: [{ id: 'p1', pick: { look: 'a' } }] });
55
+ const errs2 = checkManifest(okDir);
56
+ if (errs2.length) throw new Error('合法预设被判错:' + errs2.join(';'));
57
+ }, 'pick 必须覆盖每个 axis 并取合法 option');
58
+
59
+ /* ④ console 调色板要齐全(light/dark × a,a2,on,t,c3,c4) */
60
+ check(() => {
61
+ const dir = writePack('console-bad', { ...base, presets: [{ id: 'p2', pick: {}, console: { light: { a: '#000000' }, dark: {} } }] });
62
+ const errs = checkManifest(dir);
63
+ if (!errs.some((e) => /console\.light\.a2/.test(e))) throw new Error('没识别出配色字段缺失:' + errs.join(';'));
64
+ }, 'console 调色板缺字段会被抓出来');
65
+
66
+ /* ⑤ 合法包(带 console 预设)应当通过 */
67
+ check(() => {
68
+ const preset = {
69
+ id: 'teal', pick: {},
70
+ name: { zh: '深深 · 青绿' }, accent: '#0b7a5a',
71
+ console: {
72
+ light: { a: '#0b7a5a', a2: '#0f9d76', on: '#ffffff', t: '#0b6b4f', c3: '#3f8f78', c4: '#8a8a90' },
73
+ dark: { a: '#2fd3a0', a2: '#7fe6c2', on: '#062a20', t: '#8ae8c6', c3: '#5fbfa0', c4: '#9a9aa0' },
74
+ },
75
+ };
76
+ const dir = writePack('good', { ...base, presets: [preset] });
77
+ const errs = checkManifest(dir);
78
+ if (errs.length) throw new Error(errs.join(';'));
79
+ }, '带 console 预设的合法包通过校验');
80
+
81
+ /* ⑥ 迁移会补 pick(老包里的坏预设) */
82
+ {
83
+ const { ensureConsolePreset } = await import('../src/starter.js');
84
+ const dir = writePack('migrate', { ...base, presets: [{ id: 'teal', console: { light: {}, dark: {} } }] });
85
+ const before = checkManifest(dir);
86
+ if (!before.some((e) => /缺 pick/.test(e))) throw new Error('夹具应该是坏的');
87
+ ensureConsolePreset(dir);
88
+ const after = checkManifest(dir);
89
+ check(() => { if (after.some((e) => /缺 pick/.test(e))) throw new Error('迁移没补上 pick'); }, '迁移会给老预设补上 pick');
90
+ }
91
+
92
+ rmSync(root, { recursive: true, force: true });
93
+ console.log(fails.length ? `\nFAIL (${fails.length})\n- ${fails.join('\n- ')}` : '\nall checks passed');
94
+ process.exit(fails.length ? 1 : 0);