modelstage 0.5.28 → 0.10.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.
Files changed (98) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +2 -63
  3. package/config/models/live2d.assetbundls.json +1 -1
  4. package/config/models/live2d.azurlane.json +1 -1
  5. package/config/models/live2d.azurlane_bundle.json +1 -1
  6. package/config/models/live2d.azurlane_bundle.jsonl +2 -0
  7. package/config/models/live2d.azurlane_spine.json +1 -1
  8. package/config/models/live2d.bd2.json +1 -1
  9. package/config/models/live2d.bd2.jsonl +2 -0
  10. package/config/models/live2d.bd2_mod.json +1 -0
  11. package/config/models/live2d.bluearchive.json +1 -1
  12. package/config/models/live2d.nikke.json +1 -1
  13. package/config/models/live2d.nikke.jsonl +2 -0
  14. package/config/models/live2d.nikke_2.json +1 -1
  15. package/config/models/live2d.npc.json +1 -1
  16. package/config/models/live2d.sample_haru.json +1 -0
  17. package/config/models/spine.assetbundls.json +1 -1
  18. package/config/models/spine.azurlane.json +1 -1
  19. package/config/models/spine.azurlane_bundle.json +1 -1
  20. package/config/models/spine.azurlane_bundle.jsonl +2 -0
  21. package/config/models/spine.azurlane_spine.json +1 -1
  22. package/config/models/spine.bd2.json +1 -1
  23. package/config/models/spine.bd2.jsonl +433 -0
  24. package/config/models/spine.bd2_mod.json +1 -0
  25. package/config/models/spine.bluearchive.json +1 -1
  26. package/config/models/spine.nikke.json +1 -1
  27. package/config/models/spine.nikke_2.json +1 -1
  28. package/config/models/spine.npc.json +1 -1
  29. package/config/models/spine.sample_haru.json +1 -0
  30. package/package.json +3 -2
  31. package/plugins/unity-live2d-bundle/index.js +43 -1
  32. package/plugins/unity-live2d-bundle/lib/bundle-probe.js +79 -0
  33. package/plugins/unity-live2d-bundle/plugin.json +2 -1
  34. package/plugins/unity-spine-bundle/index.js +38 -1
  35. package/plugins/unity-spine-bundle/lib/bundle-probe.js +323 -0
  36. package/plugins/unity-spine-bundle/plugin.json +3 -1
  37. package/src/server/analyze/index.mjs +470 -0
  38. package/src/server/assets/probe.mjs +1 -1
  39. package/src/server/core/config.mjs +2 -2
  40. package/src/server/core/log.mjs +1 -1
  41. package/src/server/data/catalog.mjs +41 -16
  42. package/src/server/data/display-name-cache.mjs +142 -0
  43. package/src/server/data/entry-states.mjs +21 -0
  44. package/src/server/data/live2d.mjs +139 -40
  45. package/src/server/data/manifest-cache.mjs +53 -10
  46. package/src/server/data/manifest-jsonl.mjs +264 -0
  47. package/src/server/data/manifest-stamp.mjs +52 -2
  48. package/src/server/data/scan-progress.mjs +305 -0
  49. package/src/server/data/scan-queue.mjs +99 -0
  50. package/src/server/data/spine.mjs +324 -106
  51. package/src/server/http/write.mjs +7 -6
  52. package/src/server/index.mjs +1 -1
  53. package/src/server/plugins/registry.mjs +3 -3
  54. package/src/server/routes/data.mjs +76 -17
  55. package/src/server/routes/display-name.mjs +157 -0
  56. package/src/server/serve.mjs +17 -4
  57. package/src/server/unpack/plugin-store.mjs +1 -1
  58. package/src/server/unpack/runtime/exec.mjs +37 -8
  59. package/src/server/unpack/worker-client.mjs +23 -8
  60. package/src/shared/scan-limits.mjs +23 -0
  61. package/src/web/app/anim-list.js +1 -1
  62. package/src/web/app/backgrounds.js +4 -8
  63. package/src/web/app/dir-picker.js +3 -5
  64. package/src/web/app/memory-budget.js +0 -1
  65. package/src/web/app/memory-guard.js +0 -1
  66. package/src/web/app/model-actions.js +18 -15
  67. package/src/web/app/root-manager.js +2 -4
  68. package/src/web/app/transport-actions.js +1 -1
  69. package/src/web/app/ui-state.js +1 -1
  70. package/src/web/components.css +90 -0
  71. package/src/web/debug/race-probe.js +36 -13
  72. package/src/web/engine/textures.js +1 -2
  73. package/src/web/infra/api.js +10 -19
  74. package/src/web/infra/document.js +3 -3
  75. package/src/web/infra/plugin-host-unpack.mjs +94 -12
  76. package/src/web/infra/plugin-host.js +3 -0
  77. package/src/web/infra/ready.js +177 -39
  78. package/src/web/live2d/bridge.js +1 -1
  79. package/src/web/live2d/runtime-adapter.js +2 -4
  80. package/src/web/panel/panel-settings.js +88 -3
  81. package/src/web/render/surface.js +49 -2
  82. package/src/web/roster/display-name.js +79 -0
  83. package/src/web/roster/events.js +198 -0
  84. package/src/web/roster/filter.js +4 -4
  85. package/src/web/roster/list.js +11 -5
  86. package/src/web/roster/load.js +440 -0
  87. package/src/web/roster/persist.js +46 -37
  88. package/src/web/roster/render.js +284 -0
  89. package/src/web/roster/reveal.js +4 -9
  90. package/src/web/roster/rows.js +35 -13
  91. package/src/web/roster/scan-stream.js +346 -0
  92. package/src/web/roster/snapshot.js +14 -8
  93. package/src/web/roster/store.js +340 -0
  94. package/src/web/roster/type-filter.js +5 -5
  95. package/src/web/roster/view.js +147 -634
  96. package/src/web/spine/canvas-runtime.js +4 -5
  97. package/src/web/spine/runtimes.js +1 -1
  98. package/tool/lib/bundle-probe-node.mjs +146 -32
