@liminalia/runtime 0.0.0-stage → 0.8.4

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 (57) hide show
  1. package/LICENSE +106 -0
  2. package/dist/src/chat.js +60 -0
  3. package/dist/src/commands-play.js +300 -0
  4. package/dist/src/commands.js +534 -0
  5. package/dist/src/coverage.js +208 -0
  6. package/dist/src/headless.js +109 -0
  7. package/dist/src/host.js +1 -0
  8. package/dist/src/index.js +15 -0
  9. package/dist/src/prefetch.js +80 -0
  10. package/dist/src/program.js +131 -0
  11. package/dist/src/project-options.js +84 -0
  12. package/dist/src/retranslate.js +44 -0
  13. package/dist/src/route.js +242 -0
  14. package/dist/src/runtime.js +1929 -0
  15. package/dist/src/save.js +51 -0
  16. package/dist/src/scenario-test.js +200 -0
  17. package/dist/src/state.js +62 -0
  18. package/dist/src/value.js +464 -0
  19. package/dist/src/voice-observe.js +82 -0
  20. package/package.json +33 -4
  21. package/src/chat.ts +109 -0
  22. package/src/commands-play.ts +280 -0
  23. package/src/commands.ts +457 -0
  24. package/src/coverage.ts +257 -0
  25. package/src/headless.ts +139 -0
  26. package/src/host.ts +116 -0
  27. package/src/index.ts +16 -0
  28. package/src/prefetch.ts +78 -0
  29. package/src/program.ts +186 -0
  30. package/src/project-options.ts +128 -0
  31. package/src/retranslate.ts +67 -0
  32. package/src/route.ts +365 -0
  33. package/src/runtime.ts +2143 -0
  34. package/src/save.ts +60 -0
  35. package/src/scenario-test.ts +218 -0
  36. package/src/state.ts +353 -0
  37. package/src/value.ts +443 -0
  38. package/src/voice-observe.ts +85 -0
  39. package/types/src/chat.d.ts +63 -0
  40. package/types/src/commands-play.d.ts +2 -0
  41. package/types/src/commands.d.ts +2 -0
  42. package/types/src/coverage.d.ts +100 -0
  43. package/types/src/headless.d.ts +77 -0
  44. package/types/src/host.d.ts +140 -0
  45. package/types/src/index.d.ts +16 -0
  46. package/types/src/prefetch.d.ts +18 -0
  47. package/types/src/program.d.ts +107 -0
  48. package/types/src/project-options.d.ts +103 -0
  49. package/types/src/retranslate.d.ts +39 -0
  50. package/types/src/route.d.ts +181 -0
  51. package/types/src/runtime.d.ts +553 -0
  52. package/types/src/save.d.ts +21 -0
  53. package/types/src/scenario-test.d.ts +43 -0
  54. package/types/src/state.d.ts +357 -0
  55. package/types/src/value.d.ts +61 -0
  56. package/types/src/voice-observe.d.ts +26 -0
  57. package/README.md +0 -3
