dsh-novel-game 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/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.3.1 — 2026-11-30
4
+
5
+ 文档补丁:README 的「共同作者 / 喜欢它?/ 许可证」按插件市场统一格式重写(版本前缀、角色说明、GitHub ⭐/Issue/PR 入口、MIT License 链接)。无代码变更,测试仍 28/28。
6
+
7
+ ## 0.3.0 — 2026-11-29
8
+
9
+ 新增 Godot 与 Unity(文本文件层)两个 P1 引擎,以及摘录改绑。
10
+
11
+ ### 新增
12
+
13
+ - **Godot**:`.pck` 归档(format v1/v2 头、条目索引、加密包拒绝、64MB 条目上限)+ 散装 `.tscn/.tres/.csv/.json/.txt/.po`;`text = "..."` 文本按节点分场景,剥离 BBCode;其它文本文件走通用嗅探解析。Godot 场景文本标低置信(UI/对话混排)。
14
+ - **Unity(文本文件层)**:检测 `*_Data/globalgamemanagers`、`Managed`、`UnityPlayer.dll`、`GameAssembly.dll`;读取 `*_Data/StreamingAssets/` 下的 CSV/JSON/TXT/PO/XML 本地化与对话表。序列化资产(`.assets`)、IL2CPP、加密 AB 包明确不支持。
15
+ - **摘录改绑**:`addPick` 记录原文 `quote`;`picks` 对失效摘录按原文找唯一候选;`game_pick action=remap` 把摘录改绑到候选行,不再只能标 stale。
16
+
17
+ ### 测试
18
+
19
+ - 28 项全过(新增 Godot PCK/`.tscn`、Unity StreamingAssets、摘录改绑)。
20
+
21
+ ### 已知限制
22
+
23
+ - Godot 场景文本无法区分 UI 与剧情,默认低置信;`[link]`/对话插件(Dialogic 等)未专门解析。
24
+ - Unity 只覆盖文本文件层;`.assets` 里的 TextAsset 不解析。
25
+ - GameMaker(`data.win` STRG)排在 0.3.1。
26
+ - 搜索/导出仍是全量扫描;索引分片与流式导出排在 0.3.1。
27
+
3
28
  ## 0.2.1 — 2026-11-29
4
29
 
5
30
  修复 Codex 对 0.1.0 代码审查发现的 P0/P1(记录:`docs/REVIEW-0.1.0.md`)。
package/README.md CHANGED
@@ -53,7 +53,9 @@ npm i dsh-novel-game
53
53
  | KiriKiri / KAG | 0.2.0 | `.xp3` 归档 + 散装 `.ks`:label、对白、`@jump/@call`、标签剥离 |
54
54
  | NScripter / ONScripter | 0.2.0 | `nscript.dat`(XOR)/`0.txt`:对白、`select` 选项、`goto/jumpf`;`.nsa` 报不支持 |
55
55
  | Wolf RPG Editor | 0.2.0(文本抢救) | `Data/*.dat` 里可读文本段;低置信,默认不显示/不导出 |
56
- | Godot / Unity / GameMaker | 0.3.0 计划 | — |
56
+ | Godot | 0.3.0 | `.pck`(v1/v2)与散装 `.tscn/.tres/.csv/.json/.txt`;`text = "..."` 按节点分场景 |
57
+ | Unity | 0.3.0(文本文件层) | `*_Data/StreamingAssets` 下的 CSV/JSON/TXT/PO 本地化与对话表 |
58
+ | GameMaker | 0.3.1 计划 | — |
57
59
 
58
60
  `.rpyc` 编译脚本在 0.1.0 不解反编译:会出现在覆盖率报告里并提示用 `unrpyc` 或提供明文脚本。
59
61
 
@@ -85,7 +87,7 @@ npm i dsh-novel-game
85
87
  | `game_routes` | 剧情路线图(节点/边/候选结局) |
86
88
  | `game_search` | 台词与词条检索 |
87
89
  | `game_characters` / `game_glossary` | 人物卡草稿 / 词条 |
88
- | `game_pick` | 同人准备篮(add / list) |
90
+ | `game_pick` | 同人准备篮(add / list / remap 改绑失效摘录) |
89
91
  | `game_export` | 导出三件套 |
90
92
 
91
93
  ## 开发
@@ -97,24 +99,24 @@ npm run check
97
99
 
98
100
  零运行时依赖;纯 Node ESM。
99
101
 