@@ -0,0 +1,470 @@
1
+ // server/analyze/index.mjs —— 只读分析接口(/api/analyze)
2
+ //
3
+ // 目标:给任意路径上的容器/模型文件一个「这是什么、能不能用、缺什么」的结论。
4
+ // 三条硬约束(写在最前,改这个文件的人先看):
5
+ // ① **只读**:不写文件、不改配置;打开被分析文件只用读
6
+ // ② **不限路径**:不要求落在某个资源根内(这是这个接口与既有 /api/bundle/probe 的区别)
7
+ // ③ **不设超时**:限量靠"字节上限 / 文件数上限",不靠时间。产品代码里不出现 AbortSignal.timeout
8
+ //
9
+ // 实现复用:容器解析走 tool/lib/bundle-probe-node.mjs(它按 provides 找插件,一个都没有时降级为魔数判定),
10
+ // 本文件不重复实现 UnityFS/对象表解析。
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { probeBundleBytes, analyzeByMagicOnly } from '../../../tool/lib/bundle-probe-node.mjs';
15
+ import { memAvailableMb } from '../unpack/capacity.mjs';
16
+
17
+ /**
18
+ * 单文件字节上限。
19
+ * 取值理由:本项目最大的容器样本在 2GB 量级,但"只读分析"只需要读容器头与对象表;
20
+ * 超过 512MB 的输入一律拒绝并说明,而不是边读边解析(那样内存会被拖垮,而且没有时间上限可依赖)。
21
+ */
22
+ const MAX_FILE_BYTES = 512 * 1024 * 1024;
23
+
24
+ /** 目录递归的默认文件数上限;超出的部分写进 warnings,不静默截断。 */
25
+ const DEFAULT_MAX_FILES = 500;
26
+
27
+ /**
28
+ * 目录递归深度上限。
29
+ * 取值理由:真实资源树最深约 8 层(根/游戏/区服/资源类型/角色/皮肤/贴图);
30
+ * 12 层足够,再深基本是符号链接环或异常目录。
31
+ */
32
+ const MAX_DIR_DEPTH = 12;
33
+
34
+ /**
35
+ * 递归时认作"可能是容器/模型"的扩展名。
36
+ *
37
+ * 与扫描器判据同源(避免两套口径)。**不含普通 `.json`**:
38
+ * 目录里 `config.json` / `package.json` 之类的配置文件远多于模型,把它们都当候选
39
+ * 只会让 items 变成一堆噪音;真正的模型描述是 `.model3.json`(下方单独列出)。
40
+ */
41
+ const CANDIDATE_EXT = new Set([
42
+ '.skel', '.atlas', '.moc', '.moc3', '.model3.json', '.lpk', '.unity3d', '.bundle', '.ab',
43
+ ]);
44
+
45
+ /** 读前 16 字节判种类(只用于"该不该继续读整份"的初筛) */
46
+ function readHead(absPath, n = 16) {
47
+ const fd = fs.openSync(absPath, 'r');
48
+ try {
49
+ const buf = Buffer.alloc(n);
50
+ const read = fs.readSync(fd, buf, 0, n, 0);
51
+ return buf.subarray(0, read);
52
+ } finally {
53
+ fs.closeSync(fd);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 非 UnityFS 输入的判定(moc3 / model3.json / zip / 纯文本)。
59
+ * 这些不走插件(插件只认 UnityFS),但要给出可读结论 —— 否则"分析一个 moc3"会得到"未知"。
60
+ * @param {string} absPath
61
+ * @param {Buffer} head 文件前若干字节
62
+ * @param {number} bytes 文件大小
63
+ * @returns {{verdict: string, summary: string, warnings: string[], extra: object}}
64
+ */
65
+ function analyzeNonBundle(absPath, head, bytes) {
66
+ const ascii = head.toString('latin1');
67
+ const base = path.basename(absPath);
68
+
69
+ if (ascii.startsWith('MOC3')) {
70
+ // Cubism 4 的 .moc3:头部为 "MOC3" + 版本字节
71
+ return {
72
+ verdict: 'live2d-cubism4',
73
+ summary: `Cubism 4 模型二进制(${bytes} 字节)`,
74
+ warnings: [],
75
+ extra: { moc3VersionByte: head.length > 4 ? head[4] : null },
76
+ };
77
+ }
78
+ if (head.length >= 2 && head[0] === 0x50 && head[1] === 0x4b) {
79
+ // ZIP 容器。LPK 属于这一类,且其内部条目是加密的(元数据 JSON 里有 encrypt 字段)
80
+ return {
81
+ verdict: 'archive',
82
+ summary: `ZIP 容器(${base},${bytes} 字节);若内部是加密条目则无法直接解析`,
83
+ warnings: ['ZIP 内部条目可能是加密的(例如 Live2DViewerEX 的 LPK),需要对应密钥才能还原'],
84
+ extra: {},
85
+ };
86
+ }
87
+ if (ascii.trimStart().startsWith('{') || ascii.trimStart().startsWith('[')) {
88
+ // JSON:model3.json 是 Cubism 4 的入口描述
89
+ const isModel3 = /\.model3\.json$/i.test(base);
90
+ return {
91
+ verdict: isModel3 ? 'live2d-cubism4' : 'unknown',
92
+ summary: isModel3
93
+ ? `Cubism 4 模型描述(${base})`
94
+ : `JSON 文本(${base},${bytes} 字节)`,
95
+ warnings: [],
96
+ extra: { json: true },
97
+ };
98
+ }
99
+ return {
100
+ verdict: 'unknown',
101
+ summary: `无法从文件头识别(${base},${bytes} 字节)`,
102
+ warnings: ['不是已知的容器/模型格式;若是加密或自定义格式,需要对应的解析实现'],
103
+ extra: {},
104
+ };
105
+ }
106
+
107
+ /**
108
+ * 从插件分析结论(或降级结论)推导 verdict。
109
+ * 判据只在这里一份:插件只提供事实(TextAsset 名 / moc3 有无 / 对象数),不自己下"是什么"的结论。
110
+ * @param {object} r probeBundleBytes / analyzeByMagicOnly 的结果
111
+ * @returns {string}
112
+ */
113
+ function deriveVerdict(r) {
114
+ if (!r || r.ok === false) {
115
+ if (r && r.magic === 'MOC3') return 'live2d-cubism4';
116
+ if (r && r.magic === 'ZIP') return 'archive';
117
+ if (r && r.magic === 'UnityFS') return 'bundle-unknown'; // 是容器但没插件能细看
118
+ return 'unknown';
119
+ }
120
+ const textAssets = Array.isArray(r.textAssets) ? r.textAssets : [];
121
+ if (textAssets.some((t) => t && t.kind === 'skel')) return 'spine';
122
+ if (textAssets.some((t) => t && typeof t.name === 'string' && /\.model3\.json$/i.test(t.name))) {
123
+ return 'live2d-cubism4';
124
+ }
125
+ if (r.moc3) return 'live2d-cubism4';
126
+ if (r.cubism2Moc) return 'live2d-cubism2';
127
+ // 有对象表但没有骨架/moc3:多半是 3D 或纯资源包
128
+ return 'unity-3d';
129
+ }
130
+
131
+ /** 人可读的一句话结论(与 verdict 分开:verdict 给机器,summary 给人) */
132
+ function buildSummary(verdict, r, bytes) {
133
+ const ta = Array.isArray(r && r.textAssets) ? r.textAssets : [];
134
+ const skels = ta.filter((t) => t && t.kind === 'skel');
135
+ const textures = Array.isArray(r && r.textures) ? r.textures : [];
136
+ const parts = [];
137
+ switch (verdict) {
138
+ case 'spine':
139
+ parts.push(`Spine 模型包(${skels.length} 个骨架)`);
140
+ if (skels.length) {
141
+ const first = skels[0];
142
+ parts.push(`骨架 ${first.name}${first.spineVersion ? `(版本 ${first.spineVersion})` : ''}`);
143
+ }
144
+ break;
145
+ case 'live2d-cubism4':
146
+ parts.push('Live2D Cubism 4 模型');
147
+ break;
148
+ case 'live2d-cubism2':
149
+ parts.push('Live2D Cubism 2.1 模型(.moc,运行时已不支持)');
150
+ break;
151
+ case 'unity-3d':
152
+ parts.push('Unity 资源包,未检出骨架/moc3(可能是 3D 或纯美术资源)');
153
+ break;
154
+ case 'bundle-unknown':
155
+ parts.push('Unity 资源包,但当前没有能细看的插件(只识别了文件头)');
156
+ break;
157
+ case 'archive':
158
+ parts.push('归档容器');
159
+ break;
160
+ default:
161
+ parts.push('无法识别');
162
+ }
163
+ if (textures.length) {
164
+ const formats = [...new Set(textures.map((t) => t.formatName || t.format))];
165
+ parts.push(`${textures.length} 张纹理(${formats.slice(0, 3).join(' / ')})`);
166
+ }
167
+ parts.push(`${bytes} 字节`);
168
+ return parts.join(';');
169
+ }
170
+
171
+ /**
172
+ * 分析一个文件(只读)。
173
+ *
174
+ * @param {string} absPath 绝对路径
175
+ * @param {{maxFileBytes?: number}} [opts]
176
+ * @returns {Promise<{status: number, body: object}>} status 用于路由直接回写
177
+ */
178
+ export async function analyzeFile(absPath, opts = {}) {
179
+ const maxFileBytes = opts.maxFileBytes || MAX_FILE_BYTES;
180
+
181
+ let stat;
182
+ try {
183
+ stat = fs.statSync(absPath);
184
+ } catch {
185
+ return {
186
+ status: 404,
187
+ body: { ok: false, code: 'ANALYZE_NOT_FOUND', error: `路径不存在:${absPath}` },
188
+ };
189
+ }
190
+ if (stat.isDirectory()) {
191
+ return {
192
+ status: 400,
193
+ body: { ok: false, code: 'ANALYZE_IS_DIR', error: `这是一个目录,请用 dir 参数:${absPath}` },
194
+ };
195
+ }
196
+ if (stat.size > maxFileBytes) {
197
+ return {
198
+ status: 413,
199
+ body: {
200
+ ok: false,
201
+ code: 'ANALYZE_TOO_LARGE',
202
+ error: `文件超过单文件上限(${stat.size} > ${maxFileBytes} 字节);本接口不做流式全解析`,
203
+ bytes: stat.size,
204
+ maxFileBytes,
205
+ },
206
+ };
207
+ }
208
+
209
+ const bytes = stat.size;
210
+ let head;
211
+ try {
212
+ head = readHead(absPath, 16);
213
+ } catch (e) {
214
+ return { status: 500, body: { ok: false, code: 'ANALYZE_READ_FAILED', error: `读取失败:${e.message}` } };
215
+ }
216
+
217
+ // 非 UnityFS:不值得进插件(插件只认 UnityFS),直接给结论
218
+ if (!head.toString('latin1').startsWith('UnityFS')) {
219
+ const non = analyzeNonBundle(absPath, head, bytes);
220
+ return {
221
+ status: 200,
222
+ body: {
223
+ ok: true,
224
+ path: absPath,
225
+ bytes,
226
+ verdict: non.verdict,
227
+ analyzedBy: { fallback: true, magic: head.toString('latin1').slice(0, 7).replace(/[^\x20-\x7e]/g, '?') },
228
+ container: null,
229
+ nodes: [],
230
+ objects: [],
231
+ textAssets: [],
232
+ textures: [],
233
+ warnings: non.warnings,
234
+ summary: non.summary,
235
+ ...non.extra,
236
+ },
237
+ };
238
+ }
239
+
240
+ let buffer;
241
+ try {
242
+ buffer = fs.readFileSync(absPath);
243
+ } catch (e) {
244
+ return { status: 500, body: { ok: false, code: 'ANALYZE_READ_FAILED', error: `读取失败:${e.message}` } };
245
+ }
246
+
247
+ let r;
248
+ try {
249
+ r = probeBundleBytes(new Uint8Array(buffer));
250
+ } catch (e) {
251
+ // 插件内部抛错(解析器 bug/损坏包):降级给魔数结论,不把异常漏给调用方
252
+ r = Object.assign(analyzeByMagicOnly(new Uint8Array(buffer)), { parseError: e.message });
253
+ }
254
+
255
+ const verdict = deriveVerdict(r);
256
+ const analyzedBy = (r && r.pluginId)
257
+ ? { pluginId: r.pluginId }
258
+ : (r && r.code === 'ULB_ERR_NO_ANALYZER'
259
+ ? { fallback: true, magic: r.magic || null }
260
+ : { pluginId: null });
261
+
262
+ // 纹理:ASTC 等不解码的格式进 warnings(与预检口径一致)
263
+ const textures = Array.isArray(r.textures) ? r.textures : [];
264
+ const warnings = Array.isArray(r.warnings) ? r.warnings.slice() : [];
265
+ if (r.parseError) warnings.push(`插件解析抛错,已降级为文件头判定:${r.parseError}`);
266
+
267
+ return {
268
+ status: 200,
269
+ body: {
270
+ ok: true,
271
+ path: absPath,
272
+ bytes,
273
+ verdict,
274
+ analyzedBy,
275
+ container: r.container ? {
276
+ kind: 'UnityFS',
277
+ version: r.container.version,
278
+ engine: r.container.engine,
279
+ nodes: r.container.nodes,
280
+ } : null,
281
+ nodes: Array.isArray(r.nodes) ? r.nodes : [],
282
+ objects: Array.isArray(r.objects) ? r.objects : (typeof r.objects === 'number' ? [{ className: '(合计)', size: null, count: r.objects }] : []),
283
+ textAssets: Array.isArray(r.textAssets) ? r.textAssets : [],
284
+ textures,
285
+ warnings,
286
+ // 契约 §1.3:显示名由插件给(可缺省)。核心**不推导**——不知道 .skel/.atlas 的名字含义,
287
+ // 也不做去后缀/拼接。插件没给就是 null,由上层回落到文件名。
288
+ displayName: (typeof r.displayName === 'string' && r.displayName.trim()) ? r.displayName.trim() : null,
289
+ summary: buildSummary(verdict, r, bytes),
290
+ },
291
+ };
292
+ }
293
+
294
+ /**
295
+ * 判断一个文件是否"可能是容器/模型"(用来决定是否值得打开)。
296
+ *
297
+ * 两条判据,任一命中即可:
298
+ * ① 已知扩展名(见 CANDIDATE_EXT)
299
+ * ② **魔数**:无扩展名或扩展名不认识的容器(实测 NIKKE 的包就是无扩展名 UnityFS 文件)
300
+ * 为什么扩展名优先:魔数要读盘,大目录里几千个文件逐个读会把 IO 打满;
301
+ * 扩展名匹配的直接判定,只有"看起来不像资源"的才去读文件头。
302
+ *
303
+ * @param {string} absPath
304
+ * @param {string} name
305
+ * @returns {boolean}
306
+ */
307
+ function isCandidate(absPath, name) {
308
+ const lower = name.toLowerCase();
309
+ for (const ext of CANDIDATE_EXT) {
310
+ if (lower.endsWith(ext)) return true;
311
+ }
312
+ // 魔数兜底:只读前 8 字节
313
+ let head;
314
+ try {
315
+ head = readHead(absPath, 8);
316
+ } catch {
317
+ return false;
318
+ }
319
+ const ascii = head.toString('latin1');
320
+ if (ascii.startsWith('UnityFS')) return true;
321
+ if (ascii.startsWith('MOC3')) return true;
322
+ if (ascii.startsWith('CAB-')) return true;
323
+ if (head.length >= 2 && head[0] === 0x50 && head[1] === 0x4b) return true; // PK(zip/lpk)
324
+ return false;
325
+ }
326
+
327
+ /**
328
+ * 递归分析一个目录(只读)。
329
+ *
330
+ * 并发:逐个分析(上限 1)。这个接口与扫描器共用同一条"同时只做一件重活"的纪律,
331
+ * 不另造一套并发控制 —— 分析一个包要解 LZMA + 建对象表,并发会互相拖慢并把事件循环占满。
332
+ *
333
+ * @param {string} absDir
334
+ * @param {{maxFiles?: number, onItem?: Function}} [opts]
335
+ * @returns {Promise<{status: number, body: object}>}
336
+ */
337
+ export async function analyzeDir(absDir, opts = {}) {
338
+ const maxFiles = opts.maxFiles || DEFAULT_MAX_FILES;
339
+
340
+ let stat;
341
+ try {
342
+ stat = fs.statSync(absDir);
343
+ } catch {
344
+ return {
345
+ status: 404,
346
+ body: { ok: false, code: 'ANALYZE_NOT_FOUND', error: `目录不存在:${absDir}` },
347
+ };
348
+ }
349
+ if (!stat.isDirectory()) {
350
+ return {
351
+ status: 400,
352
+ body: { ok: false, code: 'ANALYZE_NOT_DIR', error: `不是目录,请用 path 参数:${absDir}` },
353
+ };
354
+ }
355
+
356
+ const candidates = [];
357
+ const warnings = [];
358
+ let scanned = 0;
359
+ let truncated = false;
360
+
361
+ /** 深度优先收集候选(深度上限防环) */
362
+ const walk = (dir, depth) => {
363
+ if (depth > MAX_DIR_DEPTH) return;
364
+ let entries;
365
+ try {
366
+ entries = fs.readdirSync(dir, { withFileTypes: true });
367
+ } catch (e) {
368
+ warnings.push(`目录不可读,已跳过:${dir}(${e.message})`);
369
+ return;
370
+ }
371
+ for (const entry of entries) {
372
+ if (entry.name.startsWith('.')) continue; // 隐藏目录(.trash 等)不参与
373
+ const full = path.join(dir, entry.name);
374
+ if (entry.isDirectory()) {
375
+ walk(full, depth + 1);
376
+ continue;
377
+ }
378
+ scanned += 1;
379
+ if (!isCandidate(full, entry.name)) continue;
380
+ if (candidates.length >= maxFiles) {
381
+ truncated = true;
382
+ return;
383
+ }
384
+ candidates.push(full);
385
+ }
386
+ };
387
+ walk(absDir, 0);
388
+
389
+ if (truncated) {
390
+ warnings.push(`候选文件超过上限 ${maxFiles},只分析了前 ${maxFiles} 个(可用 maxFiles 参数调整)`);
391
+ }
392
+
393
+ const items = [];
394
+ const counts = {};
395
+ for (const file of candidates) {
396
+ // 并发上限 1:逐个来(理由见函数头注释)
397
+ const { status, body } = await analyzeFile(file);
398
+ if (status !== 200 || !body.ok) {
399
+ warnings.push(`分析失败:${file}(${body.code || status})`);
400
+ continue;
401
+ }
402
+ counts[body.verdict] = (counts[body.verdict] || 0) + 1;
403
+ items.push({ path: body.path, bytes: body.bytes, verdict: body.verdict, summary: body.summary });
404
+ if (typeof opts.onItem === 'function') opts.onItem(body);
405
+ }
406
+
407
+ return {
408
+ status: 200,
409
+ body: {
410
+ ok: true,
411
+ dir: absDir,
412
+ scanned,
413
+ candidates: candidates.length,
414
+ counts,
415
+ items,
416
+ warnings,
417
+ ...(memAvailableMb() !== null ? { memAvailableMb: memAvailableMb() } : {}),
418
+ },
419
+ };
420
+ }
421
+
422
+ /**
423
+ * 路由:GET /api/analyze?path=<绝对路径> 或 ?dir=<绝对路径>
424
+ *
425
+ * @param {object} req
426
+ * @param {object} res
427
+ * @param {string} p 路径
428
+ * @param {URL} url
429
+ * @param {object} ctx 含 sendJson
430
+ * @returns {Promise<boolean>}
431
+ */
432
+ export async function handleAnalyze(req, res, p, url, ctx) {
433
+ const { sendJson } = ctx;
434
+ if (p !== '/api/analyze') return false;
435
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
436
+ sendJson(res, 405, { ok: false, code: 'ANALYZE_METHOD', error: '只支持 GET' });
437
+ return true;
438
+ }
439
+
440
+ const targetPath = url.searchParams.get('path');
441
+ const targetDir = url.searchParams.get('dir');
442
+ if (!targetPath && !targetDir) {
443
+ sendJson(res, 400, {
444
+ ok: false,
445
+ code: 'ANALYZE_BAD_ARGS',
446
+ error: '需要 path(单文件)或 dir(目录)参数;两者给一个即可',
447
+ });
448
+ return true;
449
+ }
450
+ if (targetPath && targetDir) {
451
+ sendJson(res, 400, {
452
+ ok: false,
453
+ code: 'ANALYZE_BAD_ARGS',
454
+ error: 'path 与 dir 只能给一个',
455
+ });
456
+ return true;
457
+ }
458
+
459
+ const maxFilesRaw = url.searchParams.get('maxFiles');
460
+ const maxFiles = maxFilesRaw ? Number(maxFilesRaw) : DEFAULT_MAX_FILES;
461
+
462
+ const { status, body } = targetPath
463
+ ? await analyzeFile(targetPath)
464
+ : await analyzeDir(targetDir, { maxFiles: Number.isFinite(maxFiles) && maxFiles > 0 ? maxFiles : DEFAULT_MAX_FILES });
465
+
466
+ sendJson(res, status, body);
467
+ return true;
468
+ }
469
+
470
+ export { MAX_FILE_BYTES, DEFAULT_MAX_FILES, MAX_DIR_DEPTH, deriveVerdict };
@@ -150,7 +150,7 @@ export function parseAtlasPages(atlasPath) {
150
150
  try {
151
151
  // 先剥一次 BOM 再按行匹配。原因:JS 的 \s **包含 U+FEFF**,而 AssetStudio 导出的 atlas
152
152
  // 首行是「BOM + 页名」(EF BB BF ...)⇒ 不剥的话首行被 /^[^\s]/ 判成"有前导空白"整行跳过
153
- // ⇒ 多页图集的**第一页页名丢失**(现场:NIKKE 根 247 个模型里 34 份 atlas 带 BOM,均丢第一页 ⇒ 贴图拿不到、画面空白)。
153
+ // ⇒ 多页图集的**第一页页名丢失** ⇒ 贴图拿不到、画面空白。
154
154
  // 为什么前端 src/web/engine/textures.js 没这个坑:它**先 trim() 再匹配**,而 trim() 会把 U+FEFF
155
155
  // 当空白吃掉 —— 所以那边页名本来就干净。这里剥 BOM 就是与"先 trim"等价,别删。
156
156
  // 只剥解析用的文本:**不改 atlas 落盘字节、不改页名大小写**(产物必须逐字节不变)。
@@ -126,8 +126,8 @@ function readHeader() {
126
126
  * 按 name(显示名称 = 归一 key)把资源根归并成组,供前端直接渲染。
127
127
  *
128
128
  * 归一语义:name 相同的多个资源根合并为一个条目。
129
- * 例:「棕色尘埃2 原版」与「棕色尘埃2 mod」两个目录若都命名为"棕色尘埃2",
130
- * 界面合并成一个"棕色尘埃2",其下汇总各 root 的模型(原版 + mod 共存不覆盖)。
129
+ * 例:原版目录与 Mod 目录若填了同一个显示名,界面合并成一个条目,
130
+ * 其下汇总各 root 的模型(原版 + Mod 共存不覆盖)。
131
131
  *
132
132
  * @param {Array} roots 资源根数组
133
133
  * @returns {Array<{name:string, rootCount:number, roots:Array}>}
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // 记录形状(与前端同一套字段名):{ at, level, tag, msg, detail }
8
8
  // 输出格式(单行,人读 + 可解析兼顾):
9
- // 14:32:07.981 INFO [models] 已生成清单 models.bd2.json {"count":389}
9
+ // 14:32:07.981 INFO [models] 已生成清单 spine.<rootId>.json {"count":0}
10
10
  // └ 固定宽度前缀 ⇒ 正则 /^(\d{2}:\d{2}:\d{2}\.\d{3}) (\w+)\s+\[(\S+)\] (.*?)(\{.*\})?$/ 可切四段
11
11
  // 流向:error → stderr(真正的异常),debug/info/warn → stdout。
12
12
  // 项目启动脚本是 `nohup … >"$LOG_FILE" 2>&1`,两流合并写同一文件,所以分流不丢日志,
@@ -24,6 +24,8 @@ import { encodePath } from '../assets/probe.mjs';
24
24
  import { KNOWN_FILE_EXT } from './tree.mjs';
25
25
  // 指纹判据只有一份实现:catalog / 上报路由 / 解包路径三处必须同源(INV-D6)
26
26
  import { providerFingerprintOf, assetFingerprintOf } from './entry-states.mjs';
27
+ // 列表显示名缓存:只按 key 存取,本文件不认识任何容器格式(名字的语义归插件)
28
+ import { readDisplayNameCache, lookupDisplayName, displayNameCacheFile } from './display-name-cache.mjs';
27
29
 
28
30
  /**
29
31
  * 路径式文件 URL(Live2D 定义文件内部用相对路径引用,必须用 /files/ 前缀)。
@@ -209,7 +211,6 @@ export function toSpineEntry(cfg, m) {
209
211
  skins: m.skins || [],
210
212
  expressions: [],
211
213
  textureCount: m.textureCount,
212
- fileSize: m.fileSize,
213
214
  extras: {
214
215
  versionLabel: m.version,
215
216
  format: m.format,
@@ -316,7 +317,6 @@ function buildLive2DMeta(lm, fromDef, textureCheck) {
316
317
  textureCount: (lm.textureFiles || []).length,
317
318
  // 声明了但磁盘缺失的纹理(前端据此预判并给出明确提示,不必等渲染报错)
318
319
  missingTextures: textureCheck.missing,
319
- fileSize: lm.fileSize,
320
320
  extras: { cubism: lm.cubism, defFile: lm.defFile, mocFile: lm.mocFile },
321
321
  };
322
322
  }
@@ -446,9 +446,9 @@ export function toBundleEntry(cfg, file, provider, owner = null) {
446
446
  /**
447
447
  * 容器列举的规模上限 —— 值来自**实测**,不是拍脑袋。
448
448
  *
449
- * 实测 6 个 enabled 资源根(2026-10 现场):
450
- * 文件最大深度 3(bd2)|目录数 max 535(azurlane)|容器命中最多 19(azurlane_bundle,全在根层)
451
- * nikke_2 的 3 个容器在**第二层**(`<角色名>/<包>`)—— 这正是"只扫根层"会漏掉的那类。
449
+ * 实测多个真实资源根:
450
+ * 文件最大深度 3 | 目录数数百 | 容器命中十几个
451
+ * 也有根的容器在**第二层**(`<角色名>/<包>`)—— 这正是"只扫根层"会漏掉的那类。
452
452
  * 深度取「实测 max + 1」,给未来更深的 Mod 类根留一层余量。
453
453
  *
454
454
  * 超限**绝不静默截断**:stopped 带回原因,由调用方写进 warnings
@@ -469,7 +469,7 @@ const BUNDLE_SCAN_MAX_HITS = 500;
469
469
  * "顺手统一成 listTree"会把冷启动拖回 31 秒 —— 这条注释就是防这个的。
470
470
  *
471
471
  * 只对**未知扩展名**的文件读 8 字节魔数,扩展名集合复用 tree 的 `KNOWN_FILE_EXT`(同一份真相):
472
- * 实测 bd2 / azurlane / azurlane_spine 三个大根的未知扩展名文件数都是 **0**,
472
+ * 实测常见资源根的未知扩展名文件数为 **0**,
473
473
  * 即这三个根一次文件打开都不需要,成本全在 readdir 本身。
474
474
  *
475
475
  * 返回 `byDir`(按目录聚合)是为将来「按 dirSignature 缓存」留的钩子:
@@ -535,9 +535,8 @@ export function findContainerFiles(rootPath, detectContainer, opts = {}) {
535
535
  /**
536
536
  * 列资源包根下的条目(递归,不再只看根层)。
537
537
  *
538
- * 为什么必须递归:资源包的实际摆法不统一 —— 有的根把包平铺在根层
539
- * (azurlane_bundle:19 个包全在 L0),有的按 `<角色名>/<包>` 分目录
540
- * (nikke_2:3 个包都在 L1)。只看根层时后者 catalog 条目为 0,
538
+ * 为什么必须递归:资源包的实际摆法不统一 —— 有的根把包平铺在根层,
539
+ * 有的按 `<角色名>/<包>` 分目录。只看根层时后者 catalog 条目为 0,
541
540
  * 表现是"资源包明明在盘上,模型列表里却没有"。
542
541
  *
543
542
  * @returns {{entries: Array, warnings: string[], skipped: number}}
@@ -646,7 +645,26 @@ const ROOT_PATH_PROBLEM_TEXT = {
646
645
  * 装配模型目录(合并该资源根下的 Spine 与 Live2D 两路扫描)。
647
646
  * @param {{config: object, spine: object, live2d: object}} deps
648
647
  */
649
- export function createCatalog({ config, spine, live2d, tree, plugins, unpack = null, entryStates = null }) {
648
+ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = null, entryStates = null, configFile = null }) {
649
+ /**
650
+ * 显示名缓存的**进程内快照**:按缓存文件的 mtime 判是否重读。
651
+ *
652
+ * 为什么不在每条条目上读盘:一次 catalog 会过上百条,每条 `readFileSync` 一次是白费;
653
+ * 而缓存文件只在"取到新名字"时变一次,用 mtime 就能精确知道该不该重读。
654
+ */
655
+ let displayNameSnapshot = { file: null, mtimeMs: -1, table: {} };
656
+ function displayNameTable() {
657
+ if (!configFile) return {};
658
+ const file = displayNameCacheFile(configFile);
659
+ let mtimeMs = -1;
660
+ try { mtimeMs = Number(fs.statSync(file).mtimeMs); } catch { return {}; } // 文件不存在 ⇒ 空表
661
+ if (displayNameSnapshot.file === file && displayNameSnapshot.mtimeMs === mtimeMs) {
662
+ return displayNameSnapshot.table;
663
+ }
664
+ const table = readDisplayNameCache(configFile);
665
+ displayNameSnapshot = { file, mtimeMs, table };
666
+ return table;
667
+ }
650
668
  /**
651
669
  * 解包缓存句柄(只读用途:查"这个包被哪个插件解出来过")。
652
670
  * 装配顺序上 store 在 data 之后创建(serve.mjs),所以留 setter 注入,
@@ -764,7 +782,7 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
764
782
  * @returns {{entries: Array, warnings: string[], scanErrors: Error[],
765
783
  * cachedAll: boolean, pathProblem: string|null}}
766
784
  */
767
- function scanRootEntries(cfg) {
785
+ async function scanRootEntries(cfg) {
768
786
  const entries = [];
769
787
  const warnings = [];
770
788
  /** 扫描过程中抛的错(用于判断 rootWarning 该说"扫不动"还是"真的空") */
@@ -775,7 +793,7 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
775
793
  const pathProblem = inspectRootPath(cfg.path);
776
794
 
777
795
  try {
778
- const scan = spine.getSpineModels(cfg, false);
796
+ const scan = await spine.getSpineModels(cfg, false);
779
797
  for (const m of scan.models) entries.push(toSpineEntry(cfg, m));
780
798
  if (scan.cached !== true) cachedAll = false;
781
799
  } catch (e) {
@@ -783,7 +801,7 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
783
801
  warnings.push(`spine 扫描失败:${e.message}`);
784
802
  }
785
803
  try {
786
- const scan = live2d.getLive2DModels(cfg, false);
804
+ const scan = await live2d.getLive2DModels(cfg, false);
787
805
  for (const lm of scan.models) entries.push(toLive2DEntry(cfg, lm));
788
806
  if (scan.cached !== true) cachedAll = false;
789
807
  } catch (e) {
@@ -801,14 +819,14 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
801
819
  return { entries, warnings, scanErrors, cachedAll, pathProblem, skipped: bundle.skipped };
802
820
  }
803
821
 
804
- function listCatalog(rootId) {
822
+ async function listCatalog(rootId) {
805
823
  const t0 = performance.now();
806
824
  const cfg = config.readConfig().find((r) => r.id === rootId);
807
825
  if (!cfg) {
808
826
  // 形状与其它接口的错误体保持一致;按约定这里用 404(资源根不存在)
809
827
  return { status: 404, body: { error: `未找到资源根: ${rootId}` } };
810
828
  }
811
- const { entries, warnings, scanErrors, cachedAll, pathProblem, skipped } = scanRootEntries(cfg);
829
+ const { entries, warnings, scanErrors, cachedAll, pathProblem, skipped } = await scanRootEntries(cfg);
812
830
  const { sawStale } = assembleEntryStates(cfg, entries);
813
831
  // §八 触发来源(三选一,别混成一条):这一根里只要有一条是"旧结论作废"排进来的,
814
832
  // 就说明这轮探测是**能力变化**引起的(fingerprint);否则是清单重建引起的(catalog)。
@@ -889,6 +907,8 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
889
907
  e.display = computed.display;
890
908
  e.support = computed.support;
891
909
  e.loadResult = computed.loadResult;
910
+ // 第四字段:列表显示名(工厂产出,前端只渲染)。null 表示没取到 ⇒ 前端回落既有规则。
911
+ e.displayName = computed.displayName || null;
892
912
  applyOwnerFallback(e, common.providers);
893
913
  // 回报给调用方:assembleEntryStates 要靠 pendingProbe 判断"这轮探测是不是能力变化引起的"
894
914
  return computed;
@@ -940,8 +960,13 @@ export function createCatalog({ config, spine, live2d, tree, plugins, unpack = n
940
960
  ...entryFacts,
941
961
  providerFingerprint: providerFp,
942
962
  assetFingerprint: assetFingerprintOf(e.size),
963
+ // 列表显示名:只从缓存里查(缓存由"选中/装载时触发 analyze"写入),
964
+ // 这里不做任何解析。查不到 ⇒ recompute 产出 null ⇒ 前端回落既有规则。
965
+ // 判失效用 size(条目自带),够用且不用为展示态多做一次 stat。
966
+ displayNameFor: () => lookupDisplayName(displayNameTable(), cfg.id, e.rel || e.name, { size: e.size }),
943
967
  })
944
- : { display: { accent: null, provider: null, candidates: e.candidates }, support: { state: 'unknown', detail: null }, loadResult: null, pendingProbe: false };
968
+ // 没注入 entryStates 时的等价形状:displayName 也要在(否则调用方要判 "字段在不在")
969
+ : { display: { accent: null, provider: null, candidates: e.candidates }, support: { state: 'unknown', detail: null }, loadResult: null, displayName: null, pendingProbe: false };
945
970
  // 待探测登记(§八 判据 a/b):**同步路径只登记**,绝不在这次请求里解析包体。
946
971
  // · 容器条目:从没结论,或旧结论因能力/文件变化作废 ⇒ 都要排
947
972
  // · 目录型条目:support 来自资产检查(缺贴图),与包内形态无关 ⇒ 不排