dsh-novel-game 0.0.0 → 0.2.0

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/client.js ADDED
@@ -0,0 +1,490 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-novel-game",
3
+ factory(require) {
4
+ const React = require("react");
5
+ const h = React.createElement;
6
+
7
+ /* remote contract mirrors lib/remote-contract.js */
8
+ const scalar = (v) => ({
9
+ parse: (x) => { v(x); return x; },
10
+ safeParse: (x) => { try { v(x); return { success: true, data: x }; } catch (e) { return { success: false, error: e }; } },
11
+ });
12
+ const sid = scalar((v) => { if (typeof v !== "string" || !v) throw new Error("bad sessionId"); });
13
+ const obj = scalar((v) => { if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("bad options"); });
14
+ const res = scalar((v) => { if (!v || typeof v !== "object") throw new Error("bad result"); });
15
+ const codec = (t, s) => ({ mode: "strict", typeSymbol: t, create: () => s });
16
+ const param = (n, s) => ({ name: n, wire: n, source: "json", codec: codec(n, s) });
17
+ const invoke = (m, ps) => ({
18
+ id: `dsh-novel-game#gamePanel/${m}`,
19
+ namespace: "gamePanel",
20
+ service: "gamePanel",
21
+ method: m,
22
+ invocation: { kind: "direct" },
23
+ parameters: [param("sessionId", sid), ...ps],
24
+ result: codec("GameResult", res),
25
+ });
26
+ const REMOTE = {
27
+ package: "dsh-novel-game",
28
+ descriptors: [
29
+ invoke("status", []),
30
+ invoke("listGames", []),
31
+ invoke("detect", [param("options", obj)]),
32
+ invoke("import", [param("options", obj)]),
33
+ invoke("jobStatus", [param("options", obj)]),
34
+ invoke("cancelJob", [param("options", obj)]),
35
+ invoke("scenes", [param("options", obj)]),
36
+ invoke("scene", [param("options", obj)]),
37
+ invoke("search", [param("options", obj)]),
38
+ invoke("routes", [param("options", obj)]),
39
+ invoke("characters", [param("options", obj)]),
40
+ invoke("glossary", [param("options", obj)]),
41
+ invoke("picks", [param("options", obj)]),
42
+ invoke("addPick", [param("options", obj)]),
43
+ invoke("export", [param("options", obj)]),
44
+ invoke("getSettings", []),
45
+ invoke("saveSettings", [param("options", obj)]),
46
+ ],
47
+ };
48
+
49
+ const unwrap = (value) => {
50
+ if (!value || value.ok === false) throw new Error(value?.message || "调用失败");
51
+ return value;
52
+ };
53
+
54
+ const C = {
55
+ border: "var(--dsw-alias-border-l1,#e8e7e0)",
56
+ bg: "var(--dsw-alias-bg-l1,#fff)",
57
+ bg2: "var(--dsw-alias-bg-l2,#f7f7f4)",
58
+ fg: "var(--dsw-alias-label-primary,#292f2b)",
59
+ sub: "var(--dsw-alias-label-secondary,#6b7280)",
60
+ accent: "var(--dsw-alias-brand-primary,#2f6f4f)",
61
+ };
62
+
63
+ const S = {
64
+ wrap: { display: "flex", flexDirection: "column", gap: 8, padding: "10px 12px", color: C.fg, fontSize: 12, minHeight: 0 },
65
+ row: { display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" },
66
+ head: { display: "flex", gap: 6, alignItems: "center", justifyContent: "space-between" },
67
+ title: { fontSize: 13, fontWeight: 600 },
68
+ tabs: { display: "flex", gap: 4, flexWrap: "wrap", borderBottom: `1px solid ${C.border}`, paddingBottom: 6 },
69
+ tab: (on) => ({
70
+ border: `1px solid ${on ? C.accent : C.border}`,
71
+ background: on ? C.accent : C.bg,
72
+ color: on ? "#fff" : C.fg,
73
+ borderRadius: 6, padding: "3px 8px", cursor: "pointer", fontSize: 11,
74
+ }),
75
+ btn: (on) => ({
76
+ border: `1px solid ${on === false ? C.border : C.border}`,
77
+ background: on === false ? C.bg2 : C.bg,
78
+ color: C.fg, borderRadius: 6, padding: "3px 8px", cursor: "pointer", fontSize: 11,
79
+ }),
80
+ input: {
81
+ flex: 1, minWidth: 120, border: `1px solid ${C.border}`, borderRadius: 6,
82
+ padding: "4px 6px", fontSize: 11, background: C.bg, color: C.fg,
83
+ },
84
+ card: { border: `1px solid ${C.border}`, borderRadius: 8, padding: 8, background: C.bg },
85
+ card2: { border: `1px solid ${C.border}`, borderRadius: 8, padding: 8, background: C.bg2 },
86
+ sub: { color: C.sub, fontSize: 11 },
87
+ line: { padding: "3px 0", borderBottom: `1px dashed ${C.border}`, lineHeight: 1.5 },
88
+ speaker: { fontWeight: 600, marginRight: 4 },
89
+ choice: { margin: "6px 0", padding: 6, border: `1px solid ${C.border}`, borderRadius: 6, background: C.bg2 },
90
+ notice: { color: C.accent, fontSize: 11 },
91
+ error: { color: "#b42318", fontSize: 11, whiteSpace: "pre-wrap" },
92
+ list: { display: "flex", flexDirection: "column", gap: 4, maxHeight: 380, overflow: "auto" },
93
+ pill: { fontSize: 10, padding: "1px 6px", borderRadius: 999, border: `1px solid ${C.border}`, color: C.sub },
94
+ empty: { padding: 16, textAlign: "center", color: C.sub, fontSize: 11 },
95
+ };
96
+
97
+ function Btn({ children, onClick, disabled, on }) {
98
+ return h("button", { type: "button", onClick, disabled, style: { ...S.btn(on), opacity: disabled ? 0.5 : 1 } }, children);
99
+ }
100
+
101
+ function Panel({ sessionId, remote }) {
102
+ const [tab, setTab] = React.useState("library");
103
+ const [status, setStatus] = React.useState(null);
104
+ const [gameId, setGameId] = React.useState("");
105
+ const [pathInput, setPathInput] = React.useState("");
106
+ const [consent, setConsent] = React.useState(false);
107
+ const [detected, setDetected] = React.useState(null);
108
+ const [job, setJob] = React.useState(null);
109
+ const [coverage, setCoverage] = React.useState(null);
110
+ const [scenes, setScenes] = React.useState(null);
111
+ const [detail, setDetail] = React.useState(null);
112
+ const [query, setQuery] = React.useState("");
113
+ const [results, setResults] = React.useState(null);
114
+ const [cast, setCast] = React.useState(null);
115
+ const [routes, setRoutes] = React.useState(null);
116
+ const [terms, setTerms] = React.useState(null);
117
+ const [picks, setPicks] = React.useState(null);
118
+ const [exported, setExported] = React.useState(null);
119
+ const [notice, setNotice] = React.useState("");
120
+ const [error, setError] = React.useState("");
121
+ const [busy, setBusy] = React.useState(false);
122
+
123
+ const flash = (message) => { setNotice(message); setTimeout(() => setNotice(""), 2600); };
124
+
125
+ const run = async (fn, success) => {
126
+ if (!remote) { setError("面板服务未就绪(remote 未挂载)"); return null; }
127
+ setBusy(true); setError("");
128
+ try {
129
+ const value = await fn();
130
+ if (success) flash(success);
131
+ return value;
132
+ } catch (e) {
133
+ setError(String(e?.message ?? e));
134
+ return null;
135
+ } finally {
136
+ setBusy(false);
137
+ }
138
+ };
139
+
140
+ async function loadScenes(id = gameId, offset = 0) {
141
+ if (!id) return;
142
+ const value = await run(async () => unwrap(await remote.scenes(sessionId, { gameId: id, offset, limit: 120 })));
143
+ if (value) setScenes(offset === 0 ? value : { ...value, items: [...(scenes?.items ?? []), ...value.items] });
144
+ }
145
+
146
+ async function loadStatus() {
147
+ const value = await run(async () => unwrap(await remote.status(sessionId)));
148
+ if (!value) return;
149
+ setStatus(value);
150
+ const nextId = gameId || value.list?.[0]?.gameId || "";
151
+ if (nextId) {
152
+ setGameId(nextId);
153
+ await loadScenes(nextId, 0);
154
+ setCoverage(value.list?.find((item) => item.gameId === nextId) ?? null);
155
+ }
156
+ }
157
+
158
+ React.useEffect(() => { loadStatus(); }, []);
159
+
160
+ React.useEffect(() => {
161
+ if (!job || job.status !== "running" || !remote) return undefined;
162
+ let timer = null;
163
+ let stopped = false;
164
+ const tick = async () => {
165
+ try {
166
+ const value = unwrap(await remote.jobStatus(sessionId, { jobId: job.jobId }));
167
+ if (stopped) return;
168
+ setJob(value.job);
169
+ if (value.job.status !== "running") {
170
+ if (value.job.status === "done") {
171
+ setCoverage(value.job.result?.coverage ?? null);
172
+ await loadStatus();
173
+ setTab("story");
174
+ flash("解包完成");
175
+ } else if (value.job.status === "failed") {
176
+ setError(value.job.error?.message ?? "解包失败");
177
+ }
178
+ return;
179
+ }
180
+ timer = setTimeout(tick, 700);
181
+ } catch (e) {
182
+ if (!stopped) setError(String(e?.message ?? e));
183
+ }
184
+ };
185
+ timer = setTimeout(tick, 500);
186
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
187
+ }, [job?.jobId, job?.status]);
188
+
189
+ async function openScene(sceneId) {
190
+ const value = await run(async () => unwrap(await remote.scene(sessionId, { gameId, sceneId })));
191
+ if (value) { setDetail(value); setTab("story"); }
192
+ }
193
+
194
+ async function doDetect() {
195
+ const value = await run(async () => unwrap(await remote.detect(sessionId, { path: pathInput.trim() })));
196
+ if (value) setDetected(value);
197
+ }
198
+
199
+ async function doImport() {
200
+ if (!consent) { setError("先勾选「我合法持有该游戏副本」"); return; }
201
+ const value = await run(async () => unwrap(await remote.import(sessionId, { path: pathInput.trim(), consent: true })));
202
+ if (value) { setJob({ jobId: value.jobId, status: "running", progress: { phase: "queued" } }); setTab("extract"); }
203
+ }
204
+
205
+ async function doSearch() {
206
+ if (!query.trim()) return;
207
+ const value = await run(async () => unwrap(await remote.search(sessionId, { gameId, query: query.trim() })));
208
+ if (value) setResults(value);
209
+ }
210
+
211
+ async function loadCast() {
212
+ const [people, glossary] = await Promise.all([
213
+ run(async () => unwrap(await remote.characters(sessionId, { gameId }))),
214
+ run(async () => unwrap(await remote.glossary(sessionId, { gameId, limit: 200 }))),
215
+ ]);
216
+ if (people) setCast(people);
217
+ if (glossary) setTerms(glossary);
218
+ }
219
+
220
+ async function loadPicks() {
221
+ const value = await run(async () => unwrap(await remote.picks(sessionId, { gameId })));
222
+ if (value) setPicks(value);
223
+ }
224
+
225
+ async function loadRoutes() {
226
+ const value = await run(async () => unwrap(await remote.routes(sessionId, { gameId })));
227
+ if (value) setRoutes(value);
228
+ }
229
+
230
+ async function addPick(line) {
231
+ const value = await run(async () => unwrap(await remote.addPick(sessionId, { gameId, kind: "line", refId: line.lineId })));
232
+ if (value) flash("已收进同人准备篮");
233
+ }
234
+
235
+ async function doExport() {
236
+ const value = await run(async () => unwrap(await remote.export(sessionId, { gameId, formats: ["story", "canon", "brief"] })));
237
+ if (value) { setExported(value); flash("已导出"); }
238
+ }
239
+
240
+ const games = status?.list ?? [];
241
+ const current = games.find((item) => item.gameId === gameId) ?? null;
242
+
243
+ const header = h("div", { style: S.head },
244
+ h("div", { style: S.title }, "游戏"),
245
+ h("select", {
246
+ value: gameId,
247
+ onChange: (event) => { const id = event.target.value; setGameId(id); setDetail(null); setScenes(null); loadScenes(id, 0); },
248
+ style: { ...S.input, flex: "0 1 180px" },
249
+ }, games.length === 0 ? h("option", { value: "" }, "(还没有游戏)") : games.map((item) => h("option", { key: item.gameId, value: item.gameId }, item.title))),
250
+ );
251
+
252
+ const tabs = h("div", { style: S.tabs },
253
+ [["library", "游戏库"], ["extract", "解包"], ["story", "剧情"], ["cast", "设定"], ["search", "检索"], ["prepare", "同人准备"]]
254
+ .map(([id, label]) => h("button", { key: id, type: "button", style: S.tab(tab === id), onClick: () => { setTab(id); if (id === "cast" && !cast) loadCast(); if (id === "prepare") loadPicks(); } }, label)),
255
+ );
256
+
257
+ function renderLibrary() {
258
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
259
+ games.length === 0 ? h("div", { style: S.empty }, "还没有导入游戏。把本地游戏目录填到下面,先探测再导入。") : null,
260
+ ...games.map((item) => h("div", {
261
+ key: item.gameId,
262
+ style: { ...S.card, borderColor: item.gameId === gameId ? C.accent : C.border, cursor: "pointer" },
263
+ onClick: () => { setGameId(item.gameId); setDetail(null); loadScenes(item.gameId, 0); },
264
+ },
265
+ h("div", { style: S.row }, h("b", null, item.title), h("span", { style: S.pill }, item.engine), h("span", { style: S.pill }, item.status)),
266
+ h("div", { style: S.sub }, `场景 ${item.counts?.scenes ?? 0} · 台词 ${item.counts?.lines ?? 0} · 词条 ${item.counts?.glossary ?? 0}`),
267
+ h("div", { style: { ...S.sub, wordBreak: "break-all" } }, item.root),
268
+ )),
269
+ h("div", { style: S.card2 },
270
+ h("div", { style: S.sub, marginBottom: 4 }, "导入本地游戏(只读;必须是你合法持有的副本)"),
271
+ h("div", { style: S.row },
272
+ h("input", { style: S.input, placeholder: "D:\\Games\\某游戏", value: pathInput, onChange: (e) => setPathInput(e.target.value) }),
273
+ h(Btn, { onClick: doDetect, disabled: busy || !pathInput.trim() }, "探测"),
274
+ h(Btn, { onClick: doImport, disabled: busy || !pathInput.trim() || !consent }, "导入"),
275
+ ),
276
+ h("label", { style: { ...S.row, marginTop: 6, ...S.sub } },
277
+ h("input", { type: "checkbox", checked: consent, onChange: (e) => setConsent(e.target.checked) }),
278
+ "我合法持有该游戏副本,仅用于个人同人创作参考",
279
+ ),
280
+ detected ? h("div", { style: { ...S.card, marginTop: 6 } },
281
+ h("div", { style: S.row }, h("b", null, detected.chosen?.label ?? "未知"), h("span", { style: S.pill }, `置信度 ${Math.round((detected.chosen?.confidence ?? 0) * 100)}%`)),
282
+ h("div", { style: S.sub }, detected.chosen?.evidence?.join(";") ?? ""),
283
+ h("div", { style: S.sub }, `文本容器 ${detected.containers?.filter((c) => c.textBearing).length ?? 0} 个;标题:${detected.meta?.title ?? ""}`),
284
+ ) : null,
285
+ ),
286
+ );
287
+ }
288
+
289
+ function renderExtract() {
290
+ const summary = coverage?.summary ?? current?.coverage ?? null;
291
+ const containers = coverage?.containers ?? [];
292
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
293
+ job ? h("div", { style: S.card },
294
+ h("div", { style: S.row }, h("b", null, "导入任务"), h("span", { style: S.pill }, job.status), h("span", { style: S.sub }, job.progress?.phase ?? "")),
295
+ h("div", { style: S.sub }, `进度:${job.progress?.done ?? 0}/${job.progress?.total ?? 0}`),
296
+ job.status === "running" ? h(Btn, { onClick: async () => { const value = await run(async () => unwrap(await remote.cancelJob(sessionId, { jobId: job.jobId }))); if (value) flash("已请求取消"); } }, "取消") : null,
297
+ ) : h("div", { style: S.empty }, "还没有进行中的任务。到「游戏库」导入一个游戏。"),
298
+ summary ? h("div", { style: S.card },
299
+ h("div", { style: S.row }, h("b", null, "覆盖率")),
300
+ h("div", { style: S.sub }, `容器 ${summary.containers ?? 0}(文本 ${summary.textBearing ?? 0});已解 ${summary.extracted ?? 0};复用 ${summary.reused ?? 0};错误 ${summary.errors ?? 0};跳过单元 ${summary.skippedUnits ?? 0}`),
301
+ ) : null,
302
+ containers.length ? h("div", { style: S.list },
303
+ ...containers.slice(0, 60).map((row) => h("div", { key: row.rel, style: { ...S.sub, display: "flex", justifyContent: "space-between", gap: 6 } },
304
+ h("span", { style: { wordBreak: "break-all" } }, row.rel),
305
+ h("span", null, `${row.status}${row.units ? ` · ${row.units}` : ""}`),
306
+ )),
307
+ ) : null,
308
+ );
309
+ }
310
+
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
+ }
325
+ if (detail) {
326
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
327
+ h("div", { style: S.row },
328
+ h(Btn, { onClick: () => setDetail(null) }, "← 场景列表"),
329
+ h("b", null, detail.scene?.title ?? ""),
330
+ h("span", { style: S.pill }, `${detail.total} 句`),
331
+ ),
332
+ h("div", { style: S.list },
333
+ ...detail.lines.map((line) => h("div", { key: line.lineId, style: S.line },
334
+ h("div", null,
335
+ line.speakerName ? h("span", { style: S.speaker }, `${line.speakerName}:`) : null,
336
+ h("span", null, line.text),
337
+ h("button", { type: "button", style: { ...S.btn(), marginLeft: 6, padding: "0 6px" }, onClick: () => addPick(line) }, "收"),
338
+ ),
339
+ line.refs?.voice || line.refs?.cg ? h("div", { style: S.sub }, [line.refs?.voice ? `语音 ${line.refs.voice}` : "", line.refs?.cg ? `CG ${line.refs.cg}` : ""].filter(Boolean).join(" · ")) : null,
340
+ )),
341
+ ...detail.choices.map((choice) => h("div", { key: choice.choiceId, style: S.choice },
342
+ choice.prompt ? h("div", { style: S.sub }, choice.prompt) : null,
343
+ h("div", null, `[选项] ${choice.options.map((option) => option.text).join(" / ")}`),
344
+ )),
345
+ ),
346
+ );
347
+ }
348
+ const items = scenes?.items ?? [];
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 }, "路线图")),
351
+ items.length === 0 ? h("div", { style: S.empty }, "这个游戏还没有可浏览的场景。") : null,
352
+ ...items.map((scene) => h("div", {
353
+ key: scene.sceneId, style: { ...S.card, cursor: "pointer" },
354
+ onClick: () => openScene(scene.sceneId),
355
+ },
356
+ h("div", { style: S.row }, h("span", { style: { ...S.pill, minWidth: 26, textAlign: "center" } }, String((scene.seq ?? 0) + 1)), h("b", null, scene.title)),
357
+ h("div", { style: S.sub }, `${scene.lineCount} 句${scene.choiceCount ? ` · ${scene.choiceCount} 个选项` : ""}`),
358
+ )),
359
+ scenes && scenes.items.length < scenes.total ? h(Btn, { onClick: () => loadScenes(gameId, scenes.items.length) }, "加载更多") : null,
360
+ );
361
+ }
362
+
363
+ function renderCast() {
364
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
365
+ h("div", { style: S.row }, h("b", null, "人物"), h("span", { style: S.pill }, `${cast?.total ?? 0}`)),
366
+ ...(cast?.characters ?? []).slice(0, 40).map((character) => h("div", { key: character.characterId, style: S.card },
367
+ h("div", { style: S.row }, h("b", null, character.name), h("span", { style: S.pill }, `${character.lineCount} 句`), h("span", { style: S.sub }, `出场 ${character.sceneCount} 场`)),
368
+ character.aliases?.length ? h("div", { style: S.sub }, `别名:${character.aliases.join("、")}`) : null,
369
+ ...character.quotes.slice(0, 2).map((quote, index) => h("div", { key: index, style: { ...S.sub, marginTop: 2 } }, `「${quote.text}」`)),
370
+ )),
371
+ h("div", { style: S.row, marginTop: 4 }, h("b", null, "词条"), h("span", { style: S.pill }, `${terms?.total ?? 0}`)),
372
+ ...(terms?.items ?? []).slice(0, 60).map((term) => h("div", { key: term.glossaryId, style: { ...S.sub, display: "flex", gap: 6 } },
373
+ h("span", { style: S.pill }, term.kind),
374
+ h("span", null, term.name),
375
+ term.description ? h("span", { style: { opacity: 0.8 } }, `— ${term.description}`) : null,
376
+ )),
377
+ );
378
+ }
379
+
380
+ function renderSearch() {
381
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
382
+ h("div", { style: S.row },
383
+ h("input", { style: S.input, placeholder: "搜台词/角色/词条", value: query, onChange: (e) => setQuery(e.target.value), onKeyDown: (e) => { if (e.key === "Enter") doSearch(); } }),
384
+ h(Btn, { onClick: doSearch, disabled: busy }, "搜索"),
385
+ ),
386
+ results ? h("div", { style: S.sub }, `命中 ${results.total} 条`) : null,
387
+ ...(results?.items ?? []).map((item) => h("div", {
388
+ key: item.lineId ?? item.glossaryId,
389
+ style: { ...S.card, cursor: item.kind === "line" ? "pointer" : "default" },
390
+ onClick: () => { if (item.kind === "line") openScene(item.sceneId); },
391
+ },
392
+ h("div", { style: S.sub }, `${item.sceneTitle ?? ""}${item.speakerName ? ` · ${item.speakerName}` : ""}`),
393
+ h("div", null, item.text ?? `${item.term}:${item.description ?? ""}`),
394
+ )),
395
+ );
396
+ }
397
+
398
+ function renderPrepare() {
399
+ return h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
400
+ h("div", { style: S.row }, h("b", null, "同人准备篮"), h("span", { style: S.pill }, `${picks?.total ?? 0}`)),
401
+ (picks?.items ?? []).length === 0 ? h("div", { style: S.empty }, "在剧情里点「收」,把关键台词收进来。") : null,
402
+ ...(picks?.items ?? []).map((pick) => h("div", { key: pick.pickId, style: S.card },
403
+ h("div", { style: S.sub }, `${pick.kind} · ${pick.refId}`),
404
+ pick.note ? h("div", null, pick.note) : null,
405
+ )),
406
+ h("div", { style: S.card2 },
407
+ h("div", { style: S.sub, marginBottom: 4 }, "导出(只写 .dsh-novel-game/exports/)"),
408
+ h("div", { style: S.row },
409
+ h(Btn, { onClick: doExport, disabled: busy || !gameId }, "导出三件套"),
410
+ h(Btn, { onClick: doExport, disabled: busy || !gameId }, "再导一次"),
411
+ ),
412
+ exported ? h("div", { style: { ...S.sub, marginTop: 6, wordBreak: "break-all" } },
413
+ `story:${exported.files?.story ?? ""}`,
414
+ h("br"), `canon:${exported.files?.canon ?? ""}`,
415
+ h("br"), `brief:${exported.files?.brief ?? ""}`,
416
+ h("br"), "在 fanfic 里用 /fic import 指到 story.md 即可建 canon。",
417
+ ) : null,
418
+ ),
419
+ );
420
+ }
421
+
422
+ return h("div", { style: S.wrap },
423
+ header,
424
+ tabs,
425
+ tab === "library" ? renderLibrary() : null,
426
+ tab === "extract" ? renderExtract() : null,
427
+ tab === "story" ? renderStory() : null,
428
+ tab === "cast" ? renderCast() : null,
429
+ tab === "search" ? renderSearch() : null,
430
+ tab === "prepare" ? renderPrepare() : null,
431
+ notice ? h("div", { style: S.notice }, notice) : null,
432
+ error ? h("div", { style: S.error }, error) : null,
433
+ );
434
+ }
435
+
436
+ const TAB_ID = "dsh-novel-game";
437
+ const TAB_KIND = "novel-game";
438
+
439
+ function OpenButton({ open }) {
440
+ return h("button", {
441
+ type: "button", onClick: open, title: "打开游戏剧情面板",
442
+ style: {
443
+ border: "1px solid var(--dsw-alias-border-l1,#e8e7e0)",
444
+ background: "var(--dsw-alias-bg-l1,#fff)",
445
+ color: "var(--dsw-alias-label-primary,#292f2b)",
446
+ borderRadius: 8, padding: "3px 9px", cursor: "pointer", fontSize: 12,
447
+ },
448
+ }, "游戏");
449
+ }
450
+
451
+ return {
452
+ inject: ["slots", "remote"],
453
+ async apply(ctx) {
454
+ let remote = null;
455
+ try {
456
+ const dispose = await ctx.remote.$mount(REMOTE);
457
+ remote = ctx.get("remote.gamePanel") ?? null;
458
+ if (typeof dispose === "function") ctx.effect(() => () => { try { dispose(); } catch { /* gone */ } });
459
+ if (!remote) console.error("[novel-game] remote.gamePanel 未注册");
460
+ } catch (e) {
461
+ console.error("[novel-game] remote mount 失败", e);
462
+ }
463
+
464
+ const seat = ctx.inject(["sidebarRightTabs", "sidebarRight"], (scoped) => {
465
+ const tabs = scoped.get("sidebarRightTabs");
466
+ const right = scoped.get("sidebarRight");
467
+ if (!tabs || !right) return;
468
+ scoped.effect(() => tabs.register({
469
+ id: TAB_ID,
470
+ kind: TAB_KIND,
471
+ priority: "extension",
472
+ keepMounted: true,
473
+ title: () => "游戏",
474
+ guide: [{ id: TAB_ID, order: 27, title: () => "游戏", description: () => "本地游戏剧情/文本/设定的解包、浏览与同人准备" }],
475
+ }), "novel-game: tab type");
476
+ scoped.effect(() => scoped.slots.inject("sidebar.right.pane.tab", () => scoped.slots.register(
477
+ { name: "sidebar.right.pane.tab", key: TAB_ID, inject: (sessionId) => ({ sessionId, remote }) },
478
+ Panel,
479
+ )), "novel-game: tab body");
480
+ scoped.effect(() => scoped.slots.inject("conversation.session.header.utilities", () => scoped.slots.register(
481
+ { name: "conversation.session.header.utilities", id: "dsh-novel-game-open", order: 40,
482
+ inject: () => ({ open: () => { try { right.openTab(TAB_KIND); } catch (e) { console.error("[novel-game] openTab", e); } } }) },
483
+ OpenButton,
484
+ )), "novel-game: header button");
485
+ });
486
+ ctx.effect(() => () => { try { seat?.(); } catch { /* gone */ } });
487
+ },
488
+ };
489
+ },
490
+ });
@@ -0,0 +1,6 @@
1
+ - insert:
2
+ - id: dsh-novel-game
3
+ name: dsh-novel-game
4
+ config: {}
5
+ - id: dsh-novel-game-remote
6
+ name: dsh-novel-game/remote
package/docs/DETAIL.md ADDED
@@ -0,0 +1,62 @@
1
+ # 实现细节
2
+
3
+ ## 分层
4
+
5
+ ```
6
+ index.js Host 工具注册(13 个)
7
+ lib/core/ 错误码、路径守卫、哈希、ID、编码、JSONL 原子写
8
+ lib/ctx.mjs 游戏目录只读上下文
9
+ lib/detect.mjs 多候选引擎探测与筛选
10
+ lib/adapters/ rpgmaker / renpy / generic-text + registry
11
+ lib/archive/rpa.mjs RPA 头、受限 pickle、条目解压
12
+ lib/ingest.mjs 导入编排:哈希、增量、分片、聚合、manifest
13
+ lib/store.mjs .dsh-novel-game/ 读写与 generation
14
+ lib/service.mjs 业务:浏览/检索/人物/词条/摘录/导出
15
+ lib/jobs.mjs 长任务(串行更新,避免进度覆盖 done)
16
+ lib/remote-contract.js 面板的 Typert 契约
17
+ lib/remote.js Host 侧 remote 服务
18
+ client.js 右栏六页面板
19
+ ```
20
+
21
+ ## 导入流程
22
+
23
+ 1. `planImport`:探测 → 选 adapter → `open` → meta/containers/fingerprintFiles。
24
+ 2. 对指纹文件与文本容器算 sha256;`gameId` 优先复用同 root 的已有游戏,否则由「引擎 + 标题 + 指纹文件清单」生成。
25
+ 3. `beginGeneration` 建新代;未变化文件的旧分片拷进新代。
26
+ 4. `source.extract({ shouldRead })` 流式产出:
27
+ - `scene` → scenes 聚合
28
+ - `line` → 当前文件分片
29
+ - `choice` → choices 聚合
30
+ - `glossary` → glossary 聚合
31
+ - `asset`/`skip`/`label`/`jump`/`condition` → 当前文件分片
32
+ - `error` → 覆盖率错误
33
+ 5. 合并上一代未变化文件的场景/选项/词条;场景按 Map 序号排序并写 `seq`。
34
+ 6. 写聚合 → `finalizeGeneration`(manifest + library)→ `pruneGenerations(2)`。
35
+
36
+ ## ID 规则
37
+
38
+ ```
39
+ gameId = g_ + hash(engine + title + 指纹文件清单)
40
+ sceneId = s_ + hash(gameId + relPath + sceneKey)
41
+ lineId = l_ + hash(gameId + relPath + src.path + kind)
42
+ choiceId = c_ + hash(gameId + relPath + src.path)
43
+ glossaryId = t_ + hash(gameId + relPath + entry.key)
44
+ ```
45
+
46
+ 文本内容不参与 ID:改一句台词不会丢摘录;结构移动由 UI 提示(0.2.0 做旧新映射)。
47
+
48
+ ## 分片
49
+
50
+ - 每个源文件一个分片:`story/shards/<hash(rel)>.jsonl`,行带 `t` 区分 `line/asset/skip/label/jump/condition`。
51
+ - 聚合:`story/scenes.jsonl`、`story/choices.jsonl`、`glossary.jsonl`。
52
+ - 增量:分片按哈希复用;新代只重写变化文件的分片。
53
+
54
+ ## 错误与部分成功
55
+
56
+ - 单文件失败只进 `coverage.errors`,不中断整本。
57
+ - `manifest.status = partial`(有错误)或 `ready`。
58
+ - 工具返回 `{ ok: true, partial: true, ... }` 表示有缺口。
59
+
60
+ ## 剧透边界
61
+
62
+ `settings.json` 的 `spoiler = { mode: 'all' | 'scene', maxSceneOrder }`:场景列表、场景详情、导出都按 `seq` 过滤;`mode=route` 预留给 0.2.0。
@@ -0,0 +1,75 @@
1
+ # 引擎格式依据
2
+
3
+ > 每个适配器的实现依据;改格式前先看这里。只记录「结构/字段」,不含游戏内容。
4
+ > 原则:不引原生依赖,纯 JS;不执行归档内代码;加密资源不解密(0.1.0)。
5
+
6
+ ## RPG Maker MV / MZ
7
+
8
+ - 目录:MV 为 `www/data/*.json`,MZ 为 `data/*.json`;`js/rpg_core.js`(MV)或 `js/rmmz_core.js`(MZ)用于判版本。
9
+ - 数据文件:`Map###.json`(`events[].pages[].list[]`)、`CommonEvents.json`、`Troops.json`、`Actors.json`、`Classes.json`、`Items.json`、`Weapons.json`、`Armors.json`、`Skills.json`、`States.json`、`Enemies.json`、`System.json`、`MapInfos.json`。
10
+ - 事件指令码(本插件用到的):
11
+ - `101` 显示文字头(`faceName, faceIndex, background, positionType`)+ `401` 每行
12
+ - `105` 滚动文字头 + `405` 每行
13
+ - `102` 显示选项(`parameters[0]` 是选项文本数组)+ `402` 分支 / `403` 取消 / `404` 结束
14
+ - `111` 条件分支、`118` 标签、`119` 跳转
15
+ - `231` 显示图片、`241` 播放 BGM、`250` 播放 SE
16
+ - `320` 更改名字、`324` 更改昵称
17
+ - `355/655` 脚本、`356/357` 插件命令(0.1.0 不解析,计入未解析)
18
+ - 控制符:`\N[n]` 角色名、`\V[n]` 变量(不求值)、`\C[n]`/`\I[n]`/`\F[n]` 等展示控制符去掉;`\P[n]` 保留标记。
19
+ - 加密:`System.json` 的 `hasEncryptedImages/hasEncryptedAudio` 与 `encryptionKey`;`.rpgmvp/.rpgmvo/.rpgmva` 头为 `RPGMV` + 16 字节假头。0.1.0 只报告状态,不解密。
20
+ - 参考:
21
+ - [Petschko/RPG-Maker-MV-Decrypter](https://github.com/Petschko/RPG-Maker-MV-Decrypter)(加密头与密钥)
22
+ - [kemsig/rpgmaker-mv-ai-translate](https://github.com/kemsig/rpgmaker-mv-ai-translate)(从 data/*.json 抽文本的字段清单)
23
+
24
+ ## Ren'Py
25
+
26
+ - 脚本:`game/**/*.rpy` 明文;`define x = Character("名字")`;`label`、`menu`、`jump/call`、`scene/show`、`voice`;`$`/`python:`/`screen`/`translate` 块不执行、不混入正文。
27
+ - 归档:`RPA-2.0` 头 `RPA-2.0 <offset>`;`RPA-3.0/3.2` 头 `RPA-3.0 <offset16> <key8>`,索引为 zlib + pickle;条目为 zlib 压缩,偏移按 `key` XOR 还原。
28
+ - pickle:只允许索引需要的 opcode 子集(PROTO/EMPTY_DICT/EMPTY_LIST/MARK/BINUNICODE/BINSTRING/BININT*/LONG1/TUPLE/APPEND/SETITEMS/DICT/STOP 等);`GLOBAL/REDUCE/BUILD/STACK_GLOBAL` 等一律拒绝。
29
+ - `.rpyc`:`RENPY RPC2` 头 + 编译数据;0.1.0 不反编译,报未解析。
30
+ - 参考:
31
+ - [CensoredUsername/unrpyc](https://github.com/CensoredUsername/unrpyc)
32
+ - [asakura-minami/unrpyc-pure](https://github.com/asakura-minami/unrpyc-pure)
33
+ - [Lattyware/unrpa](https://github.com/Lattyware/unrpa)
34
+
35
+ ## 通用文本嗅探
36
+
37
+ - JSON/JSONL:对象含 `text/message/dialogue/line/content/body` 之类的字符串字段;`speaker/name/character` 作说话人;`lines/dialogue/messages` 等数组递归。
38
+ - CSV/TSV:表头匹配 `text|message|line|content|对话|文本` 与 `speaker|name|角色|人物|说话人`;无表头时按「说话人,文本」两列。
39
+ - PO:`msgid`/`msgstr` 成对,优先 `msgstr`。
40
+ - Yarn:`title:` 节点,`//`、`<<...>>`、`=>` 跳过。
41
+ - Ink:`=== knot ===` 分节,`*`/`+` 选项、`->`/`~`/`VAR` 跳过。
42
+ - TXT/MD:`名字:文本` 拆说话人;标题/分隔线跳过;单行 ≤240 字。
43
+ - SRT:按 cue 合并文本行。
44
+ - 编码:BOM 优先;否则 UTF-8 / GB18030 / Shift-JIS / Big5 里选坏字符最少者。
45
+
46
+ ## KiriKiri / KAG(0.2.0)
47
+
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)。