dsh-novel-game 0.1.0 → 0.2.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,49 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.2.1 — 2026-11-29
4
+
5
+ 修复 Codex 对 0.1.0 代码审查发现的 P0/P1(记录:`docs/REVIEW-0.1.0.md`)。
6
+
7
+ ### 修复
8
+
9
+ - **任务 ID 路径穿越**:`jobs` 读写先校验 jobId 只允许 `[A-Za-z0-9_-]`,并走插件根路径守卫。
10
+ - **游戏/插件目录互相包含**:工作区在游戏目录内、或游戏目录在 `.dsh-novel-game/` 内,直接拒绝(防止写入落进游戏目录)。
11
+ - **同标题不同目录共用 gameId**:检测到冲突时把游戏根路径掺进 gameId,两个副本不再互相覆盖。
12
+ - **并发导入**:同一游戏根加文件锁(`locks/<hash>.lock`,10 分钟过期),冲突返回 `BUSY`。
13
+ - **manifest 损坏**:读 manifest 区分「不存在」与「损坏」;损坏时抛 `IO_ERROR`,不再当首次导入、不会 prune 掉旧代。
14
+ - **归档增量丢内容**:`.rpa`/`.xp3` 内文本统一用外层归档作为容器键(条目名进 `src.path`),增量重导不再丢归档内剧情。
15
+ - **删除来源残留**:合并旧聚合前先与当前容器集合求交,删掉的地图/脚本不再留下场景、选项、词条。
16
+ - **Ren'Py 菜单分支体**:选项块里的对白/跳转继续解析(只跳过选项标签行);label 边界重置菜单提示。
17
+ - **复用与计数**:分片复制失败回退重抽;行/资产/未解析/条件计数从新代分片重算,不再报 0;词条型文件无分片时不误判失败。
18
+ - **只读探测副作用**:`game_detect` 不再创建 `games/`、`jobs/`。
19
+
20
+ ### 测试
21
+
22
+ - 25 项全过(新增 7 项回归:归档增量、删除来源、manifest 损坏、jobId 越界、重复 gameId、目录边界、菜单分支体)。
23
+
24
+ ## 0.2.0 — 2026-11-29
25
+
26
+ 新增 KiriKiri / NScripter 两个 Galgame 引擎、Wolf RPG 文本抢救、剧情路线图与摘录失效标记。
27
+
28
+ ### 新增
29
+
30
+ - **KiriKiri / KAG**:`.xp3` 归档(XP3 头、zlib/未压缩索引、File/info/data chunk;条目 zlib 解压)+ `.ks` 剧本(label、文本行、`@jump/@call`、标签剥离、说话人「名字「…」/名字:…」);散装 `.ks` 与归档内 `.ks` 都读。
31
+ - **NScripter / ONScripter**:`nscript.dat`(逐字节 XOR 0x84)与 `0.txt`/`*.nscript`;`*label`、`select` 选项、`goto/jumpf`、命令白名单(`bg/ld/play/…` 当演出指令跳过);`.nsa` 记为不支持容器(通常只放图片/音频)。
32
+ - **Wolf RPG Editor(文本抢救)**:检测 `Data/`、`Data.wolf`、`Game.exe`;从 `Data/*.dat`/`*.mps` 里扫描可读文本段(UTF-16LE/UTF-8),标为低置信场景;默认不进可见范围与导出,需 `settings.includeLowConfidence=true`。
33
+ - **剧情路线图**:`game_routes` 工具 + 面板「路线图」;场景为节点,选项/跳转为边,标签解析为场景;未解析边单独计数,候选结局 = 无出边的场景。
34
+ - **摘录失效标记**:`game_pick` 列表对找不到的 `lineId` 标 `stale`(结构变化不再静默丢引用)。
35
+ - **低置信开关**:`includeLowConfidence` 控制 Wolf 抢救文本是否参与浏览/导出。
36
+
37
+ ### 测试
38
+
39
+ - 18 项全过:新增 XP3 索引/条目、KiriKiri 解析、NScripter XOR 与选项、Wolf 抢救与低置信过滤、路线图、摘录 stale。
40
+
41
+ ### 已知限制
42
+
43
+ - Wolf 只做文本抢救(`Game.dat` 常见加密,不破解);`.nsa` 不解包。
44
+ - `.rpyc` 仍不反编译;KiriKiri 的 `[link]` 选项文本未单独建边(只做文本行与 jump)。
45
+ - 大 JSON 仍整文件解析(0.2.1 排流式 tokenizer)。
46
+
3
47
  ## 0.1.0 — 2026-11-29