@@ -0,0 +1,1929 @@
1
+ import { applyCommandDefaults, booleanShorthandConflicts, normalizeBooleanArgs, chapterOf, check, contextAt, countEndings, endingKinds, endingRecordKey, endingRef, ENDINGS_KEY, translatableSetValue, CHOICE_BLOCK, CHOICE_OPTION, CORE_COMMANDS, castForSpeaker, createRegistry, paramLocalName, FORBIDDEN_PROPERTIES, parse, parseInline, parseLiteral, parseTargetText, paramTypeFromName, printInline, printLiteral, plainText, runtimeDiagnostic, stripSpeechQuotes, textHash, translationKey, READ_KEY, } from "@liminalia/lang";
2
+ import { chatDialogueActive, chatPartsText, pushChatMessage } from "./chat.js";
3
+ import { CORE_IMPLEMENTATIONS } from "./commands.js";
4
+ import { buildProgram } from "./program.js";
5
+ import { collectPrefetch } from "./prefetch.js";
6
+ import { argOrigin, noteArgOrigin, textOrigins, withOrigins } from "./retranslate.js";
7
+ import { migrateSave } from "./save.js";
8
+ import { clonePlain, createState, toSaveData, voiceFile, voiceFilterFor } from "./state.js";
9
+ import { checkedDivision, display, evaluate, EvalError, nextRandom, truthy } from "./value.js";
10
+ export class Runtime {
11
+ host;
12
+ state;
13
+ /** 全セーブ共通の変数。保存は Host 側で行う。 */
14
+ system = {};
15
+ /** 訳(多言語)。null なら原文。遊んでいる途中で言語を替えたら、次のページから効く。 */
16
+ translator = null;
17
+ programs = new Map();
18
+ implementations = new Map();
19
+ registry;
20
+ speakers;
21
+ maxSteps;
22
+ onError;
23
+ returnWithoutCall;
24
+ onAssign;
25
+ onStep;
26
+ beforeStep;
27
+ /** ロードの直後に呼び出す位置(options.afterLoad)。 */
28
+ afterLoad;
29
+ /** 作品のコマンドの既定値(options.commandDefaults)。@define のマクロを呼ぶときに重ねる。 */
30
+ commandDefaults;
31
+ /** 変数の初期値(options.variables を置き場所ごとに分けたもの)。 */
32
+ gameDefaults = {};
33
+ systemDefaults = {};
34
+ /** 実行中の命令(at が返す)。 */
35
+ currentUnit = null;
36
+ currentLine = 0;
37
+ halt = null;
38
+ /** 表示中のページや選択肢の位置。この間にセーブしたら、ここから再開する。 */
39
+ resumeAt = null;
40
+ /**
41
+ * メッセージ枠のページをクリックで送ったあと、まだ命令を描画側に渡していない(TyranoScript の [p] の改ページと同じく、
42
+ * 次に渡す命令に afterPage を付け、描画側がそこで前のページの本文を消す)。NVL、チャットの画面、{noclick} のページでは立てない。
43
+ */
44
+ pageRead = false;
45
+ /**
46
+ * resumeAt に着いた時点の状態。ページの途中でセーブしたら、位置だけでなく状態もページの頭のものにする。
47
+ * そうしないと、ロードしてページを頭から流し直したとき、本文中の命令({@…})が二度効く。
48
+ */
49
+ resumeState = null;
50
+ steps = 0;
51
+ /** 本文のページを出している最中か(本文の中の命令を実行しているとき true)。 */
52
+ inPage = false;
53
+ /** 出しているページの話者(地の文と、ページの外は null)。 */
54
+ pageSpeaker = null;
55
+ abort = new AbortController();
56
+ voiceLock;
57
+ /** CG として解放する画像か(options.cg)。 */
58
+ isCg;
59
+ /** ふだんの台詞をチャットの列に積む設定(options.chatDialogue)。無ければ null。 */
60
+ chatDialogue;
61
+ /** 台詞の外側の括弧と引用符を外すか(options.stripQuotes)。 */
62
+ stripQuotes;
63
+ /** 作品の版(options.gameVersion。無ければ空)。 */
64
+ gameVersion;
65
+ /**
66
+ * 作ったときの設定(渡したものそのまま)。同じ作品を画面なしで先へ流す実行器(@liminalia/web の「次の選択肢へ」「次の未読へ」)を、
67
+ * 遊んでいる実行器と同じ設定で作るのに使う。言語と訳は作ったあとにも替わるので、今の値は language と translator を読む。
68
+ */
69
+ options;
70
+ constructor(host, options = {}) {
71
+ this.host = host;
72
+ this.options = options;
73
+ for (const impl of [...CORE_IMPLEMENTATIONS, ...(options.commands ?? [])]) {
74
+ // 作品の既定値を重ねた仕様で引数を読む(実装はそのまま)
75
+ const spec = applyCommandDefaults(impl.spec, options.commandDefaults);
76
+ this.implementations.set(impl.spec.name, spec === impl.spec ? impl : { ...impl, spec });
77
+ }
78
+ this.registry = createRegistry([...this.implementations.values()].map((i) => i.spec));
79
+ this.speakers = [...(options.speakers ?? [])];
80
+ this.maxSteps = options.maxSteps ?? 1_000_000;
81
+ this.onError = options.onError ?? "stop";
82
+ this.returnWithoutCall = options.returnWithoutCall ?? "error";
83
+ this.onAssign = options.onAssign;
84
+ this.onStep = options.onStep;
85
+ this.beforeStep = options.beforeStep;
86
+ this.afterLoad = options.afterLoad;
87
+ this.commandDefaults = options.commandDefaults;
88
+ this.isCg = options.cg ?? null;
89
+ this.cast = options.cast;
90
+ this.autoLayout = options.autoLayout;
91
+ this.voiceLock = options.voiceLock ?? null;
92
+ this.chatDialogue = options.chatDialogue ?? null;
93
+ this.stripQuotes = options.stripQuotes ?? (() => false);
94
+ this.gameVersion = options.gameVersion ?? "";
95
+ for (const [path, value] of Object.entries(options.variables ?? {})) {
96
+ const [scope, name] = path.split(".");
97
+ if (name && scope === "game")
98
+ this.gameDefaults[name] = value;
99
+ if (name && scope === "system")
100
+ this.systemDefaults[name] = value;
101
+ }
102
+ this.state = createState("", options.seed ?? 1);
103
+ this.language = options.language ?? "";
104
+ this.translator = options.translator ?? null;
105
+ this.platform = options.platform ?? { device: "pc", app: false };
106
+ this.chapters = options.chapters ?? [];
107
+ this.dataLoader = options.loadData;
108
+ this.achievementGoals = options.achievementGoals ?? {};
109
+ this.endingAchievements = options.endingAchievements ?? {};
110
+ this.endingKinds = endingKinds(options.endingKinds);
111
+ }
112
+ // ---- 開始・再開 ----
113
+ /**
114
+ * target(`chapter1`・`chapter1#start`)から実行を始める。
115
+ * temp(そのプレイ中だけの変数)は引き継ぐ。タイトル画面などが始める前に temp を入れておけるようにするため(load と同じ)。
116
+ */
117
+ async start(target, options = {}) {
118
+ const [file = "", label = null] = target.split("#");
119
+ this.state = { ...createState(file, this.state.seed), temp: this.state.temp };
120
+ if (this.gameVersion)
121
+ this.state.gameVersion = this.gameVersion;
122
+ this.state.game = structuredClone(this.gameDefaults);
123
+ this.fillSystemDefaults();
124
+ this.replay = options.replay ?? null;
125
+ // 回想に渡す変数(liminalia.json の extra.replay の variables)。初期値の後ろに入れる
126
+ for (const [path, value] of Object.entries(options.variables ?? {})) {
127
+ const [scope] = path.split(".");
128
+ if (scope === "game" || scope === "temp")
129
+ this.setVariable(path, structuredClone(value));
130
+ }
131
+ await this.goto({ file, label }, file);
132
+ return this.run();
133
+ }
134
+ /** system の変数のうち、まだ値の無いものを初期値にする。 */
135
+ fillSystemDefaults() {
136
+ for (const [k, v] of Object.entries(this.systemDefaults))
137
+ if (!(k in this.system))
138
+ this.system[k] = structuredClone(v);
139
+ }
140
+ /** 現在の状態をセーブデータにする。ページや選択肢の途中なら、そのページ(選択肢)から再開する位置にする。 */
141
+ save() {
142
+ const data = this.resumeAt && this.resumeState ? clonePlain(this.resumeState) : toSaveData(this.state);
143
+ if (this.resumeAt)
144
+ data.position = { ...this.resumeAt };
145
+ // 今の作品の版を入れる(ロードした前の版のセーブも、セーブし直せば今の版のものになる)
146
+ if (this.gameVersion)
147
+ data.gameVersion = this.gameVersion;
148
+ const anchor = this.anchorOf(data.position);
149
+ if (anchor)
150
+ data.position.anchor = anchor;
151
+ // 呼び出しの戻り先にも目印を付ける(台本を直して呼んだ側の行がずれても、呼んだ命令の次へ戻るため)
152
+ data.callStack = data.callStack.map((frame) => {
153
+ const a = this.returnAnchor(frame.return);
154
+ return a ? { ...frame, return: { ...frame.return, anchor: a } } : frame;
155
+ });
156
+ return data;
157
+ }
158
+ /** 読み込み済みの実行単位(無ければ undefined。save は同期なので読み込まない)。 */
159
+ loadedUnit(id) {
160
+ const program = this.programs.get(fileOf(id));
161
+ if (!program)
162
+ return undefined;
163
+ return id === program.main.id ? program.main : program.defines.get(id.slice(id.indexOf("::") + 2));
164
+ }
165
+ /**
166
+ * 呼び出しの戻り先の目印。戻り先の一つ前が呼んだ命令(@call・マクロ・@with の中身)ならその命令(after)、
167
+ * そうでなく戻り先が選択肢(call=true の選択肢は、その選択肢へ戻る)ならその選択肢。
168
+ */
169
+ returnAnchor(at) {
170
+ const unit = this.loadedUnit(at.unit);
171
+ if (!unit)
172
+ return undefined;
173
+ const before = unit.instructions[at.index - 1];
174
+ const beforeKey = before && callSite(before) ? siteKey(before) : undefined;
175
+ if (before && beforeKey)
176
+ return { line: before.line, key: beforeKey, after: true };
177
+ const here = unit.instructions[at.index];
178
+ const key = here ? instructionKey(here) : undefined;
179
+ return here && key ? { line: here.line, key } : undefined;
180
+ }
181
+ /** その位置の命令の目印(本文・選択肢の行と文の鍵。ほかの命令は付けない)。読み込み済みの単位だけ(save は同期なので)。 */
182
+ anchorOf(at) {
183
+ const program = this.programs.get(fileOf(at.unit));
184
+ if (!program)
185
+ return undefined;
186
+ const unit = at.unit === program.main.id ? program.main : program.defines.get(at.unit.slice(at.unit.indexOf("::") + 2));
187
+ const ins = unit?.instructions[at.index];
188
+ if (!ins)
189
+ return undefined;
190
+ const key = instructionKey(ins);
191
+ return key ? { line: ins.line, key } : undefined;
192
+ }
193
+ /**
194
+ * セーブした位置を、今の台本に合わせる。目印の鍵(本文・選択肢の文)が同じ命令があればそこ(いくつもあれば元の行に近いもの)、
195
+ * 無ければ元の行にいちばん近い本文か選択肢。合わせ直したら知らせる(作品を更新して台本が変わったとき)。
196
+ */
197
+ async relocate(at) {
198
+ const anchor = at.anchor;
199
+ if (!anchor?.key)
200
+ return at;
201
+ const unit = await this.unit(at.unit);
202
+ const here = unit.instructions[at.index];
203
+ if (here && instructionKey(here) === anchor.key)
204
+ return at;
205
+ const candidates = unit.instructions.map((ins, index) => ({ ins, index })).filter(({ ins }) => instructionKey(ins) === anchor.key);
206
+ const pool = candidates.length > 0 ? candidates : unit.instructions.map((ins, index) => ({ ins, index })).filter(({ ins }) => ins.op === "say" || ins.op === "choice");
207
+ if (pool.length === 0)
208
+ return at;
209
+ const best = pool.reduce((a, b) => (Math.abs(b.ins.line - anchor.line) < Math.abs(a.ins.line - anchor.line) ? b : a));
210
+ this.diagnostic("warning", "save-relocated", `セーブした位置(${anchor.line} 行目)がシナリオの変更でずれたため、${best.ins.line} 行目から再開します`, unit, best.ins.line);
211
+ return { unit: at.unit, index: best.index };
212
+ }
213
+ /**
214
+ * 呼び出しの戻り先を、今の台本に合わせる。目印があれば同じ命令(呼んだ命令の次か、call=true の選択肢)を探す(いくつもあれば元の行に近いもの)。
215
+ * 目印の無い前の版のセーブは、戻り先の一つ前が呼んだ命令でも選択肢でもない(行がずれている)ときだけ、呼ばれた先を呼ぶ命令のうち
216
+ * 元の位置にいちばん近いものの次へ直す。見つからなければそのまま。直したら知らせる(save-relocated)。
217
+ */
218
+ async relocateReturns() {
219
+ const stack = this.state.callStack;
220
+ for (let i = 0; i < stack.length; i++) {
221
+ const frame = stack[i];
222
+ const at = frame.return;
223
+ const anchor = at.anchor;
224
+ delete at.anchor;
225
+ let unit;
226
+ try {
227
+ unit = await this.unit(at.unit);
228
+ }
229
+ catch {
230
+ continue;
231
+ }
232
+ const ins = unit.instructions.map((x, index) => ({ x, index }));
233
+ let to = null;
234
+ if (anchor) {
235
+ const offset = anchor.after ? 1 : 0;
236
+ const key = (x) => (anchor.after ? (callSite(x) ? siteKey(x) : undefined) : instructionKey(x));
237
+ const here = unit.instructions[at.index - offset];
238
+ if (here && key(here) === anchor.key)
239
+ continue;
240
+ const pool = ins.filter(({ x }) => key(x) === anchor.key);
241
+ if (pool.length === 0)
242
+ continue;
243
+ const best = pool.reduce((a, b) => (Math.abs(b.x.line - anchor.line) < Math.abs(a.x.line - anchor.line) ? b : a));
244
+ to = { index: best.index + offset, line: best.x.line };
245
+ }
246
+ else {
247
+ const before = unit.instructions[at.index - 1];
248
+ const here = unit.instructions[at.index];
249
+ if ((before && callSite(before)) || here?.op === "choice")
250
+ continue;
251
+ const callee = i + 1 < stack.length ? stack[i + 1].return.unit : this.state.position.unit;
252
+ const pool = ins.filter(({ x }) => calls(x, unit.file, callee));
253
+ if (pool.length === 0)
254
+ continue;
255
+ const best = pool.reduce((a, b) => (Math.abs(b.index - at.index) < Math.abs(a.index - at.index) ? b : a));
256
+ to = { index: best.index + (best.x.op === "choice" ? 0 : 1), line: best.x.line };
257
+ }
258
+ const from = anchor?.line ?? unit.instructions[at.index]?.line ?? 0;
259
+ this.diagnostic("warning", "save-relocated", `呼び出しの戻り先(${from} 行目)がシナリオの変更でずれたため、${to.line} 行目の次へ戻ります`, unit, to.line);
260
+ frame.return = { unit: at.unit, index: to.index };
261
+ }
262
+ }
263
+ /**
264
+ * セーブデータから再開する。描画側には現在の状態をそのまま渡し直す。
265
+ * options.call は、再開したページから場面(`#ラベル`・`ファイル#ラベル`)を呼ぶ(常駐のボタンの call=)。呼んだ場面は @return か、
266
+ * 次のラベルかファイルの終わりで戻り、そのページを出し直す。options.afterLoad を false にすると、作品の afterLoad を呼ばない
267
+ * (同じプレイの続きを組み立て直すとき)。
268
+ */
269
+ async load(raw, options = {}) {
270
+ // 古い版のセーブは今の版にする。新しい版・壊れたセーブは読まない
271
+ let save;
272
+ try {
273
+ save = migrateSave(raw);
274
+ }
275
+ catch (e) {
276
+ const message = e instanceof Error ? e.message : String(e);
277
+ this.host.onDiagnostic?.({ severity: "error", code: "save-version", message, file: "", line: 0 });
278
+ return { reason: "error", at: { unit: "", index: 0 }, message };
279
+ }
280
+ await this.program(fileOf(save.position.unit));
281
+ // 捨てた実行器は組み立て直さない(読み込みの途中で捨てられたとき、ほかの画面を上書きしないため)
282
+ if (this.abort.signal.aborted)
283
+ return { reason: "stopped", at: { ...save.position } };
284
+ this.state = { ...save, temp: this.state.temp };
285
+ this.state.position = await this.relocate(this.state.position);
286
+ delete this.state.position.anchor;
287
+ await this.relocateReturns();
288
+ // 初期値を足したあとのセーブにない変数は、初期値で補う
289
+ for (const [k, v] of Object.entries(this.gameDefaults))
290
+ if (!(k in this.state.game))
291
+ this.state.game[k] = structuredClone(v);
292
+ this.fillSystemDefaults();
293
+ // セーブしたときと違う言語で遊んでいれば、置いたままの文字を今の言語にする
294
+ this.retranslate();
295
+ this.pageRead = false;
296
+ await this.host.present({ type: "command", name: "restore", args: {}, wait: false, stage: this.state.stage }, this.abort.signal);
297
+ // 再開したページから場面を呼ぶ(戻ったらそのページを出し直す)
298
+ if (options.call)
299
+ await this.callScene(options.call, false, "here");
300
+ if (this.afterLoad && options.afterLoad !== false) {
301
+ // ロードしたページへ @return で戻るように呼び出す
302
+ this.state.callStack.push({ return: { ...this.state.position }, locals: this.state.locals });
303
+ this.state.locals = {};
304
+ await this.jump(this.afterLoad);
305
+ }
306
+ return this.run();
307
+ }
308
+ stop() {
309
+ this.halt ??= { reason: "stopped", at: { ...this.state.position } };
310
+ }
311
+ /**
312
+ * 命令から場面(`#ラベル`・`ファイル#ラベル`)を呼び出す。呼んだ場面が次のラベルかファイルの終わりに着いたら、@return を書かなくても戻る。
313
+ * again なら、戻ったときにこの命令をもう一度実行する(調べる場所の画面を出し直すなど)。そうでなければ次の行へ進む。
314
+ * 場面の中で @jump したり選択肢でほかへ飛んだりしたら戻らない(@return を書けば、そこで戻る)。
315
+ */
316
+ async callScene(target, again = false, from = "command") {
317
+ const at = this.state.position;
318
+ // here は、今の位置(まだ実行していない命令)へ戻る(ロードしたページを出し直す)
319
+ const back = from === "here" ? { ...at } : again ? { unit: at.unit, index: Math.max(0, at.index - 1) } : { ...at };
320
+ this.state.callStack.push({ return: back, locals: this.state.locals, scene: true });
321
+ this.state.locals = {};
322
+ await this.jump(target);
323
+ // 呼んだ場面のラベルそのものでは戻らないよう、ラベルを踏んでから始める(入った回数は数える)
324
+ const unit = await this.unit(this.state.position.unit);
325
+ const ins = unit.instructions[this.state.position.index];
326
+ if (ins?.op === "label") {
327
+ if (unit.id === unit.file)
328
+ this.visited(`${unit.file}#${ins.name}`);
329
+ this.state.position.index++;
330
+ }
331
+ }
332
+ /** 場面の呼び出しの枠から戻る(次のラベルかファイルの終わりに着いた)。 */
333
+ returnFromScene() {
334
+ const frame = this.state.callStack.pop();
335
+ this.state.position = { ...frame.return };
336
+ this.state.locals = frame.locals;
337
+ }
338
+ /** 場面の呼び出しの中で、ほかへ飛んだ(戻らない)。 */
339
+ leaveScene() {
340
+ if (this.state.callStack.at(-1)?.scene)
341
+ this.state.callStack.pop();
342
+ }
343
+ /** 読んだ作品のデータ(名前 → 値)。 */
344
+ dataCache = new Map();
345
+ dataLoader;
346
+ /** 作品のデータを読む(ctx.data)。ホストが読めなければ undefined。 */
347
+ loadData(name) {
348
+ const key = name.endsWith(".json") ? name : `${name}.json`;
349
+ let p = this.dataCache.get(key);
350
+ if (!p) {
351
+ const loader = this.dataLoader;
352
+ const host = this.host;
353
+ p = (async () => {
354
+ const v = host.loadData ? await host.loadData(key) : undefined;
355
+ return v !== undefined ? v : loader ? await loader(key) : undefined;
356
+ })().catch(() => undefined);
357
+ this.dataCache.set(key, p);
358
+ }
359
+ return p;
360
+ }
361
+ /** 命令から飛ぶ(`ファイル`・`#ラベル`・`ファイル#ラベル`)。 */
362
+ async jump(target) {
363
+ const [file = "", label] = target.split("#");
364
+ await this.goto({ file: file === "" ? null : file, label: label ?? null }, fileOf(this.state.position.unit));
365
+ }
366
+ /** `game.x` のような変数に値を入れる(命令の結果を受け取るとき)。 */
367
+ setVariable(path, value) {
368
+ const parts = path.split(".");
369
+ const root = parts.shift();
370
+ if (root !== "game" && root !== "system" && root !== "temp")
371
+ throw new EvalError(`変数 ${path} には代入できません`);
372
+ checkKeys(parts);
373
+ let o = this.env.lookup(root);
374
+ for (const p of parts.slice(0, -1))
375
+ o = (o[p] && typeof o[p] === "object" ? o[p] : (o[p] = {}));
376
+ o[parts.at(-1)] = value;
377
+ this.assigned(path, value);
378
+ }
379
+ /** キャストの定義(options.cast)。開発中に cast.json を書き換えたときは、プレイヤーが差し替える。 */
380
+ cast;
381
+ /** 立ち絵の登場順の自動配置の並べ方(options.autoLayout)。開発中に liminalia.json を書き換えたときは、プレイヤーが差し替える。 */
382
+ autoLayout;
383
+ /** 実行中の命令の行に診断を出す(命令の実装が、止めずに知らせたいとき)。 */
384
+ report(severity, code, message) {
385
+ if (this.currentUnit)
386
+ this.diagnostic(severity, code, message, this.currentUnit, this.currentLine);
387
+ }
388
+ /** 実行中の命令の位置(ファイルと行)。始める前は null。 */
389
+ get at() {
390
+ return this.currentUnit ? { file: this.currentUnit.file, line: this.currentLine } : null;
391
+ }
392
+ /**
393
+ * 今いるファイルとラベル(その位置より前で最後のラベル。ラベルより前なら label は null)。@define の中なら、呼び出したところ。
394
+ * セーブの一覧に章の名前を出すのに使う。読み込む前は null。
395
+ */
396
+ get label() {
397
+ const unit = this.currentUnit;
398
+ const program = unit ? this.programs.get(unit.file) : undefined;
399
+ if (!unit || !program)
400
+ return null;
401
+ let line = this.currentLine;
402
+ if (unit !== program.main) {
403
+ // @define の中なら、本体のどこから呼んだか(戻る位置の一つ前の命令)
404
+ const back = [...this.state.callStack].reverse().find((f) => f.return.unit === program.main.id);
405
+ const call = back ? program.main.instructions[back.return.index - 1] : undefined;
406
+ if (!call)
407
+ return { file: unit.file, label: null };
408
+ line = call.line;
409
+ }
410
+ // ラベルの位置は、ラベルの次の命令。その命令の行が今の行より後なら、まだそのラベルには入っていない
411
+ let label = null;
412
+ let best = -1;
413
+ for (const [name, index] of Object.entries(program.main.labels)) {
414
+ const first = program.main.instructions[index];
415
+ if (first && first.line <= line && index > best) {
416
+ label = name;
417
+ best = index;
418
+ }
419
+ }
420
+ return { file: unit.file, label };
421
+ }
422
+ waitClick() {
423
+ return this.host.waitClick(this.abort.signal);
424
+ }
425
+ /** 読み込んだファイルの、本文の行 → ページの鍵(既読を覚えるのに使う)。まだ読み込んでいなければ undefined。 */
426
+ pageKeysOf(file) {
427
+ return this.programs.get(file)?.pageKeys;
428
+ }
429
+ /** 本文のページを出している最中か(@voice が「その場で鳴らす」か「次の台詞で鳴らす」かを決める)。 */
430
+ get speaking() {
431
+ return this.inPage;
432
+ }
433
+ /** 出しているページの話者(地の文と、ページの外は null)。本文の中の @voice のフィルターに使う。 */
434
+ get speakerNow() {
435
+ return this.inPage ? this.pageSpeaker : null;
436
+ }
437
+ dispose() {
438
+ this.abort.abort();
439
+ this.stop();
440
+ }
441
+ // ---- 取っておいた状態(@sleep-game・@checkpoint) ----
442
+ /** 今の状態を取っておく。位置は実行中の命令の次。 */
443
+ snapshot() {
444
+ const { position, locals, callStack, game, stage, seed, visits, chosen, variants } = this.state;
445
+ return structuredClone({ position, locals, callStack, game, stage, seed, ...(visits ? { visits } : {}), ...(chosen ? { chosen } : {}), ...(variants ? { variants } : {}) });
446
+ }
447
+ /**
448
+ * 取っておいた状態に戻り、描画側に画面を組み立て直させる。
449
+ * keepVariables なら game. は今の値を、keepBgm なら BGM は今鳴っているものを残す。
450
+ */
451
+ async restoreSnapshot(snapshot, o) {
452
+ const s = structuredClone(snapshot);
453
+ // 進み具合(visits・chosen)はゲームの変数と同じに扱う
454
+ if (o.keepVariables)
455
+ Object.assign(s, { game: this.state.game, visits: this.state.visits, chosen: this.state.chosen, variants: this.state.variants });
456
+ else
457
+ Object.assign(s, { visits: s.visits, chosen: s.chosen, variants: s.variants });
458
+ if (o.keepBgm)
459
+ s.stage.bgm = this.state.stage.bgm;
460
+ Object.assign(this.state, s);
461
+ this.resumeAt = null;
462
+ this.retranslate();
463
+ this.pageRead = false;
464
+ await this.host.present({ type: "command", name: "restore", args: {}, wait: false, stage: this.state.stage }, this.abort.signal);
465
+ }
466
+ // ---- 実行 ----
467
+ async run() {
468
+ // 捨てた(dispose した)実行器は動かさない
469
+ if (this.abort.signal.aborted)
470
+ return { reason: "stopped", at: { ...this.state.position } };
471
+ this.halt = null;
472
+ while (this.halt === null) {
473
+ if (++this.steps > this.maxSteps)
474
+ return { reason: "max-steps", at: { ...this.state.position } };
475
+ const unit = await this.unit(this.state.position.unit);
476
+ const instruction = unit.instructions[this.state.position.index];
477
+ if (!instruction) {
478
+ // 場面の呼び出し(callScene)はファイルの終わりで戻る
479
+ if (this.state.callStack.at(-1)?.scene && unit.id === unit.file) {
480
+ this.returnFromScene();
481
+ continue;
482
+ }
483
+ return { reason: "end", at: { ...this.state.position } };
484
+ }
485
+ this.onStep?.({ file: unit.file, line: instruction.line });
486
+ const hold = this.beforeStep?.({ file: unit.file, line: instruction.line });
487
+ if (hold) {
488
+ await hold;
489
+ if (this.abort.signal.aborted)
490
+ return { reason: "stopped", at: { ...this.state.position } };
491
+ if (this.halt !== null)
492
+ break;
493
+ }
494
+ this.state.position.index++;
495
+ this.currentUnit = unit;
496
+ this.currentLine = instruction.line;
497
+ try {
498
+ await this.execute(instruction, unit);
499
+ }
500
+ catch (e) {
501
+ if (e instanceof EvalError)
502
+ this.fail(e.message, unit, instruction.line);
503
+ else
504
+ throw e;
505
+ }
506
+ }
507
+ return this.halt;
508
+ }
509
+ async execute(ins, unit) {
510
+ const signal = this.abort.signal;
511
+ switch (ins.op) {
512
+ case "label":
513
+ // 場面の呼び出し(callScene)は次のラベルに着いたら戻る
514
+ if (unit.id === unit.file && this.state.callStack.at(-1)?.scene)
515
+ return this.returnFromScene();
516
+ // ファイル本体のラベルに入った回数と既読(式の visits・read)
517
+ if (unit.id === unit.file)
518
+ this.visited(`${unit.file}#${ins.name}`);
519
+ return;
520
+ case "say":
521
+ await this.flushSceneWait();
522
+ this.holdResume({ unit: unit.id, index: this.state.position.index - 1 });
523
+ await this.say(ins.speaker, ins.content, unit, ins.line, ins.name, ins.id);
524
+ this.holdResume(null);
525
+ return;
526
+ case "command":
527
+ return this.command(ins.name, ins.args, unit, ins.line, ins.body, ins.content);
528
+ case "content": {
529
+ // マクロに @with で渡された中身を、呼んだ側の局所変数で実行する(渡されていなければ何もしない)
530
+ const frame = this.state.callStack.at(-1);
531
+ if (!frame?.content)
532
+ return;
533
+ this.state.callStack.push({ return: { ...this.state.position }, locals: this.state.locals });
534
+ this.state.locals = frame.locals;
535
+ this.state.position = { unit: frame.content, index: 0 };
536
+ return;
537
+ }
538
+ case "branch":
539
+ if (!this.condition(ins.condition, unit, ins.line))
540
+ this.state.position.index = ins.otherwise;
541
+ return;
542
+ case "goto":
543
+ this.state.position.index = ins.to;
544
+ return;
545
+ case "set": {
546
+ // `@set 変数 = "文字"` の文字は、訳があれば訳を入れる(鍵はコマンドの文字と同じ。lim i18n が集める)
547
+ const source = this.translator?.arg ? translatableSetValue(ins.operator, ins.value) : null;
548
+ const translated = source !== null ? this.translator?.arg?.(unit.file, source, contextAt(unit.labels, this.state.position.index - 1)) : null;
549
+ return this.assign(ins.target, ins.operator, translated || this.eval(ins.value));
550
+ }
551
+ case "let":
552
+ checkKeys([ins.name]);
553
+ this.state.locals[ins.name] = this.eval(ins.value);
554
+ this.assigned(ins.name, this.state.locals[ins.name]);
555
+ return;
556
+ case "choice": {
557
+ await this.flushSceneWait();
558
+ // 条件(if=)が偽の選択肢は出さない。描画側・道筋の探索には出すものだけを渡し、選ばれた番号もその中の番号。
559
+ const shown = ins.options.filter((o) => this.optionFlag(o.args, "if", true, unit, o.line));
560
+ if (shown.length === 0) {
561
+ // TyranoScript で cond がすべて偽の [glink] のあとの [s] と同じく、選べるものが無いまま止まる(@stop と同じ)。
562
+ this.diagnostic("warning", "no-choice-shown", "選択肢の条件(if=)がすべて偽で、表示する選択肢がないため止まりました", unit, ins.line);
563
+ this.stop();
564
+ return;
565
+ }
566
+ const context = contextAt(unit.labels, this.state.position.index - 1);
567
+ // 再開の状態は、選択肢の文の出し分け({seq …})を進める前に控える(ロードで同じ文を出す)
568
+ this.holdResume({ unit: unit.id, index: this.state.position.index - 1 });
569
+ const texts = shown.map((o) => this.withVariants(unit.file, printInline(o.content), true, () => this.plain(this.translator?.option(unit.file, printInline(o.content), context, o.id) ?? o.content)));
570
+ const looks = shown.map((o) => (o.args.some((a) => !NOT_LOOK.has(a.key) || a.key === "locked") ? this.look(o.args, unit, o.line, context) : null));
571
+ // 飛び先(道筋の探索が目標に近い選択肢から試すのに使う)。式の飛び先は分からないので null
572
+ const targets = shown.map((o) => (o.target.expr ? null : `${o.target.file ?? unit.file}${o.target.label ? `#${o.target.label}` : ""}`));
573
+ // 制限時間(@choice timeout=)。描画側に残り時間を見せさせ、過ぎたら選ぶのをやめさせる
574
+ const block = ins.args ? this.resolveArgs(CHOICE_BLOCK, ins.args) : {};
575
+ const timeout = typeof block.timeout === "number" && block.timeout > 0 ? block.timeout : 0;
576
+ let timedOut = false;
577
+ const counting = new AbortController();
578
+ let chooseSignal = signal;
579
+ // 選び終えたら外す(実行器の signal は一回の遊びのあいだ同じなので、残すと選択肢の数だけたまる)
580
+ let stopLimit = () => undefined;
581
+ if (timeout > 0) {
582
+ const limit = new AbortController();
583
+ stopLimit = () => limit.abort();
584
+ signal.addEventListener("abort", stopLimit, { once: true });
585
+ chooseSignal = limit.signal;
586
+ await this.host.present({ type: "command", name: "choice-timer", args: { time: timeout }, wait: false, stage: this.state.stage }, signal);
587
+ // 時間は描画側に計らせる(システム画面を開いている間は止める)。描画側が計らなければ実時間で
588
+ const elapsed = this.host.countdown ? this.host.countdown(timeout, counting.signal) : realCountdown(timeout, counting.signal);
589
+ void elapsed.then(() => {
590
+ if (counting.signal.aborted)
591
+ return;
592
+ timedOut = true;
593
+ limit.abort();
594
+ });
595
+ }
596
+ let selected = await this.host.choose(texts, chooseSignal, looks.some((l) => l !== null) ? looks : undefined, targets);
597
+ counting.abort();
598
+ signal.removeEventListener("abort", stopLimit);
599
+ this.holdResume(null);
600
+ if (selected === null && timedOut && !signal.aborted) {
601
+ // 時間切れ: default(上から何番目か)が表示されていて押せるならそれ、そうでなければ選ばずに @end の後へ
602
+ const fallback = typeof block.default === "number" ? ins.options[block.default - 1] : undefined;
603
+ if (fallback && shown.includes(fallback) && !this.optionFlag(fallback.args, "locked", false, unit, fallback.line)) {
604
+ selected = shown.indexOf(fallback);
605
+ }
606
+ else {
607
+ return;
608
+ }
609
+ }
610
+ if (selected === null) {
611
+ this.stop();
612
+ return;
613
+ }
614
+ const option = shown[selected];
615
+ if (!option)
616
+ return this.fail(`選択肢 ${selected} はありません`, unit, ins.line);
617
+ // 本文の流れに出す選択肢(ui.choice.position: inline)は、@nvl の間、選んだものを本文の一部として残す(ロードで出し直す)
618
+ if (this.options.inlineChoices === true && this.state.stage.nvl === true) {
619
+ (this.state.stage.nvlPages ??= []).push({
620
+ speaker: null,
621
+ parts: [],
622
+ choice: {
623
+ options: shown.map((o, i) => ({
624
+ text: texts[i] ?? "",
625
+ origin: { kind: "option", file: unit.file, source: printInline(o.content), ...(context ? { context } : {}), ...(o.id ? { id: o.id } : {}) },
626
+ })),
627
+ picked: selected,
628
+ },
629
+ });
630
+ }
631
+ const calls = this.optionFlag(option.args, "call", false, unit, option.line);
632
+ this.noteChosen(option);
633
+ if (!calls)
634
+ this.host.chosen?.({ text: texts[selected] ?? "", index: selected });
635
+ await this.chatChosen(texts[selected] ?? "", looks[selected] ?? null, { kind: "option", file: unit.file, source: printInline(option.content), ...(context ? { context } : {}), ...(option.id ? { id: option.id } : {}) });
636
+ if (!calls)
637
+ this.leaveScene();
638
+ if (calls) {
639
+ // call=true: 呼び出して、@return でこの選択肢へ戻る(もう一度出す。切り替えのボタンなど)
640
+ this.state.callStack.push({ return: { unit: unit.id, index: this.state.position.index - 1 }, locals: this.state.locals });
641
+ this.state.locals = {};
642
+ return this.goto(option.target, unit.file, option.line);
643
+ }
644
+ return this.moveTo(option.target, unit.file, option.line);
645
+ }
646
+ case "jump":
647
+ this.leaveScene();
648
+ return this.moveTo(ins.target, unit.file, ins.line);
649
+ case "call":
650
+ this.state.callStack.push({ return: { ...this.state.position }, locals: this.state.locals });
651
+ this.state.locals = {};
652
+ return this.goto(ins.target, unit.file, ins.line);
653
+ case "return": {
654
+ // マクロの戻り値は、局所変数を戻す前に計算する
655
+ const value = ins.value ? this.eval(ins.value) : undefined;
656
+ const frame = this.state.callStack.pop();
657
+ if (!frame)
658
+ return this.returnWithoutCall === "continue" ? undefined : this.fail("@call されていない場所で @return が実行されました", unit, ins.line);
659
+ this.state.position = { ...frame.return };
660
+ this.state.locals = frame.locals;
661
+ if (value !== undefined && frame.result)
662
+ this.setVariable(frame.result, value);
663
+ return;
664
+ }
665
+ case "script":
666
+ if (this.host.runScript)
667
+ return this.host.runScript(ins.code, { ...this.state.position });
668
+ this.diagnostic("warning", "script-skipped", "@script の中身は実行しません", unit, ins.line);
669
+ return;
670
+ }
671
+ }
672
+ // ---- 本文 ----
673
+ async say(speaker, content, unit, line, name, id) {
674
+ this.inPage = true;
675
+ this.pageSpeaker = speaker;
676
+ try {
677
+ await this.sayPage(speaker, content, unit, line, name, id);
678
+ }
679
+ finally {
680
+ this.pageSpeaker = null;
681
+ this.inPage = false;
682
+ }
683
+ }
684
+ async sayPage(speaker, content, unit, line, name, id) {
685
+ const signal = this.abort.signal;
686
+ const index = this.state.position.index - 1;
687
+ this.host.prefetch?.([...collectPrefetch(unit, index, this.registry), ...this.voicePrefetch(unit, index)]);
688
+ this.prefetchTargets(unit, index);
689
+ const voice = this.takeVoice(speaker, unit.file, line);
690
+ // 行の最後の {noclick}: クリックを待たずに次へ進む(訳の書き方によらず、原文で決める)
691
+ const noclick = content.at(-1)?.kind === "noclick";
692
+ // 前のページが残した本文({noclick})は、このページで消える
693
+ delete this.state.stage.noclickPage;
694
+ this.pageRead = false;
695
+ const source = printInline(content);
696
+ const context = contextAt(unit.labels, index);
697
+ const translated = this.translator?.line(unit.file, source, context, id);
698
+ if (translated)
699
+ content = translated;
700
+ // 台詞の外側の括弧と引用符を外す(ui.text.quotes: strip)
701
+ if (speaker !== null && this.stripQuotes())
702
+ content = stripSpeechQuotes(content);
703
+ const label = speaker === null ? null : this.speakerLabel(speaker, name);
704
+ delete this.state.stage.windowSuppressed;
705
+ // @window で消していなければ、本文の前にメッセージウィンドウを出す(@window show を書かなくても文字が見える)
706
+ if (!this.state.stage.window && !this.state.stage.windowHidden) {
707
+ this.state.stage.window = true;
708
+ await this.host.present({ type: "command", name: "window", args: { mode: "show" }, wait: false, stage: this.state.stage }, signal);
709
+ }
710
+ const key = this.programs.get(unit.file)?.pageKeys.get(line);
711
+ // 同時に話すほかの話者(二つ目のボイスの who)。名前欄、履歴、聞いた話者に使う
712
+ const together = [...new Set((voice?.also ?? []).flatMap((c) => (c.who && c.who !== speaker ? [c.who] : [])))].map((who) => {
713
+ const shown = this.speakerLabel(who);
714
+ return shown ? { speaker: who, label: shown } : { speaker: who };
715
+ });
716
+ await this.host.present({ type: "page", speaker, at: { file: unit.file, line }, ...(key ? { key } : {}), ...(label ? { label } : {}), ...(voice ? { voice } : {}), ...(together.length > 0 ? { with: together } : {}) }, signal);
717
+ const base = { bold: false, italic: false, color: null, perChar: null, size: null, mark: null };
718
+ const parts = [];
719
+ // 本文の出し分け({seq …})の鍵の頭と、このページの中で何番目か
720
+ const variantBase = `${unit.file}#${textHash(source)}`;
721
+ let variantIndex = 0;
722
+ const walk = async (nodes, style) => {
723
+ for (const n of nodes) {
724
+ // 捨てた(dispose した)実行器は、ページの残りを描画側へ送らない(制作画面の舞台が、同じ画面を組み立て直している最中など)。
725
+ if (signal.aborted)
726
+ return;
727
+ switch (n.kind) {
728
+ case "text":
729
+ parts.push({ text: n.text, ruby: null, style });
730
+ await this.host.present({ type: "text", text: n.text, ruby: null, style }, signal);
731
+ break;
732
+ case "ruby":
733
+ parts.push({ text: n.base, ruby: n.reading, style });
734
+ await this.host.present({ type: "text", text: n.base, ruby: n.reading, style }, signal);
735
+ break;
736
+ case "value":
737
+ {
738
+ const text = display(this.eval(n.expr));
739
+ parts.push({ text, ruby: null, style });
740
+ await this.host.present({ type: "text", text, ruby: null, style }, signal);
741
+ }
742
+ break;
743
+ case "br":
744
+ parts.push({ br: true });
745
+ await this.host.present({ type: "br" }, signal);
746
+ break;
747
+ case "click":
748
+ await this.host.waitClick(signal);
749
+ break;
750
+ case "noclick":
751
+ break;
752
+ case "command":
753
+ await this.command(n.name, n.args, unit, line);
754
+ break;
755
+ case "style":
756
+ await walk(n.children, { ...style, [n.style]: true });
757
+ break;
758
+ case "color":
759
+ await walk(n.children, { ...style, color: n.color });
760
+ break;
761
+ case "speed":
762
+ await walk(n.children, { ...style, perChar: n.perChar });
763
+ break;
764
+ case "size":
765
+ await walk(n.children, { ...style, size: n.size });
766
+ break;
767
+ case "mark":
768
+ await walk(n.children, { ...style, mark: n.color });
769
+ break;
770
+ case "fx": {
771
+ // 内側の {fx} は外側の大きさと速さを引き継がない
772
+ const { fxStrength: _s, fxSpeed: _v, ...rest } = style;
773
+ await walk(n.children, { ...rest, fx: n.effect, ...(n.strength !== undefined ? { fxStrength: n.strength } : {}), ...(n.speed !== undefined ? { fxSpeed: n.speed } : {}) });
774
+ break;
775
+ }
776
+ case "emphasis":
777
+ await walk(n.children, { ...style, emphasis: true });
778
+ break;
779
+ case "variants":
780
+ await walk(this.variantItem(n, `${variantBase}:${variantIndex++}`, true), style);
781
+ break;
782
+ case "image":
783
+ parts.push({ text: "\uFFFC", ruby: null, style: { ...style, image: n.path, ...(n.height !== undefined ? { imageHeight: n.height } : {}) } });
784
+ await this.host.present({ type: "text", text: "\uFFFC", ruby: null, style: { ...style, image: n.path, ...(n.height !== undefined ? { imageHeight: n.height } : {}) } }, signal);
785
+ break;
786
+ }
787
+ }
788
+ };
789
+ await walk(content, base);
790
+ if (signal.aborted)
791
+ return;
792
+ if (!noclick)
793
+ await this.host.waitClick(signal);
794
+ if (!noclick && !signal.aborted && this.state.stage.nvl !== true && !(this.chatDialogue && chatDialogueActive(this.state.stage)))
795
+ this.pageRead = true;
796
+ // 別の言語でロードしたときに作り直す元(原文と場面)
797
+ const origin = { file: unit.file, source, ...(context ? { context } : {}), ...(name ? { name: printInline(name) } : {}), ...(id ? { id } : {}) };
798
+ // 読み終えてから積む(クリックを待っている間のセーブでは、このページはロードでもう一度出す)
799
+ if (this.state.stage.nvl === true && !signal.aborted)
800
+ (this.state.stage.nvlPages ??= []).push({ speaker, ...(label ? { label } : {}), parts, origin });
801
+ else if (noclick && !signal.aborted && !(this.chatDialogue && chatDialogueActive(this.state.stage))) {
802
+ // クリックを待たずに残した本文(次の選択肢などの間も出しておく)。ロードで組み立て直すときに出し直す
803
+ this.state.stage.noclickPage = { speaker, ...(label ? { label } : {}), parts, origin };
804
+ }
805
+ else if (this.chatDialogue && !signal.aborted && chatDialogueActive(this.state.stage)) {
806
+ const stage = this.state.stage;
807
+ const who = speaker !== null && this.cast ? castForSpeaker(this.cast, speaker) : null;
808
+ const pose = who ? (stage.sprites[who] ?? stage.faces?.[who]) : undefined;
809
+ pushChatMessage(stage.extra, this.chatDialogue, (chat) => ({
810
+ speaker: speaker ?? "",
811
+ text: chatPartsText(parts),
812
+ image: "",
813
+ me: speaker !== null && speaker === (chat.me || this.chatDialogue?.me),
814
+ ...(speaker === null ? { note: true } : {}),
815
+ ...(label ? { label } : {}),
816
+ parts,
817
+ ...(who && pose ? { face: { who, appearance: pose.appearance, variant: pose.variant } } : {}),
818
+ // 言語を替えたときに出し直す元(本文の行と、名前欄の名前)
819
+ i18n: textOrigins({
820
+ text: { kind: "line", file: unit.file, source, ...(context ? { context } : {}), ...(id ? { id } : {}) },
821
+ label: speaker === null ? undefined : { kind: "speaker", source: this.shownName(speaker, name) },
822
+ }),
823
+ }));
824
+ }
825
+ }
826
+ /**
827
+ * 名前欄に出す名前(話者と違うときだけ。同じなら null)。この行の {name …}、無ければ @name で替えた名前、どちらも無ければ話者名。
828
+ * 訳があれば訳す(表示名の訳は、話者名と同じく訳のファイルの speakers に書く)。
829
+ */
830
+ speakerLabel(speaker, name) {
831
+ const shown = this.shownName(speaker, name);
832
+ const label = this.translator?.speaker(shown) ?? shown;
833
+ return label === speaker ? null : label;
834
+ }
835
+ /** 名前欄に出す名前の原文(この行の {name …}、無ければ @name で替えた名前、どちらも無ければ話者名)。 */
836
+ shownName(speaker, name) {
837
+ return name ? this.plain(name) : (this.state.stage.names?.[speaker] ?? speaker);
838
+ }
839
+ /**
840
+ * 置いたままの文字(stage.extra の中の、i18n を持つもの。retranslate.ts)を、今の言語(translator)で書き換える。
841
+ * ロードしたときと巻き戻したときに呼び、言語を替えたときはシステム画面が呼んで描画側に出し直させる。書き換えたものがあれば true。
842
+ */
843
+ retranslate() {
844
+ let changed = false;
845
+ for (const { target, origins } of withOrigins(this.state.stage.extra)) {
846
+ for (const [field, origin] of Object.entries(origins)) {
847
+ try {
848
+ if (this.retranslateField(target, field, origin))
849
+ changed = true;
850
+ }
851
+ catch {
852
+ // 式の値が読めないなど。その欄は今のまま
853
+ }
854
+ }
855
+ }
856
+ // NVL の読み終えた段落と、クリックを待たずに残した本文({noclick})
857
+ const stage = this.state.stage;
858
+ for (const page of [...(stage.nvlPages ?? []), ...(stage.noclickPage ? [stage.noclickPage] : [])]) {
859
+ try {
860
+ if (this.retranslatePage(page))
861
+ changed = true;
862
+ }
863
+ catch {
864
+ // 式の値が読めないなど。その段落は今のまま
865
+ }
866
+ }
867
+ return changed;
868
+ }
869
+ /** 読み終えた本文の一ページを、元(origin)から今の言語で作り直す。変わったら true。 */
870
+ retranslatePage(page) {
871
+ // 本文の流れに出した選択肢(ui.choice.position: inline)は、一つずつの文を訳し直す
872
+ if (page.choice) {
873
+ let changed = false;
874
+ for (const option of page.choice.options) {
875
+ const o = option.origin;
876
+ if (!o)
877
+ continue;
878
+ const target = { text: option.text };
879
+ if (this.retranslateField(target, "text", o) && typeof target.text === "string") {
880
+ option.text = target.text;
881
+ changed = true;
882
+ }
883
+ }
884
+ return changed;
885
+ }
886
+ const o = page.origin;
887
+ if (!o || typeof o.source !== "string" || typeof o.file !== "string")
888
+ return false;
889
+ const before = JSON.stringify([page.parts, page.label ?? null]);
890
+ let content = this.translator?.line(o.file, o.source, o.context, o.id) ?? parseInline(o.source).content;
891
+ if (page.speaker !== null && this.stripQuotes())
892
+ content = stripSpeechQuotes(content);
893
+ page.parts = this.withVariants(o.file, o.source, false, () => this.partsOf(content));
894
+ if (page.speaker !== null) {
895
+ const label = this.speakerLabel(page.speaker, typeof o.name === "string" ? parseInline(o.name).content : undefined);
896
+ if (label)
897
+ page.label = label;
898
+ else
899
+ delete page.label;
900
+ }
901
+ return JSON.stringify([page.parts, page.label ?? null]) !== before;
902
+ }
903
+ retranslateField(target, field, o) {
904
+ if (!o || typeof o.source !== "string")
905
+ return false;
906
+ const tr = this.translator;
907
+ const before = JSON.stringify([target[field] ?? null, target.parts ?? null]);
908
+ switch (o.kind) {
909
+ case "arg":
910
+ target[field] = (o.file !== undefined ? tr?.arg?.(o.file, o.source, o.context) : null) || o.source;
911
+ break;
912
+ case "option":
913
+ target[field] = this.withVariants(o.file ?? "", o.source, false, () => this.plain((o.file !== undefined ? tr?.option(o.file, o.source, o.context, o.id) : null) ?? parseInline(o.source).content));
914
+ break;
915
+ case "speaker": {
916
+ const label = tr?.speaker(o.source) ?? o.source;
917
+ if (field === "label" && label === target.speaker)
918
+ delete target[field];
919
+ else
920
+ target[field] = label;
921
+ break;
922
+ }
923
+ case "line": {
924
+ const content = (o.file !== undefined ? tr?.line(o.file, o.source, o.context, o.id) : null) ?? parseInline(o.source).content;
925
+ // 台詞の吹き出し(地の文の一行でないもの)は、出したときと同じく外側の括弧と引用符を外す(ui.text.quotes: strip)
926
+ const parts = this.withVariants(o.file ?? "", o.source, false, () => this.partsOf(target.note !== true && typeof target.speaker === "string" && target.speaker !== "" && this.stripQuotes() ? stripSpeechQuotes(content) : content));
927
+ target.parts = parts;
928
+ target[field] = chatPartsText(parts);
929
+ break;
930
+ }
931
+ default:
932
+ return false;
933
+ }
934
+ return JSON.stringify([target[field] ?? null, target.parts ?? null]) !== before;
935
+ }
936
+ /** 本文を、描画側に送るのと同じ一片の並びにする(本文中の命令とクリック待ちは除く。式はいまの値)。 */
937
+ partsOf(nodes, style = { bold: false, italic: false, color: null, perChar: null, size: null, mark: null }, out = []) {
938
+ for (const n of nodes) {
939
+ switch (n.kind) {
940
+ case "text":
941
+ out.push({ text: n.text, ruby: null, style });
942
+ break;
943
+ case "ruby":
944
+ out.push({ text: n.base, ruby: n.reading, style });
945
+ break;
946
+ case "value":
947
+ out.push({ text: display(this.eval(n.expr)), ruby: null, style });
948
+ break;
949
+ case "br":
950
+ out.push({ br: true });
951
+ break;
952
+ case "style":
953
+ this.partsOf(n.children, { ...style, [n.style]: true }, out);
954
+ break;
955
+ case "color":
956
+ this.partsOf(n.children, { ...style, color: n.color }, out);
957
+ break;
958
+ case "speed":
959
+ this.partsOf(n.children, { ...style, perChar: n.perChar }, out);
960
+ break;
961
+ case "size":
962
+ this.partsOf(n.children, { ...style, size: n.size }, out);
963
+ break;
964
+ case "mark":
965
+ this.partsOf(n.children, { ...style, mark: n.color }, out);
966
+ break;
967
+ case "fx": {
968
+ const { fxStrength: _s, fxSpeed: _v, ...rest } = style;
969
+ this.partsOf(n.children, { ...rest, fx: n.effect, ...(n.strength !== undefined ? { fxStrength: n.strength } : {}), ...(n.speed !== undefined ? { fxSpeed: n.speed } : {}) }, out);
970
+ break;
971
+ }
972
+ case "emphasis":
973
+ this.partsOf(n.children, { ...style, emphasis: true }, out);
974
+ break;
975
+ case "variants":
976
+ this.partsOf(this.scopedVariant(n), style, out);
977
+ break;
978
+ case "image":
979
+ out.push({ text: "\uFFFC", ruby: null, style: { ...style, image: n.path, ...(n.height !== undefined ? { imageHeight: n.height } : {}) } });
980
+ break;
981
+ default:
982
+ break;
983
+ }
984
+ }
985
+ return out;
986
+ }
987
+ /** 選んだ選択肢を自分の吹き出しとして積み、描画側へ知らせる(ui.chat.dialogue のとき。絵のボタン・押せる範囲は積まない)。 */
988
+ async chatChosen(text, look, origin) {
989
+ const stage = this.state.stage;
990
+ if (!this.chatDialogue || text === "" || !chatDialogueActive(stage) || look?.image || (look?.width !== undefined && look.height !== undefined))
991
+ return;
992
+ pushChatMessage(stage.extra, this.chatDialogue, (chat) => ({ speaker: chat.me || (this.chatDialogue?.me ?? ""), text, image: "", me: true, ...(origin ? { i18n: { text: origin } } : {}) }));
993
+ await this.host.present({ type: "command", name: "chat-chosen", args: {}, wait: false, stage }, this.abort.signal);
994
+ }
995
+ /**
996
+ * このページで鳴らすボイス。@voice で決めたものがあればそれ、なければ話者の連番(番号を一つ進める)。
997
+ * 番号の固定があれば、その台詞に固定した番号(固定に無い台詞は鳴らさない)。
998
+ */
999
+ takeVoice(speaker, file, line) {
1000
+ const cue = this.nextVoice(speaker, file, line);
1001
+ if (!cue || !this.state.stage.voiceFilter)
1002
+ return cue;
1003
+ // @voice-filter で掛け続けているフィルター(@voice に filter を書いたボイスはそちら)
1004
+ const withFilter = (c, who) => {
1005
+ if (c.filter !== undefined)
1006
+ return c;
1007
+ const filter = voiceFilterFor(this.state.stage, who);
1008
+ return filter ? { ...c, filter } : c;
1009
+ };
1010
+ const main = withFilter(cue, cue.who ?? speaker);
1011
+ // who を省いたボイスはその台詞の話者のもの(話者ごとのフィルターは台詞の話者のを掛ける)
1012
+ return cue.also ? { ...main, also: cue.also.map((c) => withFilter(c, c.who ?? speaker)) } : main;
1013
+ }
1014
+ nextVoice(speaker, file, line) {
1015
+ const v = this.state.stage.voice;
1016
+ if (!v)
1017
+ return null;
1018
+ if (v.next) {
1019
+ const cue = v.next;
1020
+ v.next = null;
1021
+ if (!cue.also)
1022
+ return cue;
1023
+ // 同じ channel のボイスが重なったら、空いている channel へ回す(同時に鳴らすため)
1024
+ const used = new Set();
1025
+ const [first, ...rest] = [cue, ...cue.also].map((c) => {
1026
+ let channel = c.channel ?? 1;
1027
+ while (used.has(channel))
1028
+ channel++;
1029
+ used.add(channel);
1030
+ return channel === (c.channel ?? 1) ? c : { ...c, channel };
1031
+ });
1032
+ return { ...first, also: rest };
1033
+ }
1034
+ const auto = speaker === null ? undefined : v.auto?.[speaker];
1035
+ if (!auto || auto.off)
1036
+ return null;
1037
+ const n = this.lockedVoice(file, line) ?? (this.voiceLock ? null : auto.next);
1038
+ if (n === null)
1039
+ return null;
1040
+ auto.next = n + 1;
1041
+ return { file: voiceFile(auto.pattern, n), volume: auto.volume, folder: auto.folder, n };
1042
+ }
1043
+ /** その台詞に固定したボイスの番号(固定が無い・その台詞が無ければ null)。 */
1044
+ lockedVoice(file, line) {
1045
+ const lock = this.voiceLock;
1046
+ if (!lock)
1047
+ return null;
1048
+ const key = this.programs.get(file)?.voiceKeys.get(line);
1049
+ return (key !== undefined ? lock.lines[key]?.n : undefined) ?? null;
1050
+ }
1051
+ /** この先の台詞で鳴る連番のボイス(先読み用。分岐は両方とも数えるので、番号は目安)。 */
1052
+ voicePrefetch(unit, index, limit = 8) {
1053
+ const auto = this.state.stage.voice?.auto;
1054
+ if (!auto || Object.keys(auto).length === 0)
1055
+ return [];
1056
+ const next = Object.fromEntries(Object.entries(auto).map(([who, a]) => [who, a.next]));
1057
+ const out = [];
1058
+ for (let i = index; i < unit.instructions.length && out.length < limit; i++) {
1059
+ const ins = unit.instructions[i];
1060
+ if (ins.op !== "say" || ins.speaker === null)
1061
+ continue;
1062
+ const a = auto[ins.speaker];
1063
+ if (!a || a.off)
1064
+ continue;
1065
+ const n = this.lockedVoice(unit.file, ins.line) ?? (this.voiceLock ? null : next[ins.speaker]++);
1066
+ if (n !== null)
1067
+ out.push({ kind: "asset", folder: a.folder, path: voiceFile(a.pattern, n) });
1068
+ }
1069
+ return out;
1070
+ }
1071
+ plain(content) {
1072
+ let out = "";
1073
+ for (const n of content) {
1074
+ if (n.kind === "text")
1075
+ out += n.text;
1076
+ else if (n.kind === "ruby")
1077
+ out += n.base;
1078
+ else if (n.kind === "value")
1079
+ out += display(this.eval(n.expr));
1080
+ else if (n.kind === "style" || n.kind === "color" || n.kind === "speed" || n.kind === "size" || n.kind === "mark" || n.kind === "fx" || n.kind === "emphasis")
1081
+ out += this.plain(n.children);
1082
+ else if (n.kind === "variants")
1083
+ out += this.plain(this.scopedVariant(n));
1084
+ }
1085
+ return out;
1086
+ }
1087
+ // ---- 本文の出し分け({seq a|b|c} など) ----
1088
+ /** plain と partsOf が出し分けを読むときの鍵の頭(ファイルと原文)と、何番目か。advance でなければ前に出したものを読む。 */
1089
+ variantScope = null;
1090
+ withVariants(file, source, advance, run) {
1091
+ const previous = this.variantScope;
1092
+ this.variantScope = { base: `${file}#${textHash(source)}`, n: 0, advance };
1093
+ try {
1094
+ return run();
1095
+ }
1096
+ finally {
1097
+ this.variantScope = previous;
1098
+ }
1099
+ }
1100
+ /** withVariants の中なら、その鍵で出し分けを選ぶ。外なら頭のもの(表示名の {name …} の中など)。 */
1101
+ scopedVariant(node) {
1102
+ const scope = this.variantScope;
1103
+ if (!scope)
1104
+ return node.items[0] ?? [];
1105
+ return this.variantItem(node, `${scope.base}:${scope.n++}`, scope.advance);
1106
+ }
1107
+ /**
1108
+ * 出し分けで今回出すもの。advance なら通った回数を一つ進めて選び(seq は最後で止まる、cycle は頭に戻る、once は出し終えたら何も出さない、
1109
+ * shuffle は乱数で、前と同じものを続けない)、advance でなければ前に出したものを返す(言語を替えて出し直すとき)。
1110
+ */
1111
+ variantItem(node, key, advance) {
1112
+ const n = node.items.length;
1113
+ if (n === 0)
1114
+ return [];
1115
+ const seen = this.state.variants?.[key];
1116
+ const count = seen?.[0] ?? 0;
1117
+ const last = seen?.[1] ?? -1;
1118
+ if (!advance)
1119
+ return last >= 0 ? (node.items[last] ?? []) : [];
1120
+ let i;
1121
+ switch (node.mode) {
1122
+ case "seq":
1123
+ i = Math.min(count, n - 1);
1124
+ break;
1125
+ case "cycle":
1126
+ i = count % n;
1127
+ break;
1128
+ case "once":
1129
+ i = count < n ? count : -1;
1130
+ break;
1131
+ case "shuffle":
1132
+ if (n === 1)
1133
+ i = 0;
1134
+ else if (last < 0 || last >= n)
1135
+ i = Math.floor(this.env.random() * n);
1136
+ else {
1137
+ const r = Math.floor(this.env.random() * (n - 1));
1138
+ i = r >= last ? r + 1 : r;
1139
+ }
1140
+ break;
1141
+ }
1142
+ (this.state.variants ??= {})[key] = [count + 1, i];
1143
+ return i < 0 ? [] : (node.items[i] ?? []);
1144
+ }
1145
+ /**
1146
+ * 条件(@if、@elif、@while、@for、行の if=、選択肢の if= locked= call=)の式を真偽にする。式が誤りなら、誤りを知らせて偽として扱う
1147
+ * (真の枝へ黙って入らない。初期値の無い変数を数と比べたときなど)。
1148
+ */
1149
+ condition(expr, unit, line) {
1150
+ try {
1151
+ return truthy(this.eval(expr));
1152
+ }
1153
+ catch (e) {
1154
+ if (!(e instanceof EvalError))
1155
+ throw e;
1156
+ this.fail(`条件の式を計算できないため、偽として扱いました(${e.message})`, unit, line);
1157
+ return false;
1158
+ }
1159
+ }
1160
+ /**
1161
+ * 選択肢の条件のパラメータ。if= は出すか、locked= は押せない状態で見せるか、call= は選んだら呼び出すか。
1162
+ * 書いていなければ absent。式が誤りなら偽(condition)。
1163
+ */
1164
+ optionFlag(args, key, absent, unit, line) {
1165
+ const cond = normalizeBooleanArgs(CHOICE_OPTION, args).find((a) => a.key === key);
1166
+ if (!cond)
1167
+ return absent;
1168
+ return cond.value.kind === "expr" ? this.condition(cond.value.expr, unit, line) : truthy(literalValue(cond.value, { kind: "bool" }));
1169
+ }
1170
+ /** 選択肢の見た目の引数を値にする。 */
1171
+ look(args, unit, line, context) {
1172
+ const values = this.resolveArgs(CHOICE_OPTION, args.filter((a) => !NOT_LOOK.has(a.key)), { file: unit.file, context });
1173
+ const look = {};
1174
+ if (this.optionFlag(args, "locked", false, unit, line))
1175
+ look.locked = true;
1176
+ for (const key of ["image", "hover", "cursor", "tip"])
1177
+ if (typeof values[key] === "string")
1178
+ look[key] = values[key];
1179
+ for (const key of ["x", "y", "width", "height"])
1180
+ if (typeof values[key] === "number")
1181
+ look[key] = values[key];
1182
+ return look;
1183
+ }
1184
+ // ---- 命令 ----
1185
+ async command(name, args, unit, line, body, content) {
1186
+ const define = this.findDefine(name, unit.file);
1187
+ if (define) {
1188
+ // 作品の既定値(commandDefaults)はマクロにも効く
1189
+ const values = this.resolveArgs(applyCommandDefaults(defineSpec(name, define), this.commandDefaults), args);
1190
+ // 戻り値(@return (式))を入れる変数(型 variable のパラメータ)と、@with で渡した中身
1191
+ const resultParam = define.params?.find((p) => p.type === "variable")?.name;
1192
+ const result = resultParam !== undefined && typeof values[resultParam] === "string" ? values[resultParam] : undefined;
1193
+ this.state.callStack.push({ return: { ...this.state.position }, locals: this.state.locals, ...(result ? { result } : {}), ...(content ? { content } : {}) });
1194
+ // 引数名の - は、中の式では _ で参照する(face-name → face_name)。
1195
+ this.state.locals = Object.fromEntries(Object.entries(values).map(([k, v]) => [paramLocalName(k), v]));
1196
+ this.state.position = { unit: define.id, index: 0 };
1197
+ return;
1198
+ }
1199
+ const impl = this.implementations.get(name);
1200
+ if (content !== undefined) {
1201
+ this.diagnostic("warning", "unsupported-command", `@with で呼べるのは @define のマクロだけです(@${name} はマクロではないため、中身ごとスキップしました)`, unit, line);
1202
+ return;
1203
+ }
1204
+ if (!impl) {
1205
+ this.diagnostic("warning", "unsupported-command", `@${name} はこの環境では実装されていないため、スキップしました`, unit, line);
1206
+ return;
1207
+ }
1208
+ const context = contextAt(unit.labels, this.state.position.index - 1);
1209
+ const values = this.resolveArgs(impl.spec, args, { file: unit.file, context });
1210
+ const sources = exprSources(impl.spec, args);
1211
+ // プレイを終える命令のエンディングを、見た結末として全セーブ共通に残す(式の endings() と、見た数で進める実績)
1212
+ const achieved = impl.spec.ends ? this.noteEnding(values, unit.file, context) : [];
1213
+ this.unlockCg(impl.spec, values);
1214
+ const skip = effectSkip(impl.spec, values);
1215
+ const at = { unit: unit.id, index: this.state.position.index - 1 };
1216
+ const previous = this.resumeAt;
1217
+ const previousState = this.resumeState;
1218
+ const ctx = {
1219
+ runtime: this,
1220
+ state: this.state,
1221
+ ...(body !== undefined ? { body } : {}),
1222
+ sources,
1223
+ signal: this.abort.signal,
1224
+ // 演出の命令は、描画側にクリックで早送りできるか(skip=false なら早送りしない)を添える。
1225
+ // 自動確認では、autoplay を持つ命令は描かせずに(画面なしの記録には残す)、その答えで進める
1226
+ present: async (presented, wait) => {
1227
+ // 送ったページのあとの最初の命令に印を付ける(描画側がそこで前のページの本文を消す)
1228
+ const afterPage = this.pageRead;
1229
+ this.pageRead = false;
1230
+ const event = { type: "command", name, args: presented, wait, stage: this.state.stage, ...(skip !== undefined ? { skip } : {}), ...(afterPage ? { afterPage } : {}) };
1231
+ if (!impl.autoplay)
1232
+ return this.host.present(event, this.abort.signal);
1233
+ // 自動確認でなければ、操作待ちの画面(か動画)として描かせる(lim shot が撮る所の目印にする)
1234
+ if (this.host.automated !== true)
1235
+ return this.host.present({ ...event, interactive: true }, this.abort.signal);
1236
+ await this.host.present({ ...event, autoplay: true }, this.abort.signal);
1237
+ return impl.autoplay(presented, ctx);
1238
+ },
1239
+ // 本文中の命令なら、すでにそのページから再開する位置になっている。
1240
+ // UI を出して待つ命令は、待つ間に描画側が書いた進み具合(stage.extra)をセーブに残したいので、
1241
+ // 状態は控えず、セーブの時点のものを使う(ページの途中なら、ページの頭の状態から流し直す)。
1242
+ resumeHere: () => {
1243
+ if (!previous)
1244
+ this.resumeAt = at;
1245
+ },
1246
+ choose: (options, targets) => this.host.choose(options, this.abort.signal, undefined, targets),
1247
+ unlockCg: (image) => {
1248
+ if (typeof image === "string" && image !== "")
1249
+ (this.system.cg_unlocked ??= {})[image] = true;
1250
+ },
1251
+ pick: async (outcomes, answer) => {
1252
+ if (answer !== undefined && answer !== null)
1253
+ return answer;
1254
+ if (outcomes.length === 0)
1255
+ return null;
1256
+ const picked = await ctx.choose(outcomes.map((o) => o.label), outcomes.map((o) => o.target));
1257
+ return picked === null ? null : (outcomes[picked] ?? outcomes[0]).value;
1258
+ },
1259
+ data: (name) => this.loadData(name),
1260
+ atSceneBreak: (presented) => {
1261
+ const wait = (this.state.stage.sceneWait ??= { commands: [] });
1262
+ wait.commands.push({ name, args: structuredClone(presented) });
1263
+ },
1264
+ };
1265
+ // 場面の切れ目(待たせている通知を出す時機)。場面転換、暗転、別の絵への @bg は始める前に印を付け(演出の途中のセーブにも入る)、
1266
+ // ほかの命令(プラグインの命令など)が背景を替えたときは終わってから付ける(取っておいた状態へ戻す命令は、戻した状態のまま)
1267
+ const stage = this.state.stage;
1268
+ const background = stage.background;
1269
+ if (name === "scene-change" || name === "mask" || (name === "bg" && typeof values.image === "string" && values.image !== background))
1270
+ this.sceneBreak();
1271
+ // 見た数で進めた実績は、命令の前に描画側へ知らせる(@achieve-progress と同じ形。タイトルへ戻る前に通知を出す)
1272
+ for (const a of achieved)
1273
+ await this.host.present({ type: "command", name: "achieve-progress", args: a, wait: false, stage: this.state.stage }, this.abort.signal);
1274
+ try {
1275
+ await impl.run(values, ctx);
1276
+ }
1277
+ finally {
1278
+ this.resumeAt = previous;
1279
+ this.resumeState = previousState;
1280
+ if (this.state.stage === stage && stage.background !== background)
1281
+ this.sceneBreak();
1282
+ }
1283
+ }
1284
+ /** 場面の切れ目を過ぎた。それまでに待たせていた命令を、次の本文か選択肢の前に出すようにする。 */
1285
+ sceneBreak() {
1286
+ const wait = this.state.stage.sceneWait;
1287
+ if (wait && wait.commands.length > 0)
1288
+ wait.due = wait.commands.length;
1289
+ }
1290
+ /** 場面の切れ目を過ぎた待たせている命令を、描画側へ渡して外す(本文と選択肢の前。その位置のセーブには入れない)。 */
1291
+ async flushSceneWait() {
1292
+ const wait = this.state.stage.sceneWait;
1293
+ if (!wait?.due)
1294
+ return;
1295
+ const due = wait.commands.splice(0, wait.due);
1296
+ if (wait.commands.length > 0)
1297
+ delete wait.due;
1298
+ else
1299
+ delete this.state.stage.sceneWait;
1300
+ for (const c of due)
1301
+ await this.host.present({ type: "command", name: c.name, args: c.args, wait: false, stage: this.state.stage }, this.abort.signal);
1302
+ }
1303
+ /** CG として解放する印のあるパラメータで出した画像が CG なら解放する(folder= があればそのフォルダで見る)。 */
1304
+ unlockCg(spec, values) {
1305
+ if (!this.isCg)
1306
+ return;
1307
+ for (const [name, p] of Object.entries(spec.params)) {
1308
+ if (p.type.kind !== "asset" || !p.type.cg)
1309
+ continue;
1310
+ const image = values[name];
1311
+ const folder = typeof values.folder === "string" ? values.folder : p.type.folder;
1312
+ if (typeof image !== "string" || image === "" || !this.isCg(folder, image))
1313
+ continue;
1314
+ (this.system.cg_unlocked ??= {})[image] = true;
1315
+ }
1316
+ }
1317
+ /**
1318
+ * 命令が作品のデータから出した画像を CG として解放する(liminalia.json の extra.cg か extra.cgAuto の画像なら。@bg で出したときと同じ)。
1319
+ * 解放したら true。データの形の宣言でその欄に CG の印(d.asset(…, { cg: true }))を付けておくと、どこからも出ない CG の検査が数える。
1320
+ */
1321
+ unlockCgImage(folder, image) {
1322
+ if (!this.isCg || image === "" || !this.isCg(folder, image))
1323
+ return false;
1324
+ (this.system.cg_unlocked ??= {})[image] = true;
1325
+ return true;
1326
+ }
1327
+ /** 再開する位置と、その時点の状態を控える(null で外す)。 */
1328
+ holdResume(at) {
1329
+ this.resumeAt = at;
1330
+ this.resumeState = at ? toSaveData(this.state) : null;
1331
+ }
1332
+ /**
1333
+ * 引数を仕様の型に合わせた値にし、既定値を補う。at(書いたファイルと場面)を渡せば、訳す印(translate: "text")のある文字の引数を
1334
+ * 遊んでいる言語の訳に替える(訳が無ければそのまま)。
1335
+ */
1336
+ resolveArgs(spec, args, at) {
1337
+ const conflict = booleanShorthandConflicts(spec, args, this.cast)[0];
1338
+ if (conflict)
1339
+ throw new EvalError(`${conflict.name} は真偽値と ${conflict.positional} の両方に読めます。真偽値には ${conflict.name}=true と書いてください`);
1340
+ const out = {};
1341
+ let position = 0;
1342
+ for (const a of normalizeBooleanArgs(spec, args)) {
1343
+ const name = a.key ?? spec.positional[position++];
1344
+ if (name === undefined)
1345
+ continue;
1346
+ const type = spec.params[name]?.type ?? { kind: "string" };
1347
+ out[name] = a.value.kind === "expr" ? this.eval(a.value.expr) : literalValue(a.value, type);
1348
+ if (spec.ends && name === "ending") {
1349
+ // ending=true は真偽の字面でなく、エンディングの種類の true
1350
+ if (out[name] === true)
1351
+ out[name] = "true";
1352
+ // 前の書き方の文言(BAD END、通り雨など。種類でないもの)は、移すまでコマンドの文字として訳す
1353
+ const value = out[name];
1354
+ if (at && a.value.kind === "string" && typeof value === "string" && value.trim() !== "" && !this.endingKinds.names.has(value.trim())) {
1355
+ noteArgOrigin(out, name, { kind: "arg", file: at.file, source: value, ...(at.context ? { context: at.context } : {}) });
1356
+ const translated = this.translator?.arg?.(at.file, value, at.context);
1357
+ if (translated)
1358
+ out[name] = translated;
1359
+ }
1360
+ continue;
1361
+ }
1362
+ if (at && type.kind === "string" && type.translate === "text" && typeof out[name] === "string" && out[name] !== "") {
1363
+ // 字面で書いた文字は、置いたままの文字を言語を替えたときに出し直せるよう、元を控える(argOrigin)
1364
+ if (a.value.kind === "string")
1365
+ noteArgOrigin(out, name, { kind: "arg", file: at.file, source: out[name], ...(at.context ? { context: at.context } : {}) });
1366
+ const translated = this.translator?.arg?.(at.file, out[name], at.context);
1367
+ if (translated)
1368
+ out[name] = translated;
1369
+ }
1370
+ }
1371
+ for (const [name, p] of Object.entries(spec.params)) {
1372
+ // 旧名の作品既定値より、この行に明示した新しい名前を優先する。
1373
+ if (spec.name === "scene-change" && name === "hide-at" && args.some((a) => a.key === "hide-chara-at") && !args.some((a) => a.key === "hide-at"))
1374
+ continue;
1375
+ if (!(name in out) && p.default !== undefined)
1376
+ out[name] = literalValue(parseLiteral(p.default), p.type);
1377
+ }
1378
+ return out;
1379
+ }
1380
+ /** そのファイルと、そのファイルが @use したファイルの @define を探す。 */
1381
+ findDefine(name, file) {
1382
+ const program = this.programs.get(file);
1383
+ const own = program?.defines.get(name);
1384
+ if (own)
1385
+ return own;
1386
+ for (const used of program?.uses ?? []) {
1387
+ const d = this.programs.get(used)?.defines.get(name);
1388
+ if (d)
1389
+ return d;
1390
+ }
1391
+ return undefined;
1392
+ }
1393
+ // ---- 移動 ----
1394
+ /** @jump と選択肢の移動。ほかのファイル(章)へ移ったら場面の切れ目にする(@call と @return は切れ目にしない)。 */
1395
+ async moveTo(target, currentFile, line) {
1396
+ await this.goto(target, currentFile, line);
1397
+ if (fileOf(this.state.position.unit) !== currentFile)
1398
+ this.sceneBreak();
1399
+ }
1400
+ async goto(target, currentFile, line = 0) {
1401
+ if (target.expr) {
1402
+ // 飛び先を実行時に決める式。値は `#ラベル`・`ファイル`・`ファイル#ラベル` の文字列
1403
+ const value = this.eval(target.expr);
1404
+ const resolved = typeof value === "string" ? parseTargetText(value.trim()) : null;
1405
+ if (!resolved) {
1406
+ const unit = await this.unit(this.state.position.unit);
1407
+ this.fail(`ジャンプ先の式の値 ${JSON.stringify(value)} は \`#ラベル\`、\`ファイル\`、\`ファイル#ラベル\` のどの形でもありません`, unit, line);
1408
+ return;
1409
+ }
1410
+ // to= の候補を書いたなら、その中のどれかでなければならない(検査と分岐の地図は候補だけを見ている)
1411
+ if (target.candidates && !target.candidates.includes(String(value).trim())) {
1412
+ const unit = await this.unit(this.state.position.unit);
1413
+ this.fail(`ジャンプ先の式の値 ${JSON.stringify(value)} は候補(to=${target.candidates.join(",")})にありません`, unit, line);
1414
+ return;
1415
+ }
1416
+ return this.goto(resolved, currentFile, line);
1417
+ }
1418
+ const file = target.file ?? currentFile;
1419
+ const program = await this.program(file);
1420
+ if (file !== fileOf(this.state.position.unit))
1421
+ this.state.locals = {};
1422
+ if (target.label === null) {
1423
+ this.state.position = { unit: program.main.id, index: 0 };
1424
+ this.visited(file);
1425
+ return;
1426
+ }
1427
+ const index = program.main.labels[target.label];
1428
+ if (program.main.nestedLabels?.has(target.label)) {
1429
+ this.fail(`ラベル #${target.label} は @if の中にあるため、ジャンプできません`, program.main, line);
1430
+ return;
1431
+ }
1432
+ if (index === undefined) {
1433
+ // @define・@with の中のラベルは別の実行単位にある(場面の名前に使う)ので、そこへは飛べない
1434
+ const inner = [...program.defines.entries()].find(([, u]) => target.label in u.labels);
1435
+ // 知らせる場所は、ジャンプした行(ジャンプ先のファイルの頭ではなく)
1436
+ this.fail(inner
1437
+ ? `ラベル #${target.label} は ${inner[0].startsWith("@with:") ? "@with" : `@define ${inner[0]}`} の中にあるため、ジャンプできません`
1438
+ : `ラベル #${target.label} が ${file} にありません`, await this.unit(this.state.position.unit), line);
1439
+ return;
1440
+ }
1441
+ this.state.position = { unit: program.main.id, index };
1442
+ }
1443
+ /**
1444
+ * ファイルを読んで実行できる形にする(一度読んだものは持っておく)。quiet(先読み)なら、見つけた誤りはまだ知らせず、
1445
+ * そのファイルを本当に使うときに知らせる(通らない分岐の先の誤りを、遊んでいる途中に出さないため)。
1446
+ */
1447
+ async program(file, quiet = false) {
1448
+ let program = this.programs.get(file);
1449
+ if (!program) {
1450
+ // 先読みと本当の読み込みが重なっても、読むのは一度
1451
+ let loading = this.loadingPrograms.get(file);
1452
+ if (!loading) {
1453
+ loading = this.readProgram(file).finally(() => this.loadingPrograms.delete(file));
1454
+ this.loadingPrograms.set(file, loading);
1455
+ }
1456
+ program = await loading;
1457
+ }
1458
+ if (!quiet)
1459
+ this.flushDiagnostics(file);
1460
+ return program;
1461
+ }
1462
+ /** 読み込み中のファイル(先読みと重なったとき、同じ読み込みを待つ)。 */
1463
+ loadingPrograms = new Map();
1464
+ /** 読んだが、まだ知らせていない誤り(ファイル → 診断)。使ったときに知らせる。 */
1465
+ pendingDiagnostics = new Map();
1466
+ async readProgram(file) {
1467
+ const source = await this.host.loadSource(file);
1468
+ const speakersKey = this.speakers.join("\n");
1469
+ const cached = this.options.programCache?.get(file);
1470
+ const hit = cached && cached.source === source && cached.speakers === speakersKey ? cached : null;
1471
+ const script = hit ? hit.script : parse(source, file, { speakers: this.speakers });
1472
+ // 約物の検査、書き方の提案(立ち絵のちらつき、既定値と同じパラメータなど)、前の名前の fade= は、実行の結果を変えない書き方の点検
1473
+ // (lim check と制作画面が作品の設定と原文の言語で見る)なので、動かすときには知らせない(runtimeDiagnostic。@liminalia/lang の RUNTIME_QUIET の表)
1474
+ // @use したファイルのマクロ(unknown-command)と関数(unknown-function)は、このファイルだけでは分からないので知らせない(呼んだときに分かる)
1475
+ // @script(作品の allowScript を知らない。中身を実行しないことは、通ったときに script-skipped で知らせる)も知らせない
1476
+ // 書き出したゲームでは検査しない(__LIMINALIA_EXPORT__)
1477
+ const found = [
1478
+ ...script.diagnostics.filter(runtimeDiagnostic),
1479
+ ...(typeof __LIMINALIA_EXPORT__ !== "undefined" && __LIMINALIA_EXPORT__ ? [] : check(script, { registry: this.registry, punctuation: false }).filter((d) => !RUN_TIME_KNOWN.has(d.code) && runtimeDiagnostic(d))),
1480
+ ];
1481
+ const program = hit ? hit.program : buildProgram(script);
1482
+ if (!hit)
1483
+ this.options.programCache?.set(file, { source, speakers: speakersKey, program, script });
1484
+ this.programs.set(file, program);
1485
+ if (found.length > 0)
1486
+ this.pendingDiagnostics.set(file, found);
1487
+ // @use したファイルも読んでおく(そこにある @define を呼ぶため)。互いに @use していても一度だけ読む。
1488
+ for (const used of program.uses)
1489
+ await this.program(used, true);
1490
+ return program;
1491
+ }
1492
+ /** まだ知らせていない、そのファイルと @use したファイルの誤りを知らせる。 */
1493
+ flushDiagnostics(file, seen = new Set()) {
1494
+ if (seen.has(file))
1495
+ return;
1496
+ seen.add(file);
1497
+ const found = this.pendingDiagnostics.get(file);
1498
+ if (found) {
1499
+ this.pendingDiagnostics.delete(file);
1500
+ for (const d of found)
1501
+ this.host.onDiagnostic?.(d);
1502
+ }
1503
+ for (const used of this.programs.get(file)?.uses ?? [])
1504
+ this.flushDiagnostics(used, seen);
1505
+ }
1506
+ /** 先読みした飛び先(`ファイル#ラベル`)。同じところは二度読まない。 */
1507
+ prefetched = new Set();
1508
+ /**
1509
+ * この先(collectPrefetch と同じ範囲)の @jump・@call・選択肢の飛び先を先読みする。別のファイルならそのファイルを読んでおき、
1510
+ * 飛び先の頭から使う素材を描画側に渡す(同じファイルでも、見ている範囲の外のラベルなら素材を渡す)。式の飛び先は読まない。
1511
+ * 一ページに読むのは新しい飛び先 MAX_TARGET_PREFETCH 個まで。読めなくても黙る(本当に飛んだときに知らせる)。
1512
+ */
1513
+ prefetchTargets(unit, index, limit = 40) {
1514
+ if (!this.host.prefetch)
1515
+ return;
1516
+ const targets = [];
1517
+ const end = Math.min(unit.instructions.length, index + limit);
1518
+ for (let i = index; i < end; i++) {
1519
+ const ins = unit.instructions[i];
1520
+ if (ins.op === "jump" || ins.op === "call")
1521
+ targets.push(ins.target);
1522
+ else if (ins.op === "choice")
1523
+ for (const o of ins.options)
1524
+ targets.push(o.target);
1525
+ }
1526
+ let started = 0;
1527
+ for (const t of targets) {
1528
+ if (t.expr || started >= MAX_TARGET_PREFETCH)
1529
+ continue;
1530
+ const file = t.file ?? unit.file;
1531
+ const key = `${file}#${t.label ?? ""}`;
1532
+ if (this.prefetched.has(key))
1533
+ continue;
1534
+ if (file === unit.file) {
1535
+ // 同じファイルのラベルは、見ている範囲の中なら collectPrefetch が拾っている
1536
+ const at = t.label === null ? 0 : unit.labels[t.label];
1537
+ if (unit.id !== fileOf(unit.id) || at === undefined || (at >= index && at < end))
1538
+ continue;
1539
+ }
1540
+ this.prefetched.add(key);
1541
+ started++;
1542
+ const signal = this.abort.signal;
1543
+ void this.program(file, true).then((program) => {
1544
+ if (signal.aborted)
1545
+ return;
1546
+ const at = t.label === null ? 0 : program.main.labels[t.label];
1547
+ if (at !== undefined)
1548
+ this.host.prefetch?.(collectPrefetch(program.main, at, this.registry, TARGET_PREFETCH_LIMIT));
1549
+ }, () => undefined);
1550
+ }
1551
+ }
1552
+ async unit(id) {
1553
+ const program = await this.program(fileOf(id));
1554
+ if (id === program.main.id)
1555
+ return program.main;
1556
+ const unit = program.defines.get(id.slice(id.indexOf("::") + 2));
1557
+ if (!unit)
1558
+ throw new Error(`実行単位 ${id} がありません`);
1559
+ return unit;
1560
+ }
1561
+ // ---- 変数 ----
1562
+ env = {
1563
+ lookup: (name) => {
1564
+ if (name === "game")
1565
+ return this.state.game;
1566
+ if (name === "system")
1567
+ return this.system;
1568
+ if (name === "temp")
1569
+ return this.state.temp;
1570
+ if (Object.hasOwn(this.state.locals, name))
1571
+ return this.state.locals[name] ?? null;
1572
+ // セーブの様子(読むだけ)。version はロードしたセーブを作った作品の版(新しく始めたプレイは今の版、版を入れる前のセーブは空)
1573
+ if (name === "save")
1574
+ return { version: this.state.gameVersion ?? "" };
1575
+ return null;
1576
+ },
1577
+ random: () => {
1578
+ const { value, seed } = nextRandom(this.state.seed);
1579
+ this.state.seed = seed;
1580
+ return value;
1581
+ },
1582
+ story: (name, args) => this.story(name, args),
1583
+ fn: (name, file) => this.findFunction(name, file ?? this.currentUnit?.file ?? fileOf(this.state.position.unit)),
1584
+ };
1585
+ /** そのファイルと、そのファイルが @use したファイルの @function を探す。 */
1586
+ findFunction(name, file) {
1587
+ const program = this.programs.get(file);
1588
+ const own = program?.functions.get(name);
1589
+ if (own)
1590
+ return own;
1591
+ for (const used of program?.uses ?? []) {
1592
+ const f = this.programs.get(used)?.functions.get(name);
1593
+ if (f)
1594
+ return f;
1595
+ }
1596
+ return undefined;
1597
+ }
1598
+ // ---- 進み具合と遊んでいる環境(式の visits・read・chosen・lang・platform・app・replaying) ----
1599
+ /** 式の lang() が返す、遊んでいる言語。描画側が入れる(言語を替えたら入れ直す)。 */
1600
+ language;
1601
+ /** 式の platform()・app() が返す、遊んでいる機種。描画側が入れる。 */
1602
+ platform;
1603
+ /** 再生しているおまけの回想の id(start の replay)。回想でなければ null。 */
1604
+ replay = null;
1605
+ /** 章の情報(options.chapters)。 */
1606
+ chapters;
1607
+ /** 数を数える実績の目標(options.achievementGoals)。 */
1608
+ achievementGoals;
1609
+ /**
1610
+ * 今のシナリオファイル(実行中の命令のファイル。始める前は再開する位置のファイル)の章(liminalia.json の chapters)。無ければ null。
1611
+ * 章の扉や章の終わりのプラグインのコマンドは、ここから番号と題を読む。
1612
+ */
1613
+ get chapter() {
1614
+ return chapterOf(this.chapters, this.currentUnit?.file ?? fileOf(this.state.position.unit));
1615
+ }
1616
+ story(name, args) {
1617
+ switch (name) {
1618
+ case "visits":
1619
+ return this.state.visits?.[this.progressKey(args[0] ?? null)] ?? 0;
1620
+ case "read":
1621
+ return countOf(this.system[READ_KEY], this.progressKey(args[0] ?? null)) > 0;
1622
+ case "chosen":
1623
+ return (this.state.chosen?.[String(args[0])] ?? 0) > 0;
1624
+ case "lang":
1625
+ return this.language;
1626
+ case "platform":
1627
+ return this.platform.device;
1628
+ case "app":
1629
+ return this.platform.app;
1630
+ case "replaying":
1631
+ return this.replay !== null;
1632
+ case "chapter":
1633
+ return this.chapter?.id ?? "";
1634
+ case "endings": {
1635
+ const kind = args[0];
1636
+ if (kind !== undefined && kind !== null && typeof kind !== "string")
1637
+ throw new EvalError(`endings() にはエンディングの種類(bad など)を渡します(${JSON.stringify(kind)})`);
1638
+ return countEndings(this.system[ENDINGS_KEY], typeof kind === "string" && kind !== "" ? kind : undefined);
1639
+ }
1640
+ default:
1641
+ throw new EvalError(`関数 ${name}() はありません`);
1642
+ }
1643
+ }
1644
+ /** visits・read の鍵(`ファイル#ラベル` か `ファイル`)。`#ラベル` は式を書いたファイルのラベル。 */
1645
+ progressKey(value) {
1646
+ const target = typeof value === "string" ? parseTargetText(value.trim()) : null;
1647
+ if (!target || target.expr)
1648
+ throw new EvalError(`ジャンプ先(#ラベル、ファイル、ファイル#ラベル)を渡します(${JSON.stringify(value)})`);
1649
+ const file = target.file ?? this.currentUnit?.file ?? fileOf(this.state.position.unit);
1650
+ return target.label === null ? file : `${file}#${target.label}`;
1651
+ }
1652
+ /** 見たエンディングで進める実績(options.endingAchievements)。 */
1653
+ endingAchievements;
1654
+ /** 使えるエンディングの種類(組み込みと options.endingKinds)。 */
1655
+ endingKinds;
1656
+ /**
1657
+ * プレイを終える命令の ending= と title=(原文。訳す前)を、見た結末として全セーブ共通の ENDINGS_KEY に残す(鍵はシーンと種類と名前)。
1658
+ * 見た数で進める実績の数を合わせ、変わったものを @achieve-progress の形で返す(描画側に知らせる)。回想の間は残さない。
1659
+ */
1660
+ noteEnding(values, file, context) {
1661
+ if (this.replay !== null)
1662
+ return [];
1663
+ const source = (name) => argOrigin(values, name)?.source ?? values[name];
1664
+ const ref = endingRef(source("ending"), source("title"), this.endingKinds);
1665
+ if (!ref)
1666
+ return [];
1667
+ const record = scopeOf(this.system, ENDINGS_KEY);
1668
+ const key = endingRecordKey(context ? `${file}#${context}` : file, ref);
1669
+ if (record[key] === ref.kind)
1670
+ return [];
1671
+ record[key] = ref.kind;
1672
+ this.variablesChanged("system");
1673
+ const out = [];
1674
+ const progress = (this.system.achievement_progress ??= {});
1675
+ const unlocked = (this.system.achievements ??= {});
1676
+ for (const [id, a] of Object.entries(this.endingAchievements)) {
1677
+ const value = countEndings(record, a.endings);
1678
+ const now = typeof progress[id] === "number" ? progress[id] : 0;
1679
+ if (value <= now)
1680
+ continue;
1681
+ progress[id] = value;
1682
+ let reached = false;
1683
+ if (value >= a.goal && !unlocked[id]) {
1684
+ unlocked[id] = new Date().toISOString();
1685
+ reached = true;
1686
+ }
1687
+ out.push({ id, value, goal: a.goal, unlocked: reached });
1688
+ }
1689
+ return out;
1690
+ }
1691
+ /** ラベル(かファイルの頭)に入ったことを数える(このプレイの回数と、全セーブ共通の既読)。 */
1692
+ visited(key) {
1693
+ const visits = (this.state.visits ??= {});
1694
+ visits[key] = (visits[key] ?? 0) + 1;
1695
+ scopeOf(this.system, READ_KEY)[key] = true;
1696
+ this.variablesChanged("visits");
1697
+ }
1698
+ /** 選んだ選択肢の文(原文の飾りを外したもの)を覚える。 */
1699
+ noteChosen(option) {
1700
+ const chosen = (this.state.chosen ??= {});
1701
+ const text = plainText(option.content);
1702
+ chosen[text] = (chosen[text] ?? 0) + 1;
1703
+ this.variablesChanged("chosen");
1704
+ }
1705
+ eval(expr) {
1706
+ return evaluate(expr, this.env);
1707
+ }
1708
+ assign(target, operator, value) {
1709
+ // 左辺を「入れ物」と「キー」に分ける。途中の入れ物がなければ作る。
1710
+ const path = [];
1711
+ let e = target;
1712
+ while (e.kind === "member" || e.kind === "index") {
1713
+ if (e.kind === "member")
1714
+ path.unshift(e.property);
1715
+ else {
1716
+ const k = this.eval(e.index);
1717
+ if (typeof k !== "string" && typeof k !== "number")
1718
+ throw new EvalError("添字には文字列か数値が必要です");
1719
+ path.unshift(k);
1720
+ }
1721
+ e = e.object;
1722
+ }
1723
+ if (e.kind !== "name")
1724
+ throw new EvalError("@set の左辺が変数ではありません");
1725
+ checkKeys([e.name, ...path]);
1726
+ let container;
1727
+ let key;
1728
+ if (e.name === "game" || e.name === "system" || e.name === "temp") {
1729
+ if (path.length === 0)
1730
+ throw new EvalError(`${e.name} そのものには代入できません(${e.name}.名前 に代入します)`);
1731
+ container = this.env.lookup(e.name);
1732
+ key = path.pop();
1733
+ }
1734
+ else {
1735
+ container = this.state.locals;
1736
+ key = e.name;
1737
+ if (path.length > 0) {
1738
+ path.unshift(key);
1739
+ key = path.pop();
1740
+ }
1741
+ }
1742
+ const name = [e.name === "game" || e.name === "system" || e.name === "temp" ? e.name : null, ...path, key].filter((p) => p !== null).join(".");
1743
+ for (const p of path) {
1744
+ const next = container[p];
1745
+ if (next === null || next === undefined || typeof next !== "object")
1746
+ container[p] = {};
1747
+ container = container[p];
1748
+ }
1749
+ if (operator === "=") {
1750
+ container[key] = value;
1751
+ }
1752
+ else {
1753
+ const current = container[key] ?? null;
1754
+ if (operator === "+=" && (typeof current === "string" || typeof value === "string")) {
1755
+ container[key] = display(current) + display(value);
1756
+ }
1757
+ else {
1758
+ const a = current === null ? 0 : current;
1759
+ if (typeof a !== "number" || typeof value !== "number")
1760
+ throw new EvalError(`${operator} は数値にだけ使えます`);
1761
+ container[key] = operator === "+=" ? a + value : operator === "-=" ? a - value : operator === "*=" ? a * value : checkedDivision(a, value, "/");
1762
+ }
1763
+ }
1764
+ this.assigned(name, container[key]);
1765
+ }
1766
+ assigned(path, value) {
1767
+ if (this.onAssign && this.currentUnit)
1768
+ this.onAssign(path, value, { file: this.currentUnit.file, line: this.currentLine });
1769
+ this.variablesChanged(path);
1770
+ }
1771
+ changeListeners = new Set();
1772
+ /**
1773
+ * 変数が変わったときに呼ぶ(@set・@let・命令の結果の setVariable・持ち物・選んだ選択肢と入った場面の数、variablesChanged で知らせたもの)。
1774
+ * path は game.x・system.x・temp.x(入れ子は game.a.b)か局所変数の名前、持ち物は game.@items、選んだ選択肢は chosen、入った場面は visits、
1775
+ * まとめて消したら game・system・temp。図鑑の見回しのように、変数で決まるものを変わった時点で見直すのに使う。返す関数で外す。
1776
+ */
1777
+ onVariableChange(listener) {
1778
+ this.changeListeners.add(listener);
1779
+ return () => this.changeListeners.delete(listener);
1780
+ }
1781
+ /** 変数を変えたことを知らせる(state.game などを直に書き換えたプラグインが呼ぶ。setVariable は自分で知らせる)。 */
1782
+ variablesChanged(...paths) {
1783
+ for (const path of paths)
1784
+ for (const listener of [...this.changeListeners])
1785
+ listener(path);
1786
+ }
1787
+ // ---- 診断 ----
1788
+ fail(message, unit, line) {
1789
+ this.diagnostic("error", "runtime", message, unit, line);
1790
+ if (this.onError === "stop")
1791
+ this.halt ??= { reason: "error", at: { ...this.state.position }, message };
1792
+ }
1793
+ diagnostic(severity, code, message, unit, line) {
1794
+ this.host.onDiagnostic?.({ severity, code, message, file: unit.file, line });
1795
+ }
1796
+ }
1797
+ /** 命令の目印の鍵(本文はその文、選択肢は選択肢の文を並べたもの)。ほかの命令は無い。 */
1798
+ /** 一ページに先読みする新しい飛び先の数。 */
1799
+ const MAX_TARGET_PREFETCH = 4;
1800
+ /** 読み込んだファイルの検査のうち、実行器には分からない、または実行したときに知らせるもの(readProgram)。 */
1801
+ const RUN_TIME_KNOWN = new Set(["unknown-command", "unknown-function", "script-not-allowed", "script-skipped"]);
1802
+ /** 飛び先の頭から、素材を集める命令の数。 */
1803
+ const TARGET_PREFETCH_LIMIT = 24;
1804
+ /** 呼び出す命令か(@call・命令の名前のマクロ・@with の中身)。マクロかどうかは見ない(どの命令も、呼べば戻り先はその次)。 */
1805
+ function callSite(ins) {
1806
+ return ins.op === "call" || ins.op === "command" || ins.op === "content";
1807
+ }
1808
+ /** 呼び出す命令の鍵(命令の名前と引数、@call の飛び先から作る。行は入れない)。 */
1809
+ function siteKey(ins) {
1810
+ if (ins.op === "call")
1811
+ return translationKey("", "line", `@call ${ins.target.file ?? ""}#${ins.target.label ?? ""}${ins.target.expr ? " (expr)" : ""}`);
1812
+ if (ins.op === "command")
1813
+ return translationKey("", "line", `@${ins.name} ${ins.args.map((a) => `${a.key ?? ""}=${printLiteral(a.value)}`).join(" ")}`);
1814
+ if (ins.op === "content")
1815
+ return translationKey("", "line", "@content");
1816
+ return undefined;
1817
+ }
1818
+ /** その命令が callee(実行単位の id)を呼ぶか(前の版のセーブの戻り先を探すとき)。式の飛び先は呼ぶものとみなす。 */
1819
+ function calls(ins, file, callee) {
1820
+ const calleeFile = fileOf(callee);
1821
+ const define = callee.includes("::") ? callee.slice(callee.indexOf("::") + 2) : null;
1822
+ if (ins.op === "call")
1823
+ return !!ins.target.expr || (define === null && (ins.target.file ?? file) === calleeFile);
1824
+ if (ins.op === "command")
1825
+ return define !== null && ins.name === define;
1826
+ if (ins.op === "choice")
1827
+ return define === null && ins.options.some((o) => (o.target.file ?? file) === calleeFile && o.args.some((a) => a.key === "call"));
1828
+ return false;
1829
+ }
1830
+ function instructionKey(ins) {
1831
+ if (ins.op === "say")
1832
+ return translationKey("", "line", `${ins.speaker ?? ""}${printInline(ins.content)}`);
1833
+ if (ins.op === "choice")
1834
+ return translationKey("", "option", ins.options.map((o) => printInline(o.content)).join("\n"));
1835
+ return undefined;
1836
+ }
1837
+ /**
1838
+ * 命令の演出をクリックで早送りできるか。skip の引数を持つ命令はその値(@movie は既定で false)。持たなくても、時間の引数があって
1839
+ * 終わりを待つ(waits か wait の引数を持つ)命令は、早送りできる演出とみなす(作品の命令の演出)。どちらでもない命令(音、入力を待つ画面など)は undefined。
1840
+ */
1841
+ function effectSkip(spec, values) {
1842
+ if (typeof values.skip === "boolean")
1843
+ return values.skip;
1844
+ const timed = Object.values(spec.params).some((p) => p.type.kind === "duration");
1845
+ return timed && (spec.waits === true || "wait" in spec.params) ? true : undefined;
1846
+ }
1847
+ /** ms だけ実時間で待つ(signal で打ち切ったら解決しない)。 */
1848
+ function realCountdown(ms, signal) {
1849
+ return new Promise((resolve) => {
1850
+ const timer = setTimeout(resolve, ms);
1851
+ signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
1852
+ });
1853
+ }
1854
+ /** 名前 → 数 の入れ物(無い・形の違う値なら作り直す)。 */
1855
+ function scopeOf(root, key) {
1856
+ const v = root[key];
1857
+ if (v && typeof v === "object" && !Array.isArray(v))
1858
+ return v;
1859
+ return (root[key] = {});
1860
+ }
1861
+ /** 入れ物の数(真なら 1、無ければ 0)。 */
1862
+ function countOf(scope, key) {
1863
+ if (!scope || typeof scope !== "object" || Array.isArray(scope) || !Object.hasOwn(scope, key))
1864
+ return 0;
1865
+ const v = scope[key];
1866
+ return typeof v === "number" ? v : v === true ? 1 : 0;
1867
+ }
1868
+ /** 選択肢の行の引数のうち、見た目でないもの(出す条件と、呼び出すか)。 */
1869
+ const NOT_LOOK = new Set(["if", "call", "locked"]);
1870
+ function fileOf(unitId) {
1871
+ const i = unitId.indexOf("::");
1872
+ return i < 0 ? unitId : unitId.slice(0, i);
1873
+ }
1874
+ function literalValue(v, type) {
1875
+ switch (v.kind) {
1876
+ case "string":
1877
+ return v.value;
1878
+ case "number":
1879
+ return v.value;
1880
+ case "duration":
1881
+ return v.ms;
1882
+ case "bool":
1883
+ return v.value;
1884
+ case "color":
1885
+ return v.value;
1886
+ case "expr":
1887
+ throw new Error("式は literalValue に渡さない");
1888
+ }
1889
+ void type;
1890
+ }
1891
+ function defineSpec(name, unit) {
1892
+ // 型は作品の既定値(commandDefaults)の値を確かめるのに使う(値の読み方は書いた字面で決まる)
1893
+ const params = Object.fromEntries((unit.params ?? []).map((p) => {
1894
+ const type = paramTypeFromName(p.type) ?? { kind: "string" };
1895
+ return [p.name, p.defaultValue ? { type, default: printDefault(p.defaultValue), doc: "" } : { type, doc: "" }];
1896
+ }));
1897
+ return { name, summary: "", positional: [], params, example: "" };
1898
+ }
1899
+ function printDefault(v) {
1900
+ switch (v.kind) {
1901
+ case "string":
1902
+ return JSON.stringify(v.value);
1903
+ case "duration":
1904
+ return v.source;
1905
+ case "expr":
1906
+ return v.source;
1907
+ default:
1908
+ return String(v.value);
1909
+ }
1910
+ }
1911
+ export { CORE_COMMANDS };
1912
+ /** 変数の名前とキーの並びに __proto__、constructor、prototype があれば実行時エラーにする(オブジェクトのプロトタイプを書き換えさせない)。 */
1913
+ function checkKeys(keys) {
1914
+ for (const k of keys) {
1915
+ if (typeof k === "string" && FORBIDDEN_PROPERTIES.has(k))
1916
+ throw new EvalError(`${k} は変数の名前やキーに使えません(代入しません)`);
1917
+ }
1918
+ }
1919
+ /** 式で書いた引数の、式の元の文字(引数の名前 → 括弧の中)。 */
1920
+ function exprSources(spec, args) {
1921
+ const out = {};
1922
+ let position = 0;
1923
+ for (const a of normalizeBooleanArgs(spec, args)) {
1924
+ const name = a.key ?? spec.positional[position++];
1925
+ if (name !== undefined && a.value.kind === "expr")
1926
+ out[name] = a.value.source;
1927
+ }
1928
+ return out;
1929
+ }