@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.
- package/LICENSE +106 -0
- package/dist/src/chat.js +60 -0
- package/dist/src/commands-play.js +300 -0
- package/dist/src/commands.js +534 -0
- package/dist/src/coverage.js +208 -0
- package/dist/src/headless.js +109 -0
- package/dist/src/host.js +1 -0
- package/dist/src/index.js +15 -0
- package/dist/src/prefetch.js +80 -0
- package/dist/src/program.js +131 -0
- package/dist/src/project-options.js +84 -0
- package/dist/src/retranslate.js +44 -0
- package/dist/src/route.js +242 -0
- package/dist/src/runtime.js +1929 -0
- package/dist/src/save.js +51 -0
- package/dist/src/scenario-test.js +200 -0
- package/dist/src/state.js +62 -0
- package/dist/src/value.js +464 -0
- package/dist/src/voice-observe.js +82 -0
- package/package.json +33 -4
- package/src/chat.ts +109 -0
- package/src/commands-play.ts +280 -0
- package/src/commands.ts +457 -0
- package/src/coverage.ts +257 -0
- package/src/headless.ts +139 -0
- package/src/host.ts +116 -0
- package/src/index.ts +16 -0
- package/src/prefetch.ts +78 -0
- package/src/program.ts +186 -0
- package/src/project-options.ts +128 -0
- package/src/retranslate.ts +67 -0
- package/src/route.ts +365 -0
- package/src/runtime.ts +2143 -0
- package/src/save.ts +60 -0
- package/src/scenario-test.ts +218 -0
- package/src/state.ts +353 -0
- package/src/value.ts +443 -0
- package/src/voice-observe.ts +85 -0
- package/types/src/chat.d.ts +63 -0
- package/types/src/commands-play.d.ts +2 -0
- package/types/src/commands.d.ts +2 -0
- package/types/src/coverage.d.ts +100 -0
- package/types/src/headless.d.ts +77 -0
- package/types/src/host.d.ts +140 -0
- package/types/src/index.d.ts +16 -0
- package/types/src/prefetch.d.ts +18 -0
- package/types/src/program.d.ts +107 -0
- package/types/src/project-options.d.ts +103 -0
- package/types/src/retranslate.d.ts +39 -0
- package/types/src/route.d.ts +181 -0
- package/types/src/runtime.d.ts +553 -0
- package/types/src/save.d.ts +21 -0
- package/types/src/scenario-test.d.ts +43 -0
- package/types/src/state.d.ts +357 -0
- package/types/src/value.d.ts +61 -0
- package/types/src/voice-observe.d.ts +26 -0
- package/README.md +0 -3
package/src/value.ts
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import { arityText, FORBIDDEN_PROPERTIES, FUNCTION_ARITY, functionArity, type BinaryOp, type Expr } from "@liminalia/lang";
|
|
2
|
+
|
|
3
|
+
/** 実行時の値。セーブデータにそのまま入る(JSON にできるものだけ)。 */
|
|
4
|
+
export type Value = null | boolean | number | string | Value[] | { [key: string]: Value };
|
|
5
|
+
export type Scope = Record<string, Value>;
|
|
6
|
+
|
|
7
|
+
export class EvalError extends Error {}
|
|
8
|
+
|
|
9
|
+
export interface EvalEnv {
|
|
10
|
+
/** game / system / temp と局所変数。 */
|
|
11
|
+
lookup(name: string): Value;
|
|
12
|
+
random(): number;
|
|
13
|
+
/**
|
|
14
|
+
* 実行器が答える関数(@liminalia/lang の STORY_FUNCTIONS: visits・read・chosen・lang・platform・app・replaying・chapter・endings)。
|
|
15
|
+
* 引数の数と型は確かめてから渡す。無ければ、まだ何も無いときの値(0・false・""・"pc")。
|
|
16
|
+
*/
|
|
17
|
+
story?(name: string, args: Value[]): Value;
|
|
18
|
+
/**
|
|
19
|
+
* @function で作った式の関数を探す(無ければ undefined)。file を渡せばそのファイルから(関数の中から呼ぶ関数は、書いたファイルから探す)。
|
|
20
|
+
* 組み込みの関数と同じ名前は呼ばない(検査がエラーにする)。
|
|
21
|
+
*/
|
|
22
|
+
fn?(name: string, file?: string): { file: string; params: readonly string[]; body: Expr } | undefined;
|
|
23
|
+
/** @function の呼び出しの深さ(実行器は書かない。中で数える)。 */
|
|
24
|
+
depth?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @function の呼び出しの深さの上限(自分を呼ぶ関数が終わらないとき)。 */
|
|
28
|
+
export const MAX_FUNCTION_DEPTH = 200;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 式を評価する。暗黙の型変換はしない。例外は + の文字列連結(片方が文字列なら文字列にする)だけ。
|
|
32
|
+
* 未設定の変数や存在しないメンバーは null になる。__proto__、constructor、prototype のメンバーと添字も null
|
|
33
|
+
* (オブジェクトのプロトタイプを読ませない。代入は実行器がエラーにする)。
|
|
34
|
+
*/
|
|
35
|
+
export function evaluate(expr: Expr, env: EvalEnv): Value {
|
|
36
|
+
switch (expr.kind) {
|
|
37
|
+
case "literal":
|
|
38
|
+
return expr.value;
|
|
39
|
+
case "array":
|
|
40
|
+
return expr.items.map((e) => evaluate(e, env));
|
|
41
|
+
case "object": {
|
|
42
|
+
const o: { [key: string]: Value } = {};
|
|
43
|
+
// __proto__ などのキーは検査がエラーにする。ここでも入れない(プロトタイプを書き換えさせない)
|
|
44
|
+
for (const e of expr.entries) if (!FORBIDDEN_PROPERTIES.has(e.key)) o[e.key] = evaluate(e.value, env);
|
|
45
|
+
return o;
|
|
46
|
+
}
|
|
47
|
+
case "name":
|
|
48
|
+
return env.lookup(expr.name);
|
|
49
|
+
case "member": {
|
|
50
|
+
const o = evaluate(expr.object, env);
|
|
51
|
+
if (FORBIDDEN_PROPERTIES.has(expr.property)) return null;
|
|
52
|
+
if (o !== null && typeof o === "object" && !Array.isArray(o)) return own(o, expr.property);
|
|
53
|
+
if (Array.isArray(o) && expr.property === "length") return o.length;
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
case "index": {
|
|
57
|
+
const o = evaluate(expr.object, env);
|
|
58
|
+
const k = evaluate(expr.index, env);
|
|
59
|
+
if (Array.isArray(o) && typeof k === "number") return o[k] ?? null;
|
|
60
|
+
if (o !== null && typeof o === "object" && !Array.isArray(o) && typeof k === "string") return FORBIDDEN_PROPERTIES.has(k) ? null : own(o, k);
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
case "call":
|
|
64
|
+
return call(expr.callee, expr.args.map((a) => evaluate(a, env)), env);
|
|
65
|
+
case "unary": {
|
|
66
|
+
const v = evaluate(expr.operand, env);
|
|
67
|
+
if (expr.op === "!") return !truthy(v);
|
|
68
|
+
if (typeof v !== "number") throw new EvalError(`- は数値にだけ使えます(${describe(v)})`);
|
|
69
|
+
return -v;
|
|
70
|
+
}
|
|
71
|
+
case "binary":
|
|
72
|
+
return binary(expr.op, expr.left, expr.right, env);
|
|
73
|
+
case "conditional":
|
|
74
|
+
return truthy(evaluate(expr.test, env)) ? evaluate(expr.then, env) : evaluate(expr.otherwise, env);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** オブジェクトが自分で持つ値(継承したもの(toString など)は読まない)。無ければ null。 */
|
|
79
|
+
function own(o: { [key: string]: Value }, key: string): Value {
|
|
80
|
+
return Object.hasOwn(o, key) ? (o[key] ?? null) : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 偽になるのは false・null・0・"" だけ。 */
|
|
84
|
+
export function truthy(v: Value): boolean {
|
|
85
|
+
return !(v === false || v === null || v === 0 || v === "");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function equals(a: Value, b: Value): boolean {
|
|
89
|
+
if (a === b) return true;
|
|
90
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
91
|
+
if (a.length !== b.length) return false;
|
|
92
|
+
for (let i = 0; i < a.length; i++) {
|
|
93
|
+
if (!equals(a[i] ?? null, b[i] ?? null)) return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
if (a && b && typeof a === "object" && typeof b === "object" && !Array.isArray(a) && !Array.isArray(b)) {
|
|
98
|
+
const ka = Object.keys(a);
|
|
99
|
+
return ka.length === Object.keys(b).length && ka.every((k) => k in b && equals(a[k]!, b[k]!));
|
|
100
|
+
}
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function display(v: Value): string {
|
|
105
|
+
if (v === null) return "";
|
|
106
|
+
if (typeof v === "string") return v;
|
|
107
|
+
if (typeof v === "number" || typeof v === "boolean") return String(v);
|
|
108
|
+
return JSON.stringify(v);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function checkedDivision(a: number, b: number, op: "/" | "%"): number {
|
|
112
|
+
if (b === 0) throw new EvalError(`0 で${op === "/" ? "割る" : "割った余りを求める"}ことはできません(${describe(a)} ${op} 0)`);
|
|
113
|
+
return op === "/" ? a / b : a % b;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function binary(op: BinaryOp, l: Expr, r: Expr, env: EvalEnv): Value {
|
|
117
|
+
if (op === "&&") {
|
|
118
|
+
const a = evaluate(l, env);
|
|
119
|
+
return truthy(a) ? evaluate(r, env) : a;
|
|
120
|
+
}
|
|
121
|
+
if (op === "||") {
|
|
122
|
+
const a = evaluate(l, env);
|
|
123
|
+
return truthy(a) ? a : evaluate(r, env);
|
|
124
|
+
}
|
|
125
|
+
const a = evaluate(l, env);
|
|
126
|
+
const b = evaluate(r, env);
|
|
127
|
+
switch (op) {
|
|
128
|
+
case "==":
|
|
129
|
+
return equals(a, b);
|
|
130
|
+
case "!=":
|
|
131
|
+
return !equals(a, b);
|
|
132
|
+
case "+":
|
|
133
|
+
if (typeof a === "number" && typeof b === "number") return a + b;
|
|
134
|
+
if (typeof a === "string" || typeof b === "string") return display(a) + display(b);
|
|
135
|
+
throw new EvalError(`+ は数値どうしか文字列にだけ使えます(${describe(a)} + ${describe(b)})`);
|
|
136
|
+
case "-":
|
|
137
|
+
case "*":
|
|
138
|
+
case "/":
|
|
139
|
+
case "%": {
|
|
140
|
+
if (typeof a !== "number" || typeof b !== "number") throw new EvalError(`${op} は数値にだけ使えます(${describe(a)} ${op} ${describe(b)})`);
|
|
141
|
+
if (op === "-") return a - b;
|
|
142
|
+
if (op === "*") return a * b;
|
|
143
|
+
return checkedDivision(a, b, op);
|
|
144
|
+
}
|
|
145
|
+
case "<":
|
|
146
|
+
case "<=":
|
|
147
|
+
case ">":
|
|
148
|
+
case ">=": {
|
|
149
|
+
if (!((typeof a === "number" && typeof b === "number") || (typeof a === "string" && typeof b === "string"))) {
|
|
150
|
+
throw new EvalError(`${op} は同じ型の数値か文字列にだけ使えます(${describe(a)} ${op} ${describe(b)})`);
|
|
151
|
+
}
|
|
152
|
+
if (op === "<") return a < b;
|
|
153
|
+
if (op === "<=") return a <= b;
|
|
154
|
+
if (op === ">") return a > b;
|
|
155
|
+
return a >= b;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
type PluginFunctionImpl = (args: Value[], env: { random(): number }) => Value;
|
|
161
|
+
|
|
162
|
+
/** プラグインが足した式の関数の処理(プラグインの名前 → 関数の名前 → 処理)。@liminalia/sdk の combinePlugins が入れる。 */
|
|
163
|
+
const pluginFunctions = new Map<string, Map<string, PluginFunctionImpl>>();
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* そのプラグインが足す式の関数の処理を入れ替える(そのプラグインが前に入れたものは外す。ほかのプラグインのものは残す。
|
|
167
|
+
* 引数の数は @liminalia/lang の setPluginFunctions)。
|
|
168
|
+
*/
|
|
169
|
+
export function setPluginFunctionImpls(plugin: string, impls: Readonly<Record<string, PluginFunctionImpl>>): void {
|
|
170
|
+
pluginFunctions.delete(plugin);
|
|
171
|
+
if (Object.keys(impls).length > 0) pluginFunctions.set(plugin, new Map(Object.entries(impls)));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** プラグインの関数の処理(同じ名前は後に入れたプラグインのもの)。 */
|
|
175
|
+
function pluginFunction(name: string): PluginFunctionImpl | undefined {
|
|
176
|
+
let found: PluginFunctionImpl | undefined;
|
|
177
|
+
for (const own of pluginFunctions.values()) found = own.get(name) ?? found;
|
|
178
|
+
return found;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** プラグインの関数を呼ぶ。返した値が値の形(JSON にできるもの)でなければ誤りにする。 */
|
|
182
|
+
function callPlugin(name: string, run: (args: Value[], env: { random(): number }) => Value, args: Value[], env: EvalEnv): Value {
|
|
183
|
+
let v: unknown;
|
|
184
|
+
try {
|
|
185
|
+
v = run(structuredClone(args), { random: () => env.random() });
|
|
186
|
+
} catch (e) {
|
|
187
|
+
throw new EvalError(`${name}() が失敗しました: ${e instanceof Error ? e.message : String(e)}`);
|
|
188
|
+
}
|
|
189
|
+
if (v === undefined) return null;
|
|
190
|
+
if (v === null || typeof v === "string" || typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v))) return v;
|
|
191
|
+
if (typeof v === "object") {
|
|
192
|
+
try {
|
|
193
|
+
return JSON.parse(JSON.stringify(v)) as Value;
|
|
194
|
+
} catch {
|
|
195
|
+
// 下で誤りにする
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
throw new EvalError(`${name}() が値(数、文字、真偽、配列、オブジェクト)でないものを返しました`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function call(name: string, args: Value[], env: EvalEnv): Value {
|
|
202
|
+
if (name === "@each") {
|
|
203
|
+
// @for が回すもの(program.ts の EACH_FUNCTION)。配列はそのまま、辞書はキーの並び
|
|
204
|
+
const v = args[0] ?? null;
|
|
205
|
+
if (Array.isArray(v)) return v;
|
|
206
|
+
if (v !== null && typeof v === "object") return Object.keys(v);
|
|
207
|
+
throw new EvalError(`@for で回せるのは配列か辞書です(${describe(v)})`);
|
|
208
|
+
}
|
|
209
|
+
if (!Object.hasOwn(FUNCTION_ARITY, name)) {
|
|
210
|
+
const f = env.fn?.(name);
|
|
211
|
+
if (f) return callUser(name, f, args, env);
|
|
212
|
+
}
|
|
213
|
+
const arity = functionArity(name);
|
|
214
|
+
if (arity && (args.length < arity[0] || args.length > arity[1])) throw new EvalError(`${name}() の引数は ${arityText(arity)}です(${args.length} つ)`);
|
|
215
|
+
const num = (i: number) => {
|
|
216
|
+
const v = args[i];
|
|
217
|
+
if (typeof v !== "number") throw new EvalError(`${name}() の ${i + 1} 番目には数値が必要です(${describe(v ?? null)})`);
|
|
218
|
+
return v;
|
|
219
|
+
};
|
|
220
|
+
const str = (i: number) => {
|
|
221
|
+
const v = args[i];
|
|
222
|
+
if (typeof v !== "string") throw new EvalError(`${name}() の ${i + 1} 番目には文字列が必要です(${describe(v ?? null)})`);
|
|
223
|
+
return v;
|
|
224
|
+
};
|
|
225
|
+
const list = (i: number) => {
|
|
226
|
+
const v = args[i];
|
|
227
|
+
if (!Array.isArray(v)) throw new EvalError(`${name}() の ${i + 1} 番目には配列が必要です(${describe(v ?? null)})`);
|
|
228
|
+
return v;
|
|
229
|
+
};
|
|
230
|
+
const object = (i: number) => {
|
|
231
|
+
const v = args[i];
|
|
232
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) throw new EvalError(`${name}() の ${i + 1} 番目にはオブジェクトが必要です(${describe(v ?? null)})`);
|
|
233
|
+
return v;
|
|
234
|
+
};
|
|
235
|
+
const date = new Date();
|
|
236
|
+
switch (name) {
|
|
237
|
+
case "random":
|
|
238
|
+
// random() は 0 以上 1 未満、random(n) は 0 以上 n 未満の整数。
|
|
239
|
+
return args.length === 0 ? env.random() : Math.floor(env.random() * num(0));
|
|
240
|
+
case "randint": {
|
|
241
|
+
const [a, b] = [Math.ceil(num(0)), Math.floor(num(1))];
|
|
242
|
+
return a + Math.floor(env.random() * (b - a + 1));
|
|
243
|
+
}
|
|
244
|
+
case "pick": {
|
|
245
|
+
const xs = list(0);
|
|
246
|
+
return xs.length === 0 ? null : xs[Math.floor(env.random() * xs.length)]!;
|
|
247
|
+
}
|
|
248
|
+
case "shuffle": {
|
|
249
|
+
const xs = [...list(0)];
|
|
250
|
+
for (let i = xs.length - 1; i > 0; i--) {
|
|
251
|
+
const j = Math.floor(env.random() * (i + 1));
|
|
252
|
+
[xs[i], xs[j]] = [xs[j]!, xs[i]!];
|
|
253
|
+
}
|
|
254
|
+
return xs;
|
|
255
|
+
}
|
|
256
|
+
case "floor":
|
|
257
|
+
return Math.floor(num(0));
|
|
258
|
+
case "ceil":
|
|
259
|
+
return Math.ceil(num(0));
|
|
260
|
+
case "round": {
|
|
261
|
+
if (args.length === 1) return Math.round(num(0));
|
|
262
|
+
const k = 10 ** Math.max(0, Math.floor(num(1)));
|
|
263
|
+
return Math.round(num(0) * k) / k;
|
|
264
|
+
}
|
|
265
|
+
case "abs":
|
|
266
|
+
return Math.abs(num(0));
|
|
267
|
+
case "min":
|
|
268
|
+
return Math.min(...args.map((_, i) => num(i)));
|
|
269
|
+
case "max":
|
|
270
|
+
return Math.max(...args.map((_, i) => num(i)));
|
|
271
|
+
case "clamp":
|
|
272
|
+
return Math.min(num(2), Math.max(num(1), num(0)));
|
|
273
|
+
case "sum":
|
|
274
|
+
return list(0).reduce<number>((t, v) => {
|
|
275
|
+
if (typeof v !== "number") throw new EvalError(`sum() の配列には数値だけを入れます(${describe(v)})`);
|
|
276
|
+
return t + v;
|
|
277
|
+
}, 0);
|
|
278
|
+
case "len": {
|
|
279
|
+
const v = args[0];
|
|
280
|
+
if (typeof v === "string" || Array.isArray(v)) return v.length;
|
|
281
|
+
throw new EvalError(`len() には文字列か配列が必要です(${describe(v ?? null)})`);
|
|
282
|
+
}
|
|
283
|
+
case "includes": {
|
|
284
|
+
const [c, x] = args;
|
|
285
|
+
if (typeof c === "string" && typeof x === "string") return c.includes(x);
|
|
286
|
+
if (Array.isArray(c)) return c.some((e) => equals(e, x ?? null));
|
|
287
|
+
throw new EvalError(`includes() の 1 番目には文字列か配列が必要です(${describe(c ?? null)})`);
|
|
288
|
+
}
|
|
289
|
+
case "index": {
|
|
290
|
+
const [c, x] = args;
|
|
291
|
+
if (typeof c === "string" && typeof x === "string") return c.indexOf(x);
|
|
292
|
+
if (Array.isArray(c)) return c.findIndex((e) => equals(e, x ?? null));
|
|
293
|
+
throw new EvalError(`index() の 1 番目には文字列か配列が必要です(${describe(c ?? null)})`);
|
|
294
|
+
}
|
|
295
|
+
case "slice": {
|
|
296
|
+
const c = args[0];
|
|
297
|
+
const end = args.length > 2 ? num(2) : undefined;
|
|
298
|
+
if (typeof c === "string") return [...c].slice(num(1), end).join("");
|
|
299
|
+
if (Array.isArray(c)) return c.slice(num(1), end);
|
|
300
|
+
throw new EvalError(`slice() の 1 番目には文字列か配列が必要です(${describe(c ?? null)})`);
|
|
301
|
+
}
|
|
302
|
+
case "replace":
|
|
303
|
+
return str(0).split(str(1)).join(str(2));
|
|
304
|
+
case "upper":
|
|
305
|
+
return str(0).toUpperCase();
|
|
306
|
+
case "lower":
|
|
307
|
+
return str(0).toLowerCase();
|
|
308
|
+
case "trim":
|
|
309
|
+
return str(0).trim();
|
|
310
|
+
case "split":
|
|
311
|
+
return str(0).split(str(1));
|
|
312
|
+
case "join":
|
|
313
|
+
return list(0).map((v) => display(v)).join(args.length > 1 ? str(1) : "");
|
|
314
|
+
case "pad":
|
|
315
|
+
return display(args[0] ?? null).padStart(Math.max(0, Math.floor(num(1))), args.length > 2 ? str(2) : "0");
|
|
316
|
+
case "str":
|
|
317
|
+
return display(args[0] ?? null);
|
|
318
|
+
case "num": {
|
|
319
|
+
const v = args[0];
|
|
320
|
+
if (typeof v === "number") return v;
|
|
321
|
+
if (typeof v !== "string" || v.trim() === "") return null;
|
|
322
|
+
const n = Number(v);
|
|
323
|
+
return Number.isFinite(n) ? n : null;
|
|
324
|
+
}
|
|
325
|
+
case "push":
|
|
326
|
+
return [...list(0), args[1] ?? null];
|
|
327
|
+
case "remove":
|
|
328
|
+
return list(0).filter((e) => !equals(e, args[1] ?? null));
|
|
329
|
+
case "sort":
|
|
330
|
+
return [...list(0)].sort((a, b) => (typeof a === "number" && typeof b === "number" ? a - b : display(a) < display(b) ? -1 : display(a) > display(b) ? 1 : 0));
|
|
331
|
+
case "reverse":
|
|
332
|
+
return [...list(0)].reverse();
|
|
333
|
+
case "unique":
|
|
334
|
+
return list(0).filter((e, i, xs) => xs.findIndex((x) => equals(x, e)) === i);
|
|
335
|
+
case "keys":
|
|
336
|
+
return Object.keys(object(0));
|
|
337
|
+
case "has":
|
|
338
|
+
return Object.hasOwn(object(0), str(1));
|
|
339
|
+
case "version_before":
|
|
340
|
+
return compareVersions(versionText(args[0]), versionText(args[1])) < 0;
|
|
341
|
+
case "year":
|
|
342
|
+
return date.getFullYear();
|
|
343
|
+
case "month":
|
|
344
|
+
return date.getMonth() + 1;
|
|
345
|
+
case "day":
|
|
346
|
+
return date.getDate();
|
|
347
|
+
case "hour":
|
|
348
|
+
return date.getHours();
|
|
349
|
+
case "minute":
|
|
350
|
+
return date.getMinutes();
|
|
351
|
+
case "weekday":
|
|
352
|
+
return date.getDay();
|
|
353
|
+
case "now":
|
|
354
|
+
return date.getTime();
|
|
355
|
+
case "visits":
|
|
356
|
+
case "read":
|
|
357
|
+
case "chosen":
|
|
358
|
+
str(0);
|
|
359
|
+
return env.story ? env.story(name, args) : name === "visits" ? 0 : false;
|
|
360
|
+
case "lang":
|
|
361
|
+
case "platform":
|
|
362
|
+
case "app":
|
|
363
|
+
case "replaying":
|
|
364
|
+
case "chapter":
|
|
365
|
+
return env.story ? env.story(name, args) : name === "lang" || name === "chapter" ? "" : name === "platform" ? "pc" : false;
|
|
366
|
+
case "endings":
|
|
367
|
+
// 見たエンディングの数(全セーブ共通。実行器が答える)
|
|
368
|
+
return env.story ? env.story(name, args) : 0;
|
|
369
|
+
case "item": {
|
|
370
|
+
// 持ち物の数(ゲームの変数の、式からは書けない名前のところ。@liminalia/lang の ITEMS_KEY)
|
|
371
|
+
const items = (env.lookup("game") as Scope | null)?.["@items"];
|
|
372
|
+
const key = args[0];
|
|
373
|
+
if (typeof key !== "string") throw new EvalError(`item() には持ち物の名前(文字列)が必要です(${describe(key ?? null)})`);
|
|
374
|
+
const count = items && typeof items === "object" && !Array.isArray(items) && Object.hasOwn(items, key) ? (items as Scope)[key] : 0;
|
|
375
|
+
return typeof count === "number" ? count : 0;
|
|
376
|
+
}
|
|
377
|
+
default: {
|
|
378
|
+
const run = pluginFunction(name);
|
|
379
|
+
if (run) return callPlugin(name, run, args, env);
|
|
380
|
+
throw new EvalError(`関数 ${name}() はありません`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** @function の関数を呼ぶ。中で読めるのは引数と game・system・temp・save だけ(呼んだ側の @let は見えない)。 */
|
|
386
|
+
function callUser(name: string, f: { file: string; params: readonly string[]; body: Expr }, args: Value[], env: EvalEnv): Value {
|
|
387
|
+
if (args.length !== f.params.length) throw new EvalError(`${name}() の引数は ${f.params.length} つです(${args.length} つ)`);
|
|
388
|
+
const depth = (env.depth ?? 0) + 1;
|
|
389
|
+
if (depth > MAX_FUNCTION_DEPTH) throw new EvalError(`${name}() の呼び出しが ${MAX_FUNCTION_DEPTH} 段を超えました(自分を呼び続けていないか確かめます)`);
|
|
390
|
+
const local = new Map(f.params.map((p, i) => [p, args[i] ?? null] as const));
|
|
391
|
+
const inner: EvalEnv = {
|
|
392
|
+
...env,
|
|
393
|
+
depth,
|
|
394
|
+
lookup: (n) => (local.has(n) ? local.get(n)! : n === "game" || n === "system" || n === "temp" || n === "save" ? env.lookup(n) : null),
|
|
395
|
+
...(env.fn ? { fn: (n: string, file?: string) => env.fn!(n, file ?? f.file) } : {}),
|
|
396
|
+
};
|
|
397
|
+
return evaluate(f.body, inner);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function describe(v: Value): string {
|
|
401
|
+
if (v === null) return "null";
|
|
402
|
+
if (Array.isArray(v)) return "配列";
|
|
403
|
+
if (typeof v === "object") return "オブジェクト";
|
|
404
|
+
return `${typeof v === "string" ? "文字列" : typeof v === "number" ? "数値" : "真偽値"} ${JSON.stringify(v)}`;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** シード付きの乱数(mulberry32)。状態は数値一つなのでセーブできる。 */
|
|
408
|
+
export function nextRandom(seed: number): { value: number; seed: number } {
|
|
409
|
+
let t = (seed + 0x6d2b79f5) | 0;
|
|
410
|
+
const next = t;
|
|
411
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
412
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
413
|
+
return { value: ((t ^ (t >>> 14)) >>> 0) / 4294967296, seed: next };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** version_before の版(文字列か数。null と空は「版の無い」もの)。 */
|
|
417
|
+
function versionText(v: Value | undefined): string {
|
|
418
|
+
if (v === undefined || v === null) return "";
|
|
419
|
+
if (typeof v === "string" || typeof v === "number") return String(v).trim();
|
|
420
|
+
throw new EvalError(`version_before() にはバージョン文字列("1.2.0" など)が必要です(${describe(v)})`);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* 版を比べる(1.2.10 は 1.2.9 より後。- の後ろの付いた 1.0.0-beta は 1.0.0 より前。頭の v は読まない。空の版はどの版よりも前)。
|
|
425
|
+
* a が前なら負、同じなら 0、後なら正。デスクトップ版の更新(packages/desktop/update.cjs の compareVersions)と同じ決まり。
|
|
426
|
+
*/
|
|
427
|
+
export function compareVersions(a: string, b: string): number {
|
|
428
|
+
if (a === "" || b === "") return a === b ? 0 : a === "" ? -1 : 1;
|
|
429
|
+
const split = (v: string) => {
|
|
430
|
+
const [main = "", pre] = v.replace(/^v/, "").split("-", 2);
|
|
431
|
+
return { nums: main.split(".").map((x) => Number.parseInt(x, 10) || 0), pre: pre ?? null };
|
|
432
|
+
};
|
|
433
|
+
const x = split(a);
|
|
434
|
+
const y = split(b);
|
|
435
|
+
for (let i = 0; i < Math.max(x.nums.length, y.nums.length); i++) {
|
|
436
|
+
const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
|
|
437
|
+
if (d !== 0) return d > 0 ? 1 : -1;
|
|
438
|
+
}
|
|
439
|
+
if (x.pre === y.pre) return 0;
|
|
440
|
+
if (x.pre === null) return 1;
|
|
441
|
+
if (y.pre === null) return -1;
|
|
442
|
+
return x.pre.localeCompare(y.pre, "en", { numeric: true }) > 0 ? 1 : -1;
|
|
443
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { autoVoicedLines, packCombinations, voiceLines, type Script } from "@liminalia/lang";
|
|
2
|
+
import { explore } from "./route.ts";
|
|
3
|
+
import type { RuntimeOptions } from "./runtime.ts";
|
|
4
|
+
|
|
5
|
+
/** 一回の流しで出すページの上限(終わらない作りでも止める)。 */
|
|
6
|
+
const MAX_PAGES = 200_000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 「はじめから」を画面なしで何通りか流し、台詞の鍵(voiceLines)→ 鳴った連番を集める(lim voice-lock と制作画面の「番号を固定」)。
|
|
10
|
+
* 固定がまだ無いときに、今の数え方で鳴る番号をそのまま固定するために使う。選び方は、まだ試していないものへ広げていく
|
|
11
|
+
* (全ルートテストと同じ。route.ts の explore)。runs は流す回数の上限で、選び方を試し終えたら早く止める。
|
|
12
|
+
* 数え方の番号を見るので、渡した設定に番号の固定(voiceLock)があっても使わない(使うと、固定に無い台詞が鳴らない)。
|
|
13
|
+
*/
|
|
14
|
+
export async function observeVoiceNumbers(o: {
|
|
15
|
+
scripts: ReadonlyMap<string, Script>;
|
|
16
|
+
entry: string;
|
|
17
|
+
loadSource(file: string): Promise<string>;
|
|
18
|
+
runtime: RuntimeOptions;
|
|
19
|
+
runs: number;
|
|
20
|
+
/**
|
|
21
|
+
* パック(packs/<フォルダ>/scenario)の台本と、その中身を返す口(パックの台本だけ。無ければ undefined で、本体の台本を読む)。
|
|
22
|
+
* 遊ぶ人はパックのどの組み合わせでも入れうるので、本体にパックを一つずつ、二つずつ…重ねても流し(@liminalia/lang の packCombinations。
|
|
23
|
+
* 遊ぶ側と同じく、同じ名前の台本は後ろのパックのもの)、パックの台本にしか無い台詞の番号を集める(本体にもある台詞は、本体だけで流した番号)。
|
|
24
|
+
* 小さい組から流し、前の組で鳴った台詞には、あとの組で鳴った番号を足さない(組み合わせで番号が変わったと出さないため)。
|
|
25
|
+
* 写す台詞(その組で連番が鳴りうるもの。autoVoicedLines)が残っていない組は流さない。台本のあるパックが PACK_COMBINATION_LIMIT を超えたら、本体に一つずつとすべての組だけ。
|
|
26
|
+
*/
|
|
27
|
+
packs?: readonly { scripts: ReadonlyMap<string, Script>; source(file: string): string | undefined }[];
|
|
28
|
+
}): Promise<Map<string, Set<number>>> {
|
|
29
|
+
const seen = await observeOnce(o.scripts, o.entry, (file) => o.loadSource(file), o.runtime, o.runs);
|
|
30
|
+
const mainKeys = new Set([...o.scripts.values()].flatMap((script) => voiceLines(script).map((l) => l.key)));
|
|
31
|
+
const packs = (o.packs ?? []).filter((p) => p.scripts.size > 0);
|
|
32
|
+
const packKeys = packs.map((p) => new Set([...p.scripts.values()].flatMap((script) => voiceLines(script).map((l) => l.key)).filter((k) => !mainKeys.has(k))));
|
|
33
|
+
for (const combo of packCombinations(packs.length)) {
|
|
34
|
+
if (combo.length === 0) continue;
|
|
35
|
+
const chosen = combo.map((i) => packs[i]!);
|
|
36
|
+
const set = new Map([...o.scripts, ...chosen.flatMap((p) => [...p.scripts])]);
|
|
37
|
+
// 写す台詞: この組で連番が鳴りうる(autoVoicedLines。番号を振る updateVoiceLock と同じ)、この組のパックにしか無い、まだ写していない台詞
|
|
38
|
+
const voiced = autoVoicedLines(set, { entry: o.entry });
|
|
39
|
+
const wanted = new Set<string>();
|
|
40
|
+
for (const [name, script] of set) {
|
|
41
|
+
if (!chosen.some((p) => p.scripts.get(name) === script)) continue;
|
|
42
|
+
for (const l of voiceLines(script)) if (voiced.has(`${l.file}:${l.line}`) && combo.some((i) => packKeys[i]!.has(l.key)) && !seen.has(l.key)) wanted.add(l.key);
|
|
43
|
+
}
|
|
44
|
+
if (wanted.size === 0) continue;
|
|
45
|
+
const source = async (file: string) => {
|
|
46
|
+
// その組に無い台本(ほかのパックにだけある台本へ飛ぶパックなど)は、そこで終わる空の台本にする(組み合わせによっては無いのが正しい)
|
|
47
|
+
if (!set.has(file)) return "";
|
|
48
|
+
for (const p of [...chosen].reverse()) {
|
|
49
|
+
const text = p.source(file);
|
|
50
|
+
if (text !== undefined) return text;
|
|
51
|
+
}
|
|
52
|
+
return o.loadSource(file);
|
|
53
|
+
};
|
|
54
|
+
const observed = await observeOnce(set, o.entry, source, o.runtime, o.runs);
|
|
55
|
+
for (const [key, numbers] of observed) if (wanted.has(key)) for (const n of numbers) (seen.get(key) ?? seen.set(key, new Set()).get(key)!).add(n);
|
|
56
|
+
}
|
|
57
|
+
return seen;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** scripts(一緒に遊ばれる台本)を「はじめから」何通りか流し、台詞の鍵 → 鳴った連番を集める。 */
|
|
61
|
+
async function observeOnce(scripts: ReadonlyMap<string, Script>, entry: string, loadSource: (file: string) => Promise<string>, options: RuntimeOptions, runs: number): Promise<Map<string, Set<number>>> {
|
|
62
|
+
const o = { scripts, entry, loadSource, runtime: options, runs };
|
|
63
|
+
const keys = new Map<string, Map<number, string>>();
|
|
64
|
+
for (const [file, script] of o.scripts) keys.set(file, new Map(voiceLines(script).map((l) => [l.line, l.key])));
|
|
65
|
+
const seen = new Map<string, Set<number>>();
|
|
66
|
+
const { onStep: _onStep, onAssign: _onAssign, ...runtime } = o.runtime;
|
|
67
|
+
let pages = 0;
|
|
68
|
+
await explore({
|
|
69
|
+
start: o.entry,
|
|
70
|
+
runs: o.runs,
|
|
71
|
+
loadSource: (file) => o.loadSource(file),
|
|
72
|
+
runtime: { onError: "continue", maxSteps: 5_000_000, ...runtime, voiceLock: null },
|
|
73
|
+
begin: () => {
|
|
74
|
+
pages = 0;
|
|
75
|
+
},
|
|
76
|
+
present: (e, w) => {
|
|
77
|
+
if (e.type !== "page") return;
|
|
78
|
+
if (++pages >= MAX_PAGES) w.runtime.stop();
|
|
79
|
+
if (e.voice?.n === undefined) return;
|
|
80
|
+
const key = keys.get(e.at.file)?.get(e.at.line);
|
|
81
|
+
if (key) (seen.get(key) ?? seen.set(key, new Set()).get(key)!).add(e.voice.n);
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
return seen;
|
|
85
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { TextOrigin } from "./retranslate.js";
|
|
2
|
+
import type { NvlPart, StageState } from "./state.js";
|
|
3
|
+
import type { Value } from "./value.js";
|
|
4
|
+
/**
|
|
5
|
+
* チャットの画面の状態(stage.extra の "std.chat")。描くのと @chat-open・@chat は @liminalia/std だが、ふだんの台詞を吹き出しにするとき
|
|
6
|
+
* (ui.chat.dialogue)は、読み終えたページと選んだ選択肢を実行器が積む(NVL の段落と同じく、セーブとロード、画面なしで流す道筋の探索でも同じになるように)。
|
|
7
|
+
*/
|
|
8
|
+
export interface ChatMessage {
|
|
9
|
+
speaker: string;
|
|
10
|
+
text: string;
|
|
11
|
+
/** 画像(image からのパス。スタンプ・写真)。 */
|
|
12
|
+
image: string;
|
|
13
|
+
/** 自分の吹き出し(右に出す)。 */
|
|
14
|
+
me: boolean;
|
|
15
|
+
/** 足した命令の位置(その命令からやり直したとき、二度足さないため)。 */
|
|
16
|
+
at?: string;
|
|
17
|
+
/** 地の文(中央の小さな一行)。 */
|
|
18
|
+
note?: boolean;
|
|
19
|
+
/** 話者名の訳(多言語)。出すのはこちら。 */
|
|
20
|
+
label?: string;
|
|
21
|
+
/** 本文の一片(ルビ・装飾つき。あれば text の代わりに描く)。 */
|
|
22
|
+
parts?: NvlPart[];
|
|
23
|
+
/** そのときの顔(キャスト名と姿)。 */
|
|
24
|
+
face?: {
|
|
25
|
+
who: string;
|
|
26
|
+
appearance: string;
|
|
27
|
+
variant: string;
|
|
28
|
+
};
|
|
29
|
+
/** 言語を替えたときに出し直す元(text・label。retranslate.ts)。 */
|
|
30
|
+
i18n?: Record<string, TextOrigin>;
|
|
31
|
+
}
|
|
32
|
+
export interface Chat {
|
|
33
|
+
title: string;
|
|
34
|
+
/** 自分の名前(この話者の吹き出しを右に出す)。 */
|
|
35
|
+
me: string;
|
|
36
|
+
messages: ChatMessage[];
|
|
37
|
+
/** @chat-open を使わず、ふだんの台詞から始めた画面(ui.chat.dialogue を外した作品では出さない)。 */
|
|
38
|
+
auto?: boolean;
|
|
39
|
+
/** 言語を替えたときに出し直す元(title。retranslate.ts)。 */
|
|
40
|
+
i18n?: Record<string, TextOrigin>;
|
|
41
|
+
}
|
|
42
|
+
/** ふだんの台詞を吹き出しにする設定(ui.chat.dialogue のとき。me と title は ui.chat の値)。 */
|
|
43
|
+
export interface ChatDialogue {
|
|
44
|
+
me?: string;
|
|
45
|
+
title?: string;
|
|
46
|
+
}
|
|
47
|
+
export declare const CHAT_KEY = "std.chat";
|
|
48
|
+
/** 残す吹き出しの数(古いものから捨てる。セーブを小さく保つ)。 */
|
|
49
|
+
export declare const CHAT_KEEP = 60;
|
|
50
|
+
export declare function readChat(extra: Record<string, Value>): Chat | null;
|
|
51
|
+
/** 本文をチャットに出す状態か(@nvl on・@vertical on・@balloon on の間は、いつものメッセージ枠に戻す)。 */
|
|
52
|
+
export declare function chatDialogueActive(stage: StageState): boolean;
|
|
53
|
+
/** 列の終わりに吹き出しを足す(無ければ画面ごと作る)。 */
|
|
54
|
+
export declare function pushChatMessage(extra: Record<string, Value>, o: ChatDialogue | null, message: (chat: Chat) => ChatMessage): void;
|
|
55
|
+
/** 列を空にする(@clear)。 */
|
|
56
|
+
export declare function clearChatMessages(extra: Record<string, Value>): void;
|
|
57
|
+
/**
|
|
58
|
+
* 台詞を包む鉤括弧(「…」『…』)を、本文を出す順に外す関数を作る(吹き出しが括弧の代わりなので。入れ子の括弧は残し、(…)は心の声として残す)。
|
|
59
|
+
* 本文は装飾やルビの切れ目で分かれて届くので、ページ全体を通して一つ使う。
|
|
60
|
+
*/
|
|
61
|
+
export declare function chatQuoteStripper(): (text: string) => string;
|
|
62
|
+
/** 本文の一片の文字列(ルビは親文字だけ。絵は数えない)。 */
|
|
63
|
+
export declare function chatPartsText(parts: readonly NvlPart[]): string;
|