100
- ## 已知限制(0.2.1)
102
+ ## 已知限制(0.3.0)
101
103
 
102
- - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.1。
104
+ - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.3.1。
103
105
  - `.rpyc` 不反编译;`.rpa` 只支持受限 pickle 子集(白名单外拒绝)。
104
106
  - 不模拟 RPG Maker 的开关/变量;条件页并列展示为候选剧情,不声称实际游玩顺序。
105
107
  - Wolf RPG 只做文本抢救(`Game.dat` 常见加密,不破解);NScripter 的 `.nsa` 不解包。
106
- - KiriKiri 的 `[link]` 选项没有单独建边;Unity / Godot / GameMaker 未支持。
108
+ - KiriKiri 的 `[link]` 选项没有单独建边。
109
+ - Godot 场景文本分不清 UI 与剧情(低置信);Unity 只覆盖 StreamingAssets 文本层;GameMaker 未支持。
110
+ - 搜索/导出仍是全量扫描(索引分片与流式导出排 0.3.1)。
107
111
 
108
112
  ## 共同作者
109
113
 
110
- [@MiyueWinter](https://github.com/MiyueWinter)
114
+ 0.3.1 共同作者:[MiyueWinter](https://github.com/MiyueWinter) —— 文案、测试、设计与开发。
111
115
 
112
116
  ## 喜欢它?
113
117
 
114
- - [GitHub](https://github.com/DrizzleGig/dsh-novel-game)
115
- - [提交 Issue](https://github.com/DrizzleGig/dsh-novel-game/issues)
116
- - [发起 PR](https://github.com/DrizzleGig/dsh-novel-game/pulls)
118
+ 如果「游戏剧情解包」帮你把游戏里的剧情、文本和设定读出来了,欢迎在 [GitHub](https://github.com/DrizzleGig/dsh-novel-game) 点亮 ⭐,也欢迎 [Issue](https://github.com/DrizzleGig/dsh-novel-game/issues) 或 [PR](https://github.com/DrizzleGig/dsh-novel-game/pulls)。
117
119
 
118
120
  ## 许可证
119
121
 
120
- [MIT](LICENSE)
122
+ MIT License,见 [LICENSE](./LICENSE)。
package/docs/ENGINES.md CHANGED
@@ -67,9 +67,24 @@
67
67
  - 参考:[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)(加密与归档的权威实现;本插件不集成)。
68
68
  - 0.2.1 计划:`.wolf` 归档读取与明文 `Game.dat` 的结构化抽取。
69
69
 
70
- ## 0.3.0 计划
70
+ ## Godot(0.3.0)
71
71
 
72
- - Godot:`.pck` + `.tscn/.tres` + 翻译表。
73
- - Unity:`StreamingAssets` 本地化表、`TextAsset` 内嵌对话。
74
- - GameMaker:`data.win` 的 `STRG` 字符串表。
75
- - 参考:[Not-Parker/godot-pck-reader](https://github.com/Not-Parker/godot-pck-reader)、[AssetRipper/AssetRipper](https://github.com/AssetRipper/AssetRipper)、[UnderminersTeam/UndertaleModTool](https://github.com/UnderminersTeam/UndertaleModTool)。
72
+ - `.pck`:magic `GDPC`;v1/v2 头(v2 多 `flags` 与 `file_base`);条目 `path_len + path + offset/size(u64) + md5[16] + flags(v2)`,路径 4 字节对齐;`flags & 1` 视为加密包,直接拒绝。
73
+ - 散装项目:`project.godot`、`*.tscn`、`*.tres`、`*.csv/.json/.txt/.po`。
74
+ - `.tscn/.tres`:按 `[node name=... type=...]` 分场景,取 `text = "..."`,剥离 BBCode;标低置信(UI 与剧情混排)。
75
+ - CSV/JSON/TXT/PO:走通用嗅探解析。
76
+ - 不做:`.gd` 脚本、`.translation` 二进制、Dialogic 等插件专用格式(0.3.1 评估)。
77
+
78
+ ## Unity(0.3.0,文本文件层)
79
+
80
+ - 检测:`*_Data/globalgamemanagers`、`*_Data/Managed`、`StreamingAssets`、`UnityPlayer.dll`、`GameAssembly.dll`。
81
+ - 抽取:`*_Data/StreamingAssets/` 下 CSV/TSV/JSON/TXT/PO/XML,按通用嗅探解析;文件名作场景名,标低置信。
82
+ - 不做:`.assets`/AssetBundle/IL2CPP、`TextAsset` 二进制、加密 AB。
83
+ - 参考:[AssetRipper/AssetRipper](https://github.com/AssetRipper/AssetRipper)、[K0lb3/UnityPy](https://github.com/K0lb3/UnityPy)(仅格式参考,不集成)。
84
+
85
+ ## 0.3.1 计划
86
+
87
+ - GameMaker:`data.win` 的 `STRG` 字符串表与 `CODE` 引用。
88
+ - Godot:Dialogic/自定义对话格式、`.translation`。
89
+ - 检索索引分片 + 流式导出;KiriKiri `[link]` 建边;Wolf 抢救噪声过滤。
90
+ - 参考:[UnderminersTeam/UndertaleModTool](https://github.com/UnderminersTeam/UndertaleModTool)。
package/index.js CHANGED
@@ -248,7 +248,8 @@ const tools = [
248
248
  properties: {
249
249
  dir: dirParam,
250
250
  gameId: gameIdParam,
251
- action: { type: 'string', enum: ['add', 'list'] },
251
+ action: { type: 'string', enum: ['add', 'list', 'remap'] },
252
+ pickId: { type: 'string', description: 'action=remap 时要改绑的摘录 ID' },
252
253
  kind: { type: 'string', enum: ['line', 'scene', 'glossary', 'character'] },
253
254
  refId: { type: 'string' },
254
255
  note: { type: 'string' },
@@ -261,6 +262,7 @@ const tools = [
261
262
  execute: guarded(async (args, exec) => {
262
263
  const service = await serviceFor(await requireDir(args, exec));
263
264
  if (args.action === 'list') return service.picks(args.gameId);
265
+ if (args.action === 'remap') return service.remapPick(args.gameId, { pickId: args.pickId });
264
266
  return service.addPick(args.gameId, {
265
267
  kind: args.kind ?? 'line',
266
268
  refId: args.refId,
@@ -0,0 +1,234 @@
1
+ import path from 'node:path';
2
+ import { isPck, readPckEntry, readPckIndex } from '../archive/pck.mjs';
3
+ import { parseGenericFile } from './generic.mjs';
4
+
5
+ const TEXT_EXT = /\.(tscn|tres|csv|json|txt|po|md)$/i;
6
+ const BBCode = /\[\/?[a-zA-Z][^\]]*\]/g;
7
+
8
+ function unescapeTscn(value) {
9
+ return String(value)
10
+ .replace(/\\n/g, '\n')
11
+ .replace(/\\t/g, '\t')
12
+ .replace(/\\"/g, '"')
13
+ .replace(/\\\\/g, '\\');
14
+ }
15
+
16
+ /**
17
+ * Godot 场景/资源里的可见文本:`text = "..."`(Label/RichTextLabel 等)。
18
+ * 只做静态读取:不还原节点继承,不执行脚本。
19
+ */
20
+ export function* parseGodotText(text, { relPath, pathPrefix = '' }) {
21
+ const lines = String(text).split(/\r?\n/);
22
+ let node = null;
23
+ let nodeType = null;
24
+ let sceneKey = null;
25
+ let sceneOrder = 0;
26
+ let lineOrder = 0;
27
+
28
+ const ensureScene = function* () {
29
+ if (sceneKey) return;
30
+ sceneKey = `${relPath}#${pathPrefix}node:${node ?? 'root'}`;
31
+ yield {
32
+ type: 'scene',
33
+ key: sceneKey,
34
+ title: node ? `${node}${nodeType ? ` (${nodeType})` : ''}` : '场景文本',
35
+ container: relPath,
36
+ order: sceneOrder++,
37
+ conditions: null,
38
+ lowConfidence: true,
39
+ src: { relPath, path: `${pathPrefix}node:${node ?? 'root'}` },
40
+ };
41
+ };
42
+
43
+ for (let index = 0; index < lines.length; index += 1) {
44
+ const trimmed = lines[index].trim();
45
+ const nodeMatch = /^\[node\s+name="([^"]+)"(?:\s+type="([^"]+)")?/.exec(trimmed);
46
+ if (nodeMatch) {
47
+ node = nodeMatch[1];
48
+ nodeType = nodeMatch[2] ?? null;
49
+ sceneKey = null;
50
+ lineOrder = 0;
51
+ continue;
52
+ }
53
+ const textMatch = /^text\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/.exec(trimmed);
54
+ if (!textMatch) continue;
55
+ const value = unescapeTscn(textMatch[1]).replace(BBCode, '').trim();
56
+ if (!value || /^(res:\/\/|uid:\/\/|0$)/.test(value)) continue;
57
+ yield* ensureScene();
58
+ yield {
59
+ type: 'line',
60
+ sceneKey,
61
+ order: lineOrder++,
62
+ kind: 'narration',
63
+ speakerId: null,
64
+ speakerName: null,
65
+ text: value,
66
+ refs: {},
67
+ src: { relPath, path: `${pathPrefix}line:${index + 1}`, index },
68
+ };
69
+ }
70
+ }
71
+
72
+ function* parseTextFile(text, relPath, pathPrefix = '') {
73
+ const ext = path.extname(relPath).toLowerCase();
74
+ if (ext === '.tscn' || ext === '.tres') {
75
+ yield* parseGodotText(text, { relPath, pathPrefix });
76
+ return;
77
+ }
78
+ const parsed = parseGenericFile(text, relPath, ext);
79
+ if (parsed.length === 0) return;
80
+ const sceneKey = `${relPath}#${pathPrefix}file`;
81
+ yield {
82
+ type: 'scene',
83
+ key: sceneKey,
84
+ title: path.basename(relPath),
85
+ container: relPath,
86
+ order: 0,
87
+ conditions: null,
88
+ lowConfidence: true,
89
+ src: { relPath, path: `${pathPrefix}file` },
90
+ };
91
+ for (let index = 0; index < parsed.length; index += 1) {
92
+ const item = parsed[index];
93
+ if (!item.text?.trim()) continue;
94
+ yield {
95
+ type: 'line',
96
+ sceneKey,
97
+ order: index,
98
+ kind: item.speaker ? 'dialogue' : 'narration',
99
+ speakerId: item.speaker ? `name:${item.speaker}` : null,
100
+ speakerName: item.speaker || null,
101
+ text: item.text.trim(),
102
+ refs: {},
103
+ src: { relPath, path: `${pathPrefix}${item.addr}`, index },
104
+ };
105
+ }
106
+ }
107
+
108
+ async function walk(ctx, dir, extensions, depth = 2, level = 0, out = []) {
109
+ if (level > depth) return out;
110
+ for (const entry of await ctx.list(dir)) {
111
+ if (entry.dir) await walk(ctx, entry.rel, extensions, depth, level + 1, out);
112
+ else if (extensions.some((ext) => entry.name.toLowerCase().endsWith(ext))) out.push(entry.rel);
113
+ }
114
+ return out;
115
+ }
116
+
117
+ export const godot = {
118
+ id: 'godot',
119
+ label: 'Godot',
120
+
121
+ async detect(ctx) {
122
+ const evidence = [];
123
+ let score = 0;
124
+ if (await ctx.exists('project.godot')) {
125
+ score = 0.92;
126
+ evidence.push('project.godot');
127
+ }
128
+ const pcks = await walk(ctx, '.', ['.pck'], 1);
129
+ if (pcks.length) {
130
+ score = Math.max(score, 0.86);
131
+ evidence.push(`${pcks.length} 个 .pck`);
132
+ }
133
+ const scenes = await walk(ctx, '.', ['.tscn'], 2);
134
+ if (scenes.length) {
135
+ score = Math.max(score, score ? score : 0.8);
136
+ evidence.push(`${scenes.length} 个 .tscn`);
137
+ }
138
+ if (await ctx.exists('godot.exe') || (await ctx.list('.')).some((entry) => /godot/i.test(entry.name))) {
139
+ score = Math.max(score, score ? score : 0.72);
140
+ evidence.push('Godot 可执行文件/名称');
141
+ }
142
+ if (score === 0) return null;
143
+ return {
144
+ engineId: 'godot',
145
+ label: 'Godot',
146
+ confidence: score,
147
+ variant: 'godot',
148
+ evidence: [...new Set(evidence)],
149
+ title: path.basename(ctx.root),
150
+ pcks,
151
+ scenes,
152
+ };
153
+ },
154
+
155
+ async open(ctx, detection) {
156
+ const pcks = detection.pcks ?? (await walk(ctx, '.', ['.pck'], 1));
157
+ const loose = await walk(ctx, '.', ['.tscn', '.tres', '.csv', '.json', '.txt', '.po'], 2);
158
+ const containers = [
159
+ ...pcks.map((rel) => ({ rel, kind: 'archive', textBearing: true, note: 'PCK' })),
160
+ ...loose.map((rel) => ({ rel, kind: 'text', textBearing: true, note: '' })),
161
+ ];
162
+
163
+ return {
164
+ id: 'godot',
165
+ meta() {
166
+ return {
167
+ title: detection.title || path.basename(ctx.root),
168
+ engine: 'Godot',
169
+ variant: 'godot',
170
+ encrypted: false,
171
+ dataDir: '.',
172
+ pckCount: pcks.length,
173
+ fileCount: loose.length,
174
+ };
175
+ },
176
+ containers() {
177
+ return containers;
178
+ },
179
+ fingerprintFiles() {
180
+ return [...(detection.scenes ?? []).slice(0, 2), ...pcks.slice(0, 1)];
181
+ },
182
+
183
+ async *extract(options = {}) {
184
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
185
+
186
+ for (const rel of loose) {
187
+ if (!shouldRead(rel)) continue;
188
+ try {
189
+ const { text } = await ctx.readText(rel, 16 * 1024 * 1024);
190
+ yield* parseTextFile(text, rel);
191
+ } catch (error) {
192
+ yield { type: 'error', relPath: rel, message: error.message };
193
+ }
194
+ }
195
+
196
+ for (const rel of pcks) {
197
+ if (!shouldRead(rel)) continue;
198
+ let buffer;
199
+ try {
200
+ buffer = await ctx.readBuffer(rel, 1024 * 1024 * 1024);
201
+ } catch (error) {
202
+ yield { type: 'error', relPath: rel, message: error.message };
203
+ continue;
204
+ }
205
+ if (!isPck(buffer)) {
206
+ yield { type: 'error', relPath: rel, message: '不是 Godot PCK(可能嵌入可执行文件)' };
207
+ continue;
208
+ }
209
+ let info;
210
+ try {
211
+ info = readPckIndex(buffer);
212
+ } catch (error) {
213
+ yield { type: 'error', relPath: rel, message: error.message };
214
+ continue;
215
+ }
216
+ const encrypted = (info.flags & 1) === 1;
217
+ for (const entry of info.entries) {
218
+ if (!TEXT_EXT.test(entry.name)) continue;
219
+ let content;
220
+ try {
221
+ content = readPckEntry(buffer, entry, { encrypted });
222
+ } catch (error) {
223
+ yield { type: 'error', relPath: `${rel}!${entry.name}`, message: error.message };
224
+ continue;
225
+ }
226
+ yield* parseTextFile(content.toString('utf8'), entry.name, `${entry.name}:`);
227
+ }
228
+ }
229
+ },
230
+ };
231
+ },
232
+ };
233
+
234
+ export default godot;
@@ -4,8 +4,10 @@ import { generic } from './generic.mjs';
4
4
  import { kirikiri } from './kirikiri.mjs';
5
5
  import { nscripter } from './nscripter.mjs';
6
6
  import { wolf } from './wolf.mjs';
7
+ import { godot } from './godot.mjs';
8
+ import { unity } from './unity.mjs';
7
9
 
8
- export const ADAPTERS = [rpgmaker, renpy, kirikiri, nscripter, wolf, generic];
10
+ export const ADAPTERS = [rpgmaker, renpy, kirikiri, nscripter, wolf, godot, unity, generic];
9
11
 
10
12
  export function getAdapter(id) {
11
13
  return ADAPTERS.find((adapter) => adapter.id === id) ?? null;
@@ -0,0 +1,146 @@
1
+ import path from 'node:path';
2
+ import { parseGenericFile } from './generic.mjs';
3
+
4
+ const TEXT_EXT = ['.csv', '.json', '.txt', '.xml', '.po', '.tsv'];
5
+
6
+ async function walk(ctx, dir, depth = 3, level = 0, out = []) {
7
+ if (level > depth) return out;
8
+ for (const entry of await ctx.list(dir)) {
9
+ if (entry.dir) await walk(ctx, entry.rel, depth, level + 1, out);
10
+ else if (TEXT_EXT.includes(path.extname(entry.name).toLowerCase())) out.push(entry.rel);
11
+ }
12
+ return out;
13
+ }
14
+
15
+ async function findDataDirs(ctx) {
16
+ const dirs = [];
17
+ for (const entry of await ctx.list('.')) {
18
+ if (!entry.dir) continue;
19
+ if (/_Data$/i.test(entry.name) || entry.name.toLowerCase() === 'streamingassets') dirs.push(entry.rel);
20
+ }
21
+ return dirs;
22
+ }
23
+
24
+ /**
25
+ * Unity:0.3.0 只做「文本文件层」——StreamingAssets / *_Data 下的 CSV/JSON/TXT/PO 本地化表与对话表。
26
+ * 序列化资产(.assets)、IL2CPP、加密 AB 包不做。
27
+ */
28
+ export const unity = {
29
+ id: 'unity',
30
+ label: 'Unity(文本文件层)',
31
+
32
+ async detect(ctx) {
33
+ const evidence = [];
34
+ let score = 0;
35
+ const dataDirs = await findDataDirs(ctx);
36
+ for (const dir of dataDirs) {
37
+ const name = path.basename(dir);
38
+ if (/_Data$/i.test(name)) {
39
+ const hasGameManager = await ctx.exists(`${dir}/globalgamemanagers`);
40
+ const hasManaged = await ctx.exists(`${dir}/Managed`);
41
+ if (hasGameManager || hasManaged) {
42
+ score = Math.max(score, 0.9);
43
+ evidence.push(`${dir}/globalgamemanagers`);
44
+ }
45
+ }
46
+ if (name.toLowerCase() === 'streamingassets') {
47
+ const files = await walk(ctx, dir, 3);
48
+ if (files.length) {
49
+ score = Math.max(score, 0.8);
50
+ evidence.push(`${dir}/ 下 ${files.length} 个文本文件`);
51
+ }
52
+ }
53
+ }
54
+ for (const name of ['UnityPlayer.dll', 'GameAssembly.dll', 'UnityCrashHandler64.exe']) {
55
+ if (await ctx.exists(name)) {
56
+ score = Math.max(score, score ? score : 0.76);
57
+ evidence.push(name);
58
+ }
59
+ }
60
+ if (score === 0) return null;
61
+ return {
62
+ engineId: 'unity',
63
+ label: 'Unity(文本文件层)',
64
+ confidence: score,
65
+ variant: 'unity-text',
66
+ evidence,
67
+ title: path.basename(ctx.root),
68
+ dataDirs,
69
+ };
70
+ },
71
+
72
+ async open(ctx, detection) {
73
+ const dataDirs = detection.dataDirs ?? (await findDataDirs(ctx));
74
+ const files = [];
75
+ for (const dir of dataDirs) {
76
+ if (!/_Data$|streamingassets/i.test(dir)) continue;
77
+ for (const rel of await walk(ctx, dir, 3)) files.push(rel);
78
+ }
79
+ const unique = [...new Set(files)].sort();
80
+
81
+ return {
82
+ id: 'unity',
83
+ meta() {
84
+ return {
85
+ title: detection.title || path.basename(ctx.root),
86
+ engine: 'Unity(文本文件层)',
87
+ variant: 'unity-text',
88
+ encrypted: false,
89
+ dataDir: dataDirs.join(', '),
90
+ fileCount: unique.length,
91
+ };
92
+ },
93
+ containers() {
94
+ return unique.map((rel) => ({ rel, kind: 'text', textBearing: true, note: 'StreamingAssets 文本' }));
95
+ },
96
+ fingerprintFiles() {
97
+ return unique.slice(0, 3);
98
+ },
99
+
100
+ async *extract(options = {}) {
101
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
102
+ let sceneOrder = 0;
103
+ for (const rel of unique) {
104
+ if (!shouldRead(rel)) continue;
105
+ let parsed = [];
106
+ try {
107
+ const { text } = await ctx.readText(rel, 16 * 1024 * 1024);
108
+ parsed = parseGenericFile(text, rel);
109
+ } catch (error) {
110
+ yield { type: 'error', relPath: rel, message: error.message };
111
+ continue;
112
+ }
113
+ if (parsed.length === 0) continue;
114
+ const sceneKey = `${rel}#file`;
115
+ yield {
116
+ type: 'scene',
117
+ key: sceneKey,
118
+ title: path.basename(rel),
119
+ container: rel,
120
+ order: sceneOrder++,
121
+ conditions: null,
122
+ lowConfidence: true,
123
+ src: { relPath: rel, path: 'file' },
124
+ };
125
+ for (let index = 0; index < parsed.length; index += 1) {
126
+ const item = parsed[index];
127
+ if (!item.text?.trim()) continue;
128
+ yield {
129
+ type: 'line',
130
+ sceneKey,
131
+ order: index,
132
+ kind: item.speaker ? 'dialogue' : 'narration',
133
+ speakerId: item.speaker ? `name:${item.speaker}` : null,
134
+ speakerName: item.speaker || null,
135
+ text: item.text.trim(),
136
+ refs: {},
137
+ src: { relPath: rel, path: item.addr, index },
138
+ };
139
+ }
140
+ }
141
+ },
142
+ };
143
+ },
144
+ };
145
+
146
+ export default unity;
@@ -0,0 +1,67 @@
1
+ import { GameError, ErrorCode } from '../core/errors.mjs';
2
+
3
+ const MAGIC = Buffer.from('GDPC', 'ascii');
4
+ const MAX_ENTRIES = 200000;
5
+
6
+ export function isPck(buffer) {
7
+ return buffer.length > 24 && buffer.subarray(0, 4).equals(MAGIC);
8
+ }
9
+
10
+ function align4(value) {
11
+ return (value + 3) & ~3;
12
+ }
13
+
14
+ /**
15
+ * 读取 Godot .pck 索引(format v1/v2)。
16
+ * v2 头:magic + version + major/minor/patch + flags + file_base + 16*u32 reserved + count
17
+ * 条目:path_len + path(utf8, 4 字节对齐) + offset u64 + size u64 + md5[16] + flags(v2)
18
+ */
19
+ export function readPckIndex(buffer) {
20
+ if (!isPck(buffer)) throw new GameError(ErrorCode.PARSE_ERROR, '不是 Godot .pck 归档');
21
+ let pos = 4;
22
+ const version = buffer.readUInt32LE(pos);
23
+ pos += 4;
24
+ if (version !== 1 && version !== 2) {
25
+ throw new GameError(ErrorCode.PARSE_ERROR, `不支持的 PCK 版本:${version}`);
26
+ }
27
+ const engine = { major: buffer.readUInt32LE(pos), minor: buffer.readUInt32LE(pos + 4), patch: buffer.readUInt32LE(pos + 8) };
28
+ pos += 12;
29
+ let flags = 0;
30
+ let fileBase = 0;
31
+ if (version === 2) {
32
+ flags = buffer.readUInt32LE(pos);
33
+ pos += 4;
34
+ fileBase = Number(buffer.readBigUInt64LE(pos));
35
+ pos += 8;
36
+ }
37
+ pos += 16 * 4; // reserved
38
+ const count = buffer.readUInt32LE(pos);
39
+ pos += 4;
40
+ if (count > MAX_ENTRIES) throw new GameError(ErrorCode.PARSE_ERROR, `PCK 条目超过上限:${count}`);
41
+
42
+ const entries = [];
43
+ for (let i = 0; i < count; i += 1) {
44
+ if (pos + 4 > buffer.length) break;
45
+ const pathLen = buffer.readUInt32LE(pos);
46
+ pos += 4;
47
+ if (pos + pathLen > buffer.length) break;
48
+ const name = buffer.toString('utf8', pos, pos + pathLen);
49
+ pos = align4(pos + pathLen);
50
+ const offset = Number(buffer.readBigUInt64LE(pos));
51
+ const size = Number(buffer.readBigUInt64LE(pos + 8));
52
+ pos += 16 + 16;
53
+ if (version === 2) pos += 4;
54
+ entries.push({ name, offset: offset + (version === 2 ? fileBase : 0), size });
55
+ }
56
+ return { version, engine, flags, entries };
57
+ }
58
+
59
+ /** 读一个 PCK 条目;加密包直接拒绝。 */
60
+ export function readPckEntry(buffer, entry, { encrypted = false, maxBytes = 64 * 1024 * 1024 } = {}) {
61
+ if (encrypted) throw new GameError(ErrorCode.ENCRYPTED, 'PCK 加密(需要游戏自身的 key),本插件不解密');
62
+ if (entry.size > maxBytes) throw new GameError(ErrorCode.INVALID_INPUT, `PCK 条目超过上限:${entry.name}`);
63
+ if (entry.offset < 0 || entry.offset + entry.size > buffer.length) {
64
+ throw new GameError(ErrorCode.PARSE_ERROR, `PCK 条目越界:${entry.name}`);
65
+ }
66
+ return buffer.subarray(entry.offset, entry.offset + entry.size);
67
+ }
package/lib/service.mjs CHANGED
@@ -335,10 +335,20 @@ export class GameService {
335
335
  async addPick(gameId, { kind = 'line', refId, note = '', tags = [] } = {}) {
336
336
  if (!refId) throw new GameError(ErrorCode.INVALID_INPUT, 'refId 不能为空');
337
337
  const manifest = await this.manifest(gameId);
338
+ let quote = '';
339
+ if (kind === 'line') {
340
+ for await (const row of this.store.iterateShards(gameId, manifest.activeGeneration)) {
341
+ if (row.t === 'line' && row.lineId === refId) {
342
+ quote = String(row.text ?? '').slice(0, MAX_QUOTE);
343
+ break;
344
+ }
345
+ }
346
+ }
338
347
  const pick = {
339
348
  pickId: pickIdOf(gameId, kind, refId),
340
349
  kind,
341
350
  refId,
351
+ quote,
342
352
  note: String(note ?? ''),
343
353
  tags: Array.isArray(tags) ? tags.map(String) : [],
344
354
  generation: manifest.activeGeneration,
@@ -352,14 +362,47 @@ export class GameService {
352
362
  const rows = await this.store.readPicks(gameId);
353
363
  const { genId } = await this.active(gameId);
354
364
  const lineIds = new Set();
365
+ const textIndex = new Map();
355
366
  for await (const row of this.store.iterateShards(gameId, genId)) {
356
- if (row.t === 'line') lineIds.add(row.lineId);
367
+ if (row.t !== 'line') continue;
368
+ lineIds.add(row.lineId);
369
+ const text = String(row.text ?? '');
370
+ if (text) {
371
+ const list = textIndex.get(text) ?? [];
372
+ list.push({ lineId: row.lineId, sceneId: row.sceneId });
373
+ textIndex.set(text, list);
374
+ }
357
375
  }
358
- const items = rows.map((row) => ({
359
- ...row,
360
- stale: row.kind === 'line' ? !lineIds.has(row.refId) : false,
361
- }));
362
- return { gameId, total: items.length, items, staleCount: items.filter((row) => row.stale).length };
376
+ const items = rows.map((row) => {
377
+ const stale = row.kind === 'line' ? !lineIds.has(row.refId) : false;
378
+ let candidate = null;
379
+ if (stale && row.quote) {
380
+ const found = (textIndex.get(row.quote) ?? []).filter((entry) => entry.lineId !== row.refId);
381
+ if (found.length === 1) candidate = found[0];
382
+ }
383
+ return { ...row, stale, candidate };
384
+ });
385
+ return {
386
+ gameId,
387
+ total: items.length,
388
+ items,
389
+ staleCount: items.filter((row) => row.stale).length,
390
+ remappable: items.filter((row) => row.candidate).length,
391
+ };
392
+ }
393
+
394
+ /** 把失效摘录改绑到候选行(只改插件自己的 picks)。 */
395
+ async remapPick(gameId, { pickId } = {}) {
396
+ if (!pickId) throw new GameError(ErrorCode.INVALID_INPUT, 'pickId 不能为空');
397
+ const current = await this.picks(gameId);
398
+ const target = current.items.find((row) => row.pickId === pickId);
399
+ if (!target) throw new GameError(ErrorCode.NOT_FOUND, `摘录不存在:${pickId}`);
400
+ if (!target.candidate) throw new GameError(ErrorCode.NOT_FOUND, '没有唯一候选可改绑(可能文本已变或有多处相同)');
401
+ const rows = (await this.store.readPicks(gameId)).map((row) => (row.pickId === pickId
402
+ ? { ...row, refId: target.candidate.lineId, remappedFrom: row.refId, remappedAt: nowIso() }
403
+ : row));
404
+ await this.store.writePicks(gameId, rows);
405
+ return { pickId, refId: target.candidate.lineId, remappedFrom: target.refId };
363
406
  }
364
407
 
365
408
  /**
package/lib/store.mjs CHANGED
@@ -177,6 +177,11 @@ export class GameStore {
177
177
  return pick;
178
178
  }
179
179
 
180
+ async writePicks(gameId, rows) {
181
+ await writeJsonl(this.picksPath(gameId), rows);
182
+ return rows;
183
+ }
184
+
180
185
  async readNotes(gameId) {
181
186
  return (await readJson(this.notesPath(gameId))) ?? { schemaVersion: SCHEMA_VERSION, notes: [] };
182
187
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-novel-game",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "DSH 小说插件·游戏剧情:解包本地合法游戏副本中玩家可见的剧情/文本/设定,整理成可浏览、可检索、可摘录的 canon,供同人创作参考;只写 .dsh-novel-game/,游戏目录只读。",
5
5
  "type": "module",
6
6
  "main": "index.js",