4
48
 
5
49
  首个可用版本:本地合法游戏副本的剧情/文本/设定解包,右栏六页面板,三件套单向导出。
package/README.md CHANGED
@@ -19,7 +19,7 @@ DSH 插件:Host 工具 + 右侧栏六页面板。只处理你自己合法持
19
19
  ## 它不做什么
20
20
 
21
21
  - 不解析完整游戏代码、不反编译着色器/引擎运行时;只抽「玩家可见内容」。
22
- - 不解密图片/音频、不复制素材、不生成缩略图(0.1.0)。
22
+ - 不解密图片/音频、不复制素材、不生成缩略图(0.2.0)。
23
23
  - 不做盗版下载、不绕过 DRM/在线验证、不处理手游/联机/抽卡的服务端内容。
24
24
  - 不写其它 `.dsh-novel-*/` 目录;与 fanfic/kit 只做单向导出。
25
25
 
@@ -50,7 +50,9 @@ npm i dsh-novel-game
50
50
  | RPG Maker MV / MZ | 0.1.0 | 地图/公共/战斗事件的对白与选项、角色/物品/技能/敌人/系统词条、图片与 BGM 引用 |
51
51
  | Ren'Py | 0.1.0 | 明文 `.rpy` 的 label、Character、say、menu、jump/call、scene/show、voice;`.rpa` 内文本条目 |
52
52
  | 通用文本嗅探 | 0.1.0 | JSON/CSV/PO/Yarn/Ink/TXT/SRT 里的对话候选(低置信,需核对) |
53
- | KiriKiri / NScripter / Wolf RPG | 0.2.0 计划 | — |
53
+ | KiriKiri / KAG | 0.2.0 | `.xp3` 归档 + 散装 `.ks`:label、对白、`@jump/@call`、标签剥离 |
54
+ | NScripter / ONScripter | 0.2.0 | `nscript.dat`(XOR)/`0.txt`:对白、`select` 选项、`goto/jumpf`;`.nsa` 报不支持 |
55
+ | Wolf RPG Editor | 0.2.0(文本抢救) | `Data/*.dat` 里可读文本段;低置信,默认不显示/不导出 |
54
56
  | Godot / Unity / GameMaker | 0.3.0 计划 | — |
55
57
 
56
58
  `.rpyc` 编译脚本在 0.1.0 不解反编译:会出现在覆盖率报告里并提示用 `unrpyc` 或提供明文脚本。
@@ -80,6 +82,7 @@ npm i dsh-novel-game
80
82
  | `game_detect` | 只探测不写入 |
81
83
  | `game_import` / `game_job_status` / `game_cancel_job` | 后台导入与进度 |
82
84
  | `game_scenes` / `game_scene` | 场景列表 / 场景台词与选项 |
85
+ | `game_routes` | 剧情路线图(节点/边/候选结局) |
83
86
  | `game_search` | 台词与词条检索 |
84
87
  | `game_characters` / `game_glossary` | 人物卡草稿 / 词条 |
85
88
  | `game_pick` | 同人准备篮(add / list) |
@@ -94,12 +97,13 @@ npm run check
94
97
 
95
98
  零运行时依赖;纯 Node ESM。
96
99
 
97
- ## 已知限制(0.1.0)
100
+ ## 已知限制(0.2.1)
98
101
 
99
- - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.0。
102
+ - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.1。
100
103
  - `.rpyc` 不反编译;`.rpa` 只支持受限 pickle 子集(白名单外拒绝)。
101
104
  - 不模拟 RPG Maker 的开关/变量;条件页并列展示为候选剧情,不声称实际游玩顺序。
102
- - Unity / Godot / GameMaker 未支持。
105
+ - Wolf RPG 只做文本抢救(`Game.dat` 常见加密,不破解);NScripter 的 `.nsa` 不解包。
106
+ - KiriKiri 的 `[link]` 选项没有单独建边;Unity / Godot / GameMaker 未支持。
103
107
 
104
108
  ## 共同作者
105
109
 
package/client.js CHANGED
@@ -35,6 +35,7 @@ window.__ModuleLoader__.load({
35
35
  invoke("scenes", [param("options", obj)]),
36
36
  invoke("scene", [param("options", obj)]),
37
37
  invoke("search", [param("options", obj)]),
38
+ invoke("routes", [param("options", obj)]),
38
39
  invoke("characters", [param("options", obj)]),
39
40
  invoke("glossary", [param("options", obj)]),
40
41
  invoke("picks", [param("options", obj)]),
@@ -111,6 +112,7 @@ window.__ModuleLoader__.load({
111
112
  const [query, setQuery] = React.useState("");
112
113
  const [results, setResults] = React.useState(null);
113
114
  const [cast, setCast] = React.useState(null);
115
+ const [routes, setRoutes] = React.useState(null);
114
116
  const [terms, setTerms] = React.useState(null);
115
117
  const [picks, setPicks] = React.useState(null);
116
118
  const [exported, setExported] = React.useState(null);
@@ -220,6 +222,11 @@ window.__ModuleLoader__.load({
220
222
  if (value) setPicks(value);
221
223
  }
222
224
 
225
+ async function loadRoutes() {
226
+ const value = await run(async () => unwrap(await remote.routes(sessionId, { gameId })));
227
+ if (value) setRoutes(value);
228
+ }
229
+
223
230
  async function addPick(line) {
224
231
  const value = await run(async () => unwrap(await remote.addPick(sessionId, { gameId, kind: "line", refId: line.lineId })));
225
232
  if (value) flash("已收进同人准备篮");
@@ -302,6 +309,19 @@ window.__ModuleLoader__.load({
302
309
  }
303
310
 
304
311
  function renderStory() {
312
+ if (routes) {
313
+ const titleOf = (id) => routes.nodes.find((node) => node.sceneId === id)?.title ?? id;
314
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
315
+ h("div", { style: S.row }, h(Btn, { onClick: () => setRoutes(null) }, "← 场景列表"), h("b", null, "路线图")),
316
+ h("div", { style: S.sub }, `节点 ${routes.nodes.length} · 边 ${routes.edges.length} · 未解析 ${routes.unresolved}`),
317
+ ...routes.edges.filter((edge) => edge.resolved).slice(0, 80).map((edge, index) => h("div", { key: index, style: S.sub },
318
+ `${titleOf(edge.from)} → ${titleOf(edge.to)}(${edge.kind === "choice" ? "选项" : "跳转"}:${edge.label})`,
319
+ )),
320
+ h("div", { style: { ...S.row, marginTop: 6 } }, h("b", null, "候选结局")),
321
+ ...routes.endings.slice(0, 40).map((id) => h("div", { key: id, style: S.sub }, titleOf(id))),
322
+ h("div", { style: { ...S.sub, marginTop: 6 } }, routes.note ?? ""),
323
+ );
324
+ }
305
325
  if (detail) {
306
326
  return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
307
327
  h("div", { style: S.row },
@@ -327,6 +347,7 @@ window.__ModuleLoader__.load({
327
347
  }
328
348
  const items = scenes?.items ?? [];
329
349
  return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
350
+ h("div", { style: S.row }, h("span", { style: S.sub }, `共 ${scenes?.total ?? 0} 场`), h(Btn, { onClick: loadRoutes, disabled: busy || !gameId }, "路线图")),
330
351
  items.length === 0 ? h("div", { style: S.empty }, "这个游戏还没有可浏览的场景。") : null,
331
352
  ...items.map((scene) => h("div", {
332
353
  key: scene.sceneId, style: { ...S.card, cursor: "pointer" },
package/docs/ENGINES.md CHANGED
@@ -43,9 +43,33 @@
43
43
  - SRT:按 cue 合并文本行。
44
44
  - 编码:BOM 优先;否则 UTF-8 / GB18030 / Shift-JIS / Big5 里选坏字符最少者。
45
45
 
46
- ## 0.2.0 计划
46
+ ## KiriKiri / KAG(0.2.0)
47
47
 
48
- - KiriKiri:`.xp3` 索引 + `.ks` 的 KAG 标签。
49
- - NScripter:`nscript.dat`(XOR 0x84)/ `0.txt`、`arc.nsa`。
50
- - Wolf RPG:`.wolf` 归档、`Game.dat`、地图/公共事件数据库。
51
- - 参考:[morkt/GARbro](https://github.com/morkt/GARbro)、[stmkza/xp3.js](https://github.com/stmkza/xp3.js)、[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)、[danmig06/nscript.dat-tool](https://github.com/danmig06/nscript.dat-tool)。
48
+ - 归档:`.xp3` 头 11 字节 `XP3\r\n \x1a\x8b\x67\x01`,其后 u64 索引偏移;索引多数为 zlib 压缩,少数未压缩(读取时先试 inflate,失败按原文解析)。
49
+ - 索引为 chunk 流:`File`(0x656C6946)chunk 内含 `info`(u16 名称长度 + UTF-16LE 名称 + 文件大小)与 `data`(offset / packedSize / unpackedSize 三个 u64)。
50
+ - 条目:`packedSize === unpackedSize` 视为未压缩,否则 zlib 解压;有 64MB 上限。
51
+ - 剧本:`.ks` 的 `*label`、文本行、`[tag]` 剥离、`@jump/@call target=...`;`@bg` 等演出指令计入未解析。
52
+ - 参考:[stmkza/xp3.js](https://github.com/stmkza/xp3.js)、[morkt/GARbro](https://github.com/morkt/GARbro)。
53
+ - 已知缺口:`[link]` 选项未建边;加密/定制 xp3 只报错。
54
+
55
+ ## NScripter / ONScripter(0.2.0)
56
+
57
+ - `nscript.dat` 为逐字节 XOR 0x84 的脚本(`*` 0x2A → 0xAE 可作签名);`0.txt`/`*.nscript` 为明文。
58
+ - 语法:`*label`、`select "文本",*标签,...`、`goto/jumpf`、命令白名单(`bg/ld/play/stop/wait/…`)跳过;文本行剥离 `\n` 等转义。
59
+ - `.nsa` 不解包(通常只放图片/音频),在覆盖率里标「不支持」。
60
+ - 参考:[danmig06/nscript.dat-tool](https://github.com/danmig06/nscript.dat-tool)。
61
+
62
+ ## Wolf RPG Editor(0.2.0,文本抢救)
63
+
64
+ - 检测:`Data/`、`Data.wolf`、`Game.exe`。
65
+ - `Game.dat` 常见加密,**不破解**;对 `Data/*.dat`、`MapData/*.mps` 做 UTF-16LE / UTF-8 可读文本段扫描(含 CJK 或句末标点/长英文句),去重后作为低置信旁白。
66
+ - 低置信场景默认不参与浏览与导出;`settings.includeLowConfidence=true` 才显示。
67
+ - 参考:[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)(加密与归档的权威实现;本插件不集成)。
68
+ - 0.2.1 计划:`.wolf` 归档读取与明文 `Game.dat` 的结构化抽取。
69
+
70
+ ## 0.3.0 计划
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)。
@@ -0,0 +1,39 @@
1
+ # dsh-novel-game — Codex 0.1.0 代码审查与修复(2026-11-29)
2
+
3
+ > 审查:桌面端 Codex,只读,按 P0/P1/P2 带文件行号输出(`tmp/2026-11-29-game-0.1.0-Codex审查任务书.md`)。
4
+ > 修复版本:**0.2.1**。测试:25/25 通过。
5
+
6
+ ## 已修(P0/P1)
7
+
8
+ | Codex 结论 | 修复 |
9
+ |---|---|
10
+ | 任务 ID 路径越界 | `jobs` 读写前 `assertSafeId` + `pluginPath`,`../` 直接 `INVALID_INPUT` |
11
+ | 存储根/游戏目录边界未验证 | `assertSeparateRoots`:游戏目录在插件目录内、或工作区在游戏目录内,都拒绝 |
12
+ | 重复 gameId 冲突 | 同指纹不同 root 时把 root 掺进 `gameId`(`gameIdOf` 支持 salt) |
13
+ | 并发导入丢更新 | 按游戏根加文件锁,10 分钟过期,冲突 `BUSY` |
14
+ | 损坏 manifest 后旧代可能被 prune | `readManifest` 区分 ENOENT 与损坏;损坏抛 `IO_ERROR`,不进入 finalize |
15
+ | RPA 增量重导丢内容 | 归档内文本统一外层归档 relPath,条目名进 `src.path`;场景/分片/覆盖率同一容器键 |
16
+ | 删除来源残留 | 合并旧聚合前与当前容器集合求交 |
17
+ | Ren'Py 菜单分支体漏解析 | 只跳过选项标签行,分支体继续解析;label 边界重置 `lastText` |
18
+
19
+ ## 顺带修(P2)
20
+
21
+ - 复用分片复制失败 → 回退重抽,不再标 `reused`。
22
+ - 计数从新代分片重算(修复复用文件 `lines/assets/skipped/conditions` 报 0)。
23
+ - 词条型文件无分片时不再误判复制失败。
24
+ - `game_detect` 不再创建目录(只读探测真正只读)。
25
+ - generation 保留数改为「当前代 + 上一代」总 2 代,与注释一致。
26
+
27
+ ## 未修 / 排到 0.3.0
28
+
29
+ | 结论 | 原因 |
30
+ |---|---|
31
+ | 搜索/导出全量扫描、内存峰值 | 需要索引与流式导出,0.3.0 统一做 |
32
+ | 通用嗅探的 JSON/CSV 启发式误判 | 需要更强的置信度与人工确认流 |
33
+ | KiriKiri `[link]` 选项未建边 | 需要解析 link 块结构 |
34
+ | Wolf 文本抢救噪声 | 低置信已隔离,后续做白名单/词典过滤 |
35
+ | 游戏目录只读的 OS 级保证 | 目前是代码级只读;OS 级只读需要平台能力 |
36
+
37
+ ## 结论
38
+
39
+ P0 全部修复;P1 全部修复;P2 中影响正确性的部分已修,性能与启发式问题登记到 0.3.0。发布 0.2.1。
package/index.js CHANGED
@@ -41,9 +41,9 @@ async function requireDir(args, exec) {
41
41
  return dir;
42
42
  }
43
43
 
44
- async function serviceFor(dir) {
44
+ async function serviceFor(dir, { init = true } = {}) {
45
45
  const service = new GameService({ workspace: dir });
46
- await service.init();
46
+ if (init) await service.init();
47
47
  return service;
48
48
  }
49
49
 
@@ -89,7 +89,7 @@ const tools = [
89
89
  },
90
90
  output,
91
91
  execute: guarded(async (args, exec) => {
92
- const service = await serviceFor(await requireDir(args, exec));
92
+ const service = await serviceFor(await requireDir(args, exec), { init: false });
93
93
  return service.detect({ gameRoot: path.resolve(args.path) });
94
94
  }),
95
95
  },
@@ -269,6 +269,21 @@ const tools = [
269
269
  });
270
270
  }),
271
271
  },
272
+ {
273
+ name: 'game_routes',
274
+ description: '剧情路线图:场景节点、选项/跳转边、候选结局;未解析边单独标出。',
275
+ parameters: {
276
+ type: 'object',
277
+ properties: { dir: dirParam, gameId: gameIdParam },
278
+ required: ['dir', 'gameId'],
279
+ additionalProperties: false,
280
+ },
281
+ output,
282
+ execute: guarded(async (args, exec) => {
283
+ const service = await serviceFor(await requireDir(args, exec));
284
+ return service.routes(args.gameId);
285
+ }),
286
+ },
272
287
  {
273
288
  name: 'game_export',
274
289
  description: '导出三件套到 .dsh-novel-game/exports/:story.md(可给 fanfic /fic import)、canon.json、brief.md。',
@@ -0,0 +1,196 @@
1
+ import path from 'node:path';
2
+ import { isXp3, readXp3Entry, readXp3Index } from '../archive/xp3.mjs';
3
+
4
+ /**
5
+ * KAG 剧本解析(KiriKiri .ks)。
6
+ * 只做静态解析:标签、文本行、跳转;不解释表达式、不执行。
7
+ */
8
+ export function* parseKagScript(text, { relPath, pathPrefix = '' }) {
9
+ const lines = String(text).split(/\r?\n/);
10
+ let sceneKey = null;
11
+ let sceneOrder = 0;
12
+ let lineOrder = 0;
13
+ let label = null;
14
+
15
+ const ensureScene = function* () {
16
+ if (sceneKey) return;
17
+ sceneKey = `${relPath}#${pathPrefix}top`;
18
+ yield { type: 'scene', key: sceneKey, title: '开场', container: relPath, order: sceneOrder++, conditions: null, src: { relPath, path: `${pathPrefix}top` } };
19
+ };
20
+
21
+ for (let index = 0; index < lines.length; index += 1) {
22
+ const raw = lines[index];
23
+ const trimmed = raw.trim();
24
+ if (!trimmed) continue;
25
+ if (trimmed.startsWith(';') || trimmed.startsWith('//')) continue;
26
+ const src = { relPath, path: `${pathPrefix}line:${index + 1}`, index };
27
+
28
+ const labelMatch = /^\*([A-Za-z_][\w.-]*)\s*$/.exec(trimmed);
29
+ if (labelMatch) {
30
+ label = labelMatch[1];
31
+ sceneKey = `${relPath}#${pathPrefix}label:${label}`;
32
+ lineOrder = 0;
33
+ yield { type: 'scene', key: sceneKey, title: label, container: relPath, order: sceneOrder++, conditions: null, src };
34
+ continue;
35
+ }
36
+
37
+ // 命令:@jump / @call / [jump ...] / [link ...]
38
+ const jump = /^@(?:jump|call)\s+(?:target|storage)=["']?([^"'\s]+)/.exec(trimmed)
39
+ ?? /^\[(?:jump|call)\s+(?:target|storage)=["']?([^"'\s]+)/.exec(trimmed);
40
+ if (jump) {
41
+ yield* ensureScene();
42
+ yield { type: 'jump', sceneKey, label: jump[1].replace(/^\*/, ''), src };
43
+ continue;
44
+ }
45
+ if (/^@|^\[(?:cm|er|hr|r|p|l|delay|wait|locate|position|image|bg|music|sound|se|voice|trans|quake|flash|fadein|fadeout|graph|move|anim|stop|play|call|jump|if|elsif|else|endif|end|link|endlink|macro|endmacro|ignore|endignore)\b/.test(trimmed)) {
46
+ yield* ensureScene();
47
+ yield { type: 'skip', sceneKey, reason: 'kag-tag', src };
48
+ continue;
49
+ }
50
+
51
+ // 文本行:去掉 [tag]
52
+ const plain = trimmed.replace(/\[[^\]]*\]/g, '').trim();
53
+ if (!plain) continue;
54
+ const speaker = /^([^「」::]{1,16})[「::]\s*[「]?(.+?)[」]?$/.exec(plain);
55
+ yield* ensureScene();
56
+ yield {
57
+ type: 'line',
58
+ sceneKey,
59
+ order: lineOrder++,
60
+ kind: speaker ? 'dialogue' : 'narration',
61
+ speakerId: speaker ? `name:${speaker[1]}` : null,
62
+ speakerName: speaker ? speaker[1].trim() : null,
63
+ text: speaker ? speaker[2].trim() : plain,
64
+ refs: {},
65
+ src,
66
+ };
67
+ }
68
+ }
69
+
70
+ async function walk(ctx, dir, extensions, depth = 2, level = 0, out = []) {
71
+ if (level > depth) return out;
72
+ for (const entry of await ctx.list(dir)) {
73
+ if (entry.dir) await walk(ctx, entry.rel, extensions, depth, level + 1, out);
74
+ else if (extensions.some((ext) => entry.name.toLowerCase().endsWith(ext))) out.push(entry.rel);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ export const kirikiri = {
80
+ id: 'kirikiri',
81
+ label: 'KiriKiri / KAG',
82
+
83
+ async detect(ctx) {
84
+ const evidence = [];
85
+ let score = 0;
86
+ const archives = [];
87
+ for (const dir of ['', 'game', 'data']) {
88
+ for (const entry of await ctx.list(dir || '.')) {
89
+ if (!entry.dir && entry.name.toLowerCase().endsWith('.xp3')) archives.push(entry.rel);
90
+ }
91
+ }
92
+ if (archives.length) {
93
+ score = 0.9;
94
+ evidence.push(`${archives.length} 个 .xp3`);
95
+ }
96
+ const scripts = await walk(ctx, '.', ['.ks'], 2);
97
+ if (scripts.length) {
98
+ score = Math.max(score, 0.86);
99
+ evidence.push(`${scripts.length} 个 .ks`);
100
+ }
101
+ if (await ctx.exists('krkr.exe') || await ctx.exists('TVP(KIRIKIRI) Z.exe') || (await ctx.list('.')).some((entry) => /tvp|kirikiri/i.test(entry.name))) {
102
+ score = Math.max(score, 0.78);
103
+ evidence.push('KiriKiri 可执行文件');
104
+ }
105
+ if (score === 0) return null;
106
+ return {
107
+ engineId: 'kirikiri',
108
+ label: 'KiriKiri / KAG',
109
+ confidence: score,
110
+ variant: 'kag',
111
+ evidence,
112
+ title: path.basename(ctx.root),
113
+ archives,
114
+ scripts,
115
+ };
116
+ },
117
+
118
+ async open(ctx, detection) {
119
+ const archives = detection.archives ?? [];
120
+ const scripts = detection.scripts ?? (await walk(ctx, '.', ['.ks'], 2));
121
+ const containers = [
122
+ ...archives.map((rel) => ({ rel, kind: 'archive', textBearing: true, note: 'XP3' })),
123
+ ...scripts.map((rel) => ({ rel, kind: 'script', textBearing: true, note: '' })),
124
+ ];
125
+
126
+ return {
127
+ id: 'kirikiri',
128
+ meta() {
129
+ return {
130
+ title: detection.title || path.basename(ctx.root),
131
+ engine: 'KiriKiri / KAG',
132
+ variant: 'kag',
133
+ encrypted: false,
134
+ dataDir: '.',
135
+ archiveCount: archives.length,
136
+ scriptCount: scripts.length,
137
+ };
138
+ },
139
+ containers() {
140
+ return containers;
141
+ },
142
+ fingerprintFiles() {
143
+ return [...archives, ...scripts].slice(0, 3);
144
+ },
145
+
146
+ async *extract(options = {}) {
147
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
148
+
149
+ for (const rel of scripts) {
150
+ if (!shouldRead(rel)) continue;
151
+ try {
152
+ const { text } = await ctx.readText(rel, 8 * 1024 * 1024);
153
+ yield* parseKagScript(text, { relPath: rel });
154
+ } catch (error) {
155
+ yield { type: 'error', relPath: rel, message: error.message };
156
+ }
157
+ }
158
+
159
+ for (const rel of archives) {
160
+ if (!shouldRead(rel)) continue;
161
+ let buffer;
162
+ try {
163
+ buffer = await ctx.readBuffer(rel, 1024 * 1024 * 1024);
164
+ } catch (error) {
165
+ yield { type: 'error', relPath: rel, message: error.message };
166
+ continue;
167
+ }
168
+ if (!isXp3(buffer)) {
169
+ yield { type: 'error', relPath: rel, message: '不是 XP3 归档(可能加密/定制)' };
170
+ continue;
171
+ }
172
+ let entries;
173
+ try {
174
+ entries = readXp3Index(buffer);
175
+ } catch (error) {
176
+ yield { type: 'error', relPath: rel, message: error.message };
177
+ continue;
178
+ }
179
+ for (const entry of entries) {
180
+ if (!/\.ks$/i.test(entry.name)) continue;
181
+ let content;
182
+ try {
183
+ content = readXp3Entry(buffer, entry);
184
+ } catch (error) {
185
+ yield { type: 'error', relPath: `${rel}!${entry.name}`, message: error.message };
186
+ continue;
187
+ }
188
+ yield* parseKagScript(content.toString('utf8'), { relPath: rel, pathPrefix: `${entry.name}:` });
189
+ }
190
+ }
191
+ },
192
+ };
193
+ },
194
+ };
195
+
196
+ export default kirikiri;