@liminalia/sdk 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/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export { t, toImplementation, toSpec, type CommandDefinition, type CommandDiagnostic, type CommandValidateContext, type ParamDefinition } from "./command.ts";
2
+ export { checkDeclaredData, d, dataDeclarations, declaredData, pluginDataCg, projectDataTexts } from "./data.ts";
3
+ export { apiSatisfies, checkPluginManifest, combinePlugins, commandArgs, dataKeys, defineCommandPlugin, engineMismatches, PLUGIN_API_VERSION, pluginWrittenVariables, runPluginChecks, undeclaredOverrides, type CommandPlugin, type PluginCheckProject, type PluginDiagnostic, type PluginFunction } from "./plugin.ts";
4
+ export { defineState, type PluginState } from "./state.ts";
5
+ // 作品全体の検査(lim check、制作画面、VS Code、MCP が同じ入力から同じ一覧を作る)
6
+ export { packTranslationScope, parsePacks, pluginTargetHooks, projectDiagnostics, type PackCheckSource, type ParsedPack, type ProjectCheckConfig, type ProjectCheckInput } from "./project-check.ts";
7
+ // ルール画像の切り替え(rule・pattern・vague)の引数。作品の命令でも同じ書き方で受けられる
8
+ export { RULE_PARAMS, RULE_PATTERNS } from "@liminalia/lang";
9
+ // 命令の定義に英語を重ねる(名前 → { summary, params, keywords, example } の表から summaryEn、docEn、keywordsEn、exampleEn を付ける)
10
+ export { withEnglish, type CommandEnglish } from "@liminalia/lang";
package/src/plugin.ts ADDED
@@ -0,0 +1,424 @@
1
+ import { CORE_COMMANDS, CORE_FUNCTIONS, dataFlagsSet, normalizeBooleanArgs, PLUGIN_API_VERSION, scriptLabels, setPluginFunctions, type Argument, type Cast, type CommandSpec, type DataDeclaration, type Diagnostic, type Registry, type Script, type Statement } from "@liminalia/lang";
2
+ import { setPluginFunctionImpls, type Value } from "@liminalia/runtime";
3
+ import { toImplementation, toSpec, type CommandDefinition, type CommandDiagnostic } from "./command.ts";
4
+ import { checkDeclaredData, declaredData } from "./data.ts";
5
+
6
+ export { PLUGIN_API_VERSION };
7
+
8
+ /**
9
+ * プラグインが足す式の関数(CommandPlugin.functions)。台本の式(@if・@set・{…}・条件の式)から `名前(引数…)` で呼べる。
10
+ * 引数は評価した値の写し(書き換えても台本の変数は変わらない)、返すのは値(数・文字・真偽・null・配列・オブジェクト)。
11
+ * 乱数は env.random()(作品の乱数のシードに従うので、ロードしても同じ値になる)。同期の関数で、状態を持たない(同じ引数なら同じ値)ように書く。
12
+ */
13
+ export interface PluginFunction {
14
+ /** 引数の数(数一つならちょうどその数、[最小, 最大]。最大は Infinity も書ける)。lim check と実行器が確かめる。 */
15
+ args: number | readonly [min: number, max: number];
16
+ /** 説明(lim reference の式の関数の表に出す)。 */
17
+ doc: string;
18
+ docEn?: string;
19
+ /** 書き方の例(`rank(game.score)` など。無ければ `名前()`)。 */
20
+ usage?: readonly string[];
21
+ run(args: Value[], env: { random(): number }): Value;
22
+ }
23
+
24
+ /**
25
+ * プラグインの命令側(Node でも読める部分)。プロジェクト設定の plugins に書いたパッケージの
26
+ * "./commands" がこれを default export する。検査・画面なしの実行・書き出し・プレイヤーが読む。
27
+ * 見た目(描画・システム画面)は同じパッケージの "./web" が担う(@liminalia/web の WebPlugin)。
28
+ * TyranoScript の .ks からの取り込み(タグの変換表・[iscript] の置き換え・扱わないタグ)は "./import" が担う
29
+ * (@liminalia/ks-import の TyranoImportProfile)。書き出すゲームには入らない。
30
+ */
31
+ export interface CommandPlugin {
32
+ name: string;
33
+ commands: readonly CommandDefinition[];
34
+ /**
35
+ * 作品全体を読んで診断を返す(lim check・lim build・制作画面のチェックが呼ぶ。保存のたびにも呼ぶので重い処理は避ける。同期の関数で書く)。
36
+ * 分類は「プラグイン」に入る。投げても全体のチェックは止まらず、そのプラグインの診断として出る。
37
+ */
38
+ check?(project: PluginCheckProject): readonly PluginDiagnostic[];
39
+ /**
40
+ * 作品のデータ(paths.data の .json)の形の宣言(@liminalia/sdk の d で書く)。この宣言から、lim check と制作画面のチェックが形・素材・
41
+ * キャスト・飛び先・式を確かめ、データの中のフラグと台本の @set を突き合わせ、制作画面が自動のフォームを作り、シーン・ファイル・素材・
42
+ * 変数・キャストの名前を変えたらデータも書き換える。CG の印(d.asset(…, { cg: true }))の素材は、どこからも出ない CG の検査が出ているものと数える。
43
+ */
44
+ data?: readonly DataDeclaration[];
45
+ /**
46
+ * このプラグインの命令が値を入れる変数("game.x"。末尾を .* にすると、その下の名前すべて。"game.codex.*" など)。
47
+ * lim check と制作画面のチェックは、どこでも値を入れずに読むだけの変数を綴り違いとして知らせるので、プラグインが ctx.runtime.setVariable などで
48
+ * 値を入れる変数はここに書く。
49
+ */
50
+ variables?: readonly string[];
51
+ /**
52
+ * 式の関数(名前 → 定義)。台本の式から呼べる(lim check の unknown-function にならない)。組み込みの関数と同じ名前は使えない
53
+ * (lim check が plugin-function-clash を出し、組み込みのほうを使う)。
54
+ */
55
+ functions?: Readonly<Record<string, PluginFunction>>;
56
+ /**
57
+ * このプラグインを書いたときのプラグインの口の版(PLUGIN_API_VERSION)。エンジンの版より新しければ、lim check と制作画面のチェックが
58
+ * 「新しいエンジンが要る」と知らせる(plugin-api-version)。書かなければ確かめない。
59
+ */
60
+ apiVersion?: number;
61
+ }
62
+
63
+ /** プラグインが値を入れる変数(宣言 variables)と、作品のデータが立てるフラグ。変数の綴り違いの検査に渡す。 */
64
+ export function pluginWrittenVariables(plugins: readonly CommandPlugin[], read: (name: string) => unknown): string[] {
65
+ return [...plugins.flatMap((p) => p.variables ?? []), ...dataFlagsSet(declaredData(plugins, read))];
66
+ }
67
+
68
+ /** プラグインの check が読む作品。 */
69
+ export interface PluginCheckProject {
70
+ /** 作品のフォルダ。 */
71
+ root: string;
72
+ /** liminalia.json の中身。 */
73
+ config: Readonly<Record<string, unknown>>;
74
+ /** ファイル(拡張子なし)→ 構文木。 */
75
+ scripts: ReadonlyMap<string, Script>;
76
+ /** 台本の文字(拡張子なし)。 */
77
+ text(file: string): string;
78
+ cast: Readonly<Cast>;
79
+ speakers: readonly string[];
80
+ /** 命令の仕様(組み込み・標準・プラグイン)。 */
81
+ registry: Registry;
82
+ /** 作品のデータ(paths.data の .json。無ければ undefined)。 */
83
+ data(name: string): unknown;
84
+ /** 素材のフォルダ(image・bgimage など)の中にあるか。 */
85
+ assetExists(folder: string, path: string): boolean;
86
+ /** 作品のデータの文字(診断の行を求めるのに使う。無ければ 1 行目に出す)。 */
87
+ dataText?(name: string): string | undefined;
88
+ /** 診断に書くデータのフォルダの名前(作品のフォルダからのパス。既定 data)。 */
89
+ dataFolder?: string;
90
+ }
91
+
92
+ /**
93
+ * プラグインの check が返す診断。file を省くと liminalia.json、line を省くと 1。訳があれば messageEn・hintEn に書く(無ければ英語の表示でも原文のまま)。
94
+ * fix・fixes に直し方(行の置き換え・行の削除・話者に足す・シーンを作る)を書くと、制作画面のチェックとエディタに「修正」が出る。
95
+ */
96
+ export type PluginDiagnostic = Pick<Diagnostic, "severity" | "code" | "message"> & Partial<Pick<Diagnostic, "messageEn" | "file" | "line" | "column" | "hint" | "hintEn" | "fix" | "fixes">>;
97
+
98
+ const SEVERITIES: ReadonlySet<string> = new Set(["error", "warning", "info"]);
99
+
100
+ /** プラグインの返したものを診断の形にする(形の合わないものは null)。 */
101
+ function pluginDiagnostic(name: string, d: PluginDiagnostic): Diagnostic | null {
102
+ if (!d || typeof d !== "object" || typeof d.message !== "string" || !SEVERITIES.has(d.severity) || typeof d.code !== "string") return null;
103
+ const { file, line, fix, fixes, ...rest } = d;
104
+ const out: Diagnostic = { ...rest, file: typeof file === "string" && file !== "" ? file : "liminalia.json", line: typeof line === "number" && line >= 1 ? line : 1, plugin: name };
105
+ // 直し方は形の合うものだけ(制作画面がそのまま当てる)
106
+ if (fix && validFix(fix)) out.fix = fix;
107
+ const list = Array.isArray(fixes) ? fixes.filter(validFix) : [];
108
+ if (out.fix && !list.some((f) => JSON.stringify(f) === JSON.stringify(out.fix))) list.unshift(out.fix);
109
+ if (list.length > 0) out.fixes = list;
110
+ return out;
111
+ }
112
+
113
+ /** 直し方の形(DiagnosticFix・ProjectFix)か。 */
114
+ function validFix(f: unknown): f is NonNullable<Diagnostic["fixes"]>[number] {
115
+ if (!f || typeof f !== "object") return false;
116
+ const x = f as Record<string, unknown>;
117
+ switch (x.kind) {
118
+ case "delete-line":
119
+ return typeof x.text === "string";
120
+ case "replace":
121
+ return typeof x.find === "string" && x.find !== "" && typeof x.with === "string";
122
+ case "add-speaker":
123
+ return typeof x.name === "string" && x.name !== "";
124
+ case "add-label":
125
+ return typeof x.file === "string" && typeof x.label === "string" && x.label !== "";
126
+ default:
127
+ return false;
128
+ }
129
+ }
130
+
131
+ /** 台本の命令の行(@if・@define・@with の中も)。 */
132
+ function* commandsIn(body: readonly Statement[]): Generator<{ name: string; args: readonly Argument[]; line: number }> {
133
+ for (const s of body) {
134
+ if (s.kind === "command") yield { name: s.name, args: s.args, line: s.line };
135
+ else if (s.kind === "if") {
136
+ if (s.with) yield { name: s.with.name, args: s.with.args, line: s.line };
137
+ for (const b of s.branches) yield* commandsIn(b.body);
138
+ } else if (s.kind === "define") yield* commandsIn(s.body);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 命令の行の、書いたままの文字の引数(位置引数も名前で引ける。式で書いた引数は入らない)。
144
+ * spec を渡すと、検査と実行器と同じ読み方(normalizeBooleanArgs)にする(名前なしの値を bare の引数に、真偽値の省略形をその名前に当てる)。
145
+ */
146
+ export function commandArgs(args: readonly Argument[], positional: readonly string[], spec?: CommandSpec): Record<string, string> {
147
+ const out: Record<string, string> = {};
148
+ let pos = 0;
149
+ for (const a of spec ? normalizeBooleanArgs(spec, args) : args) {
150
+ const key = a.key ?? positional[pos++];
151
+ if (!key) continue;
152
+ if (a.value.kind === "string") out[key] = a.value.value;
153
+ else if (a.value.kind === "number" || a.value.kind === "bool") out[key] = String(a.value.value);
154
+ }
155
+ return out;
156
+ }
157
+
158
+ /** 作品のデータの path(/ で区切る)の下の名前(辞書なら鍵、並びなら項目の id)。道が無ければ null。 */
159
+ export function dataKeys(data: unknown, path: string): string[] | null {
160
+ let v = data;
161
+ for (const part of path.split("/").filter((p) => p !== "")) {
162
+ if (Array.isArray(v)) v = v.find((x) => x && typeof x === "object" && (x as Record<string, unknown>).id === part);
163
+ else if (v && typeof v === "object") v = (v as Record<string, unknown>)[part];
164
+ else return null;
165
+ }
166
+ if (Array.isArray(v)) return v.flatMap((x) => (x && typeof x === "object" && typeof (x as Record<string, unknown>).id === "string" ? [(x as Record<string, unknown>).id as string] : []));
167
+ if (v && typeof v === "object") return Object.keys(v);
168
+ return null;
169
+ }
170
+
171
+ /** 命令ごとの検査(validate)と、データの名前の引数(t.dataKey)の実在。 */
172
+ function checkCommandLines(plugins: readonly CommandPlugin[], project: PluginCheckProject, out: Diagnostic[]): void {
173
+ const defs = new Map<string, { plugin: string; def: CommandDefinition }>();
174
+ for (const p of plugins) for (const c of p.commands) defs.set(c.name, { plugin: p.name, def: c });
175
+ const keyed = [...defs.values()].filter(({ def }) => def.validate || Object.values(def.params).some((p) => p.type.kind === "string" && p.type.data));
176
+ if (keyed.length === 0) return;
177
+ const folder = project.dataFolder ?? "data";
178
+ let labels: Map<string, Set<string>> | null = null;
179
+ const targetExists = (file: string, target: string) => {
180
+ labels ??= scriptLabels(project.scripts);
181
+ const [f, l] = target.startsWith("#") ? [file, target.slice(1)] : (target.split("#") as [string, string | undefined]);
182
+ const names = labels.get(f);
183
+ return !!names && (l === undefined || l === "" || names.has(l));
184
+ };
185
+ for (const [file, script] of project.scripts) {
186
+ for (const c of commandsIn(script.body)) {
187
+ const found = defs.get(c.name);
188
+ if (!found) continue;
189
+ const { plugin, def } = found;
190
+ const args = commandArgs(c.args, def.positional ?? [], toSpec(def));
191
+ // データの名前(t.dataKey)
192
+ for (const [param, p] of Object.entries(def.params)) {
193
+ const where = p.type.kind === "string" ? p.type.data : undefined;
194
+ const value = args[param];
195
+ if (!where || value === undefined) continue;
196
+ const data = project.data(where.file);
197
+ const keys = dataKeys(data, where.path);
198
+ const at = `${folder}/${where.file}`;
199
+ if (data === undefined)
200
+ out.push({ severity: "error", code: "unknown-data-key", message: `@${c.name} ${value} の ${at} がありません`, messageEn: `${at} for @${c.name} ${value} doesn't exist`, file, line: c.line, plugin, hint: `${at} を作り、${where.path} に ${value} を書きます(形の宣言のあるデータは、制作画面の「プラグイン」のタブで作れます)`, hintEn: `Create ${at} and add ${value} to ${where.path} (Studio's Plugins tab can create data with a declared shape)` });
201
+ else if (keys === null)
202
+ out.push({ severity: "error", code: "unknown-data-key", message: `@${c.name} の ${param} が読む ${at} の ${where.path} がありません`, messageEn: `${where.path} in ${at}, read by ${param} of @${c.name}, doesn't exist`, file, line: c.line, plugin });
203
+ else if (!keys.includes(value))
204
+ out.push({ severity: "error", code: "unknown-data-key", message: `@${c.name} の ${param} の ${value} が ${at} の ${where.path} にありません`, messageEn: `${value} (${param} of @${c.name}) isn't in ${where.path} of ${at}`, file, line: c.line, plugin, ...(keys.length > 0 ? { hint: `書ける名前: ${keys.slice(0, 8).join("、")}${keys.length > 8 ? " …" : ""}`, hintEn: `Names you can use: ${keys.slice(0, 8).join(", ")}${keys.length > 8 ? " …" : ""}` } : {}) });
205
+ }
206
+ if (!def.validate) continue;
207
+ try {
208
+ const result: unknown = def.validate(args, {
209
+ file,
210
+ line: c.line,
211
+ data: (name) => project.data(name),
212
+ assetExists: (f, path) => project.assetExists(f, path),
213
+ isCast: (name) => Object.hasOwn(project.cast, name),
214
+ targetExists: (target) => targetExists(file, target),
215
+ });
216
+ if (result === undefined) continue;
217
+ if (!Array.isArray(result)) throw new Error("validate が診断の配列を返しませんでした");
218
+ for (const item of result as CommandDiagnostic[]) {
219
+ const d = pluginDiagnostic(plugin, { ...item, file: item.file ?? file, line: item.line ?? c.line });
220
+ if (d) out.push(d);
221
+ else out.push({ severity: "error", code: "plugin-check-invalid", message: `@${c.name} の validate が形の合わない診断を返しました: ${JSON.stringify(item)}`, messageEn: `validate of @${c.name} returned a malformed diagnostic: ${JSON.stringify(item)}`, file, line: c.line, hint: "診断には severity(error、warning、info)、code、message を書きます", hintEn: "A diagnostic needs severity (error, warning or info), code and message", plugin });
222
+ }
223
+ } catch (e) {
224
+ const text = e instanceof Error ? e.message : String(e);
225
+ out.push({ severity: "error", code: "plugin-check-failed", message: `@${c.name} の validate が失敗しました: ${text}`, messageEn: `validate of @${c.name} failed: ${text}`, file, line: c.line, hint: "プラグインの validate を直します(ほかの検査は最後まで行いました)", hintEn: "Fix the plugin's validate (all other checks still ran)", plugin });
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ /** プラグインの口の版(apiVersion)と式の関数の名前。 */
232
+ function checkPluginApi(plugins: readonly CommandPlugin[], out: Diagnostic[]): void {
233
+ const builtIn = CORE_FUNCTIONS;
234
+ for (const p of plugins) {
235
+ if (typeof p.apiVersion === "number" && p.apiVersion > PLUGIN_API_VERSION) {
236
+ out.push({
237
+ severity: "warning",
238
+ code: "plugin-api-version",
239
+ message: `プラグイン ${p.name} はプラグイン API バージョン ${p.apiVersion} 向けで、このエンジン(バージョン ${PLUGIN_API_VERSION})より新しい API を使います`,
240
+ messageEn: `The plugin ${p.name} targets plugin API version ${p.apiVersion}, newer than this engine's (${PLUGIN_API_VERSION})`,
241
+ file: "liminalia.json",
242
+ line: 1,
243
+ hint: "Liminalia を新しいバージョンに更新するか、このエンジンに対応するバージョンのプラグインを入れます",
244
+ hintEn: "Update Liminalia, or install a version of the plugin made for this engine",
245
+ plugin: p.name,
246
+ });
247
+ }
248
+ for (const name of Object.keys(p.functions ?? {})) {
249
+ if (!builtIn.has(name)) continue;
250
+ out.push({ severity: "warning", code: "plugin-function-clash", message: `プラグイン ${p.name} の式の関数 ${name}() は組み込みの関数と同じ名前なので使われません`, messageEn: `The plugin ${p.name}'s expression function ${name}() has the same name as a built-in function, so it isn't used`, file: "liminalia.json", line: 1, hint: "関数の名前を変えます", hintEn: "Rename the function", plugin: p.name });
251
+ }
252
+ }
253
+ }
254
+
255
+
256
+ /**
257
+ * 合うエンジンの宣言(liminalia.api: 要る口の版、engines.liminalia: 合う口の版の範囲)のうち、このエンジンの口の版(PLUGIN_API_VERSION)に
258
+ * 合わないもの("3"、">=3" など、書いたままの形)。合えば、宣言が無ければ、読めなければ空。
259
+ * プラグインの package.json、テーマの theme.json、作品とひな形の liminalia.json で同じ形を読む。
260
+ */
261
+ export function engineMismatches(manifest: unknown, version: number = PLUGIN_API_VERSION): string[] {
262
+ if (!manifest || typeof manifest !== "object") return [];
263
+ const m = manifest as { liminalia?: { api?: unknown }; engines?: Record<string, unknown> };
264
+ const out: string[] = [];
265
+ const api = m.liminalia?.api;
266
+ if (typeof api === "number" && api > version) out.push(String(api));
267
+ const range = m.engines?.liminalia;
268
+ if (typeof range === "string" && range.trim() !== "" && !apiSatisfies(version, range)) out.push(range.trim());
269
+ return out;
270
+ }
271
+
272
+ /**
273
+ * プラグインの package.json の宣言(liminalia.api: 要るプラグインの口の版、engines.liminalia: 合うプラグインの口の版の範囲)を、このエンジンと比べる。
274
+ * spec は liminalia.json の plugins に書いた形(診断に出す)。合わなければ警告(plugin-engine-version)。
275
+ */
276
+ export function checkPluginManifest(spec: string, manifest: unknown): Diagnostic[] {
277
+ return engineMismatches(manifest).map((need) => ({
278
+ severity: "warning",
279
+ code: "plugin-engine-version",
280
+ message: `プラグイン ${spec} はプラグイン API バージョン ${need} 向けのため、このエンジン(バージョン ${PLUGIN_API_VERSION})では動かないことがあります`,
281
+ messageEn: `The plugin ${spec} needs plugin API version ${need}, but this engine provides version ${PLUGIN_API_VERSION}; it may not work`,
282
+ file: "liminalia.json",
283
+ line: 1,
284
+ hint: "Liminalia を新しいバージョンに更新するか、このエンジンに対応するバージョンのプラグインを入れます",
285
+ hintEn: "Update Liminalia, or install a version of the plugin made for this engine",
286
+ plugin: spec,
287
+ }));
288
+ }
289
+
290
+ /**
291
+ * プラグインの口の版 version が範囲 range に入るか。`2`、`>=2`、`>2`、`<=3`、`<3`、`^2`(2 以上 3 未満)、`2 - 4`、`*`、
292
+ * 空白区切り(すべて満たす)と `||`(どれか)を読む。読めない範囲は入るとみなす(知らない書き方で止めない)。
293
+ */
294
+ export function apiSatisfies(version: number, range: string): boolean {
295
+ return range.split("||").some((alt) => {
296
+ const part = alt.trim();
297
+ if (part === "" || part === "*" || part === "x") return true;
298
+ const hyphen = /^(\d+)(?:\.[\dx*]+)*\s+-\s+(\d+)(?:\.[\dx*]+)*$/.exec(part);
299
+ if (hyphen) return version >= Number(hyphen[1]) && version <= Number(hyphen[2]);
300
+ return part.split(/\s+/).every((c) => {
301
+ const m = /^(>=|<=|>|<|=|\^|~)?v?(\d+)(?:\.[\dx*]+)*$/.exec(c);
302
+ if (!m) return true;
303
+ const n = Number(m[2]);
304
+ switch (m[1]) {
305
+ case ">=":
306
+ return version >= n;
307
+ case "<=":
308
+ return version <= n;
309
+ case ">":
310
+ return version > n;
311
+ case "<":
312
+ return version < n;
313
+ case "^":
314
+ case "~":
315
+ case "=":
316
+ case undefined:
317
+ return version === n;
318
+ default:
319
+ return true;
320
+ }
321
+ });
322
+ });
323
+ }
324
+
325
+ /**
326
+ * 組み込みの命令か、先に読んだプラグインの同じ名前の命令を、宣言(replaces: true)なしに上書きしている命令。後に読んだプラグインの命令が使われる
327
+ * (combinePlugins と実行器)。over は上書きされた側(組み込みならエンジン、そうでなければそのプラグインの名前)。
328
+ */
329
+ export function undeclaredOverrides(plugins: readonly CommandPlugin[], builtIn: Iterable<string> = CORE_COMMANDS.map((c) => c.name)): { plugin: string; name: string; over: string | null }[] {
330
+ const owner = new Map<string, string | null>();
331
+ for (const name of builtIn) owner.set(name, null);
332
+ const out: { plugin: string; name: string; over: string | null }[] = [];
333
+ for (const p of plugins) {
334
+ for (const c of p.commands) {
335
+ if (owner.has(c.name) && !c.replaces && owner.get(c.name) !== p.name) out.push({ plugin: p.name, name: c.name, over: owner.get(c.name)! });
336
+ owner.set(c.name, p.name);
337
+ }
338
+ }
339
+ return out;
340
+ }
341
+
342
+ /** プラグインの check を順に呼ぶ。投げたもの・形の合わないものは、チェック全体を止めずにそのプラグインの診断にする。 */
343
+ export function runPluginChecks(plugins: readonly CommandPlugin[], project: PluginCheckProject): Diagnostic[] {
344
+ const out: Diagnostic[] = [];
345
+ // 宣言なしの上書き(標準の命令が増えて、作品のプラグインの命令と名前がぶつかったときなど)
346
+ for (const o of undeclaredOverrides(plugins)) {
347
+ const over = o.over === null ? "組み込み" : o.over;
348
+ const overEn = o.over === null ? "the built-in" : o.over;
349
+ out.push({
350
+ severity: "warning",
351
+ code: "plugin-replaces-command",
352
+ message: `プラグイン ${o.plugin} の @${o.name} が、${over} の @${o.name} を上書きしています(置き換えの宣言がありません)`,
353
+ messageEn: `The plugin ${o.plugin}'s @${o.name} overrides ${overEn} @${o.name} (it doesn't declare that it replaces it)`,
354
+ file: "liminalia.json",
355
+ line: 1,
356
+ hint: `置き換えるつもりなら、命令の定義に replaces: true を書きます。そうでなければ命令の名前を変えます`,
357
+ hintEn: "If it's meant to replace it, add replaces: true to the command definition. Otherwise rename the command",
358
+ plugin: o.plugin,
359
+ });
360
+ }
361
+ const problem = (name: string, code: string, message: string, messageEn: string, hint: string, hintEn: string) => out.push({ severity: "error", code, message, messageEn, file: "liminalia.json", line: 1, hint, hintEn, plugin: name });
362
+ // プラグインの口の版と、式の関数の名前
363
+ checkPluginApi(plugins, out);
364
+ // 命令ごとの検査(validate)とデータの名前の引数(t.dataKey)
365
+ checkCommandLines(plugins, project, out);
366
+ // データの形の宣言(data)の検査。投げても全体のチェックは止めない
367
+ try {
368
+ out.push(...checkDeclaredData(plugins, project));
369
+ } catch (e) {
370
+ const text = e instanceof Error ? e.message : String(e);
371
+ problem("data", "plugin-check-failed", `データの形の検査が失敗しました: ${text}`, `Checking the declared data failed: ${text}`, "データの宣言を直します(ほかの検査は最後まで行いました)", "Fix the data declarations (all other checks still ran)");
372
+ }
373
+ for (const p of plugins) {
374
+ if (!p.check) continue;
375
+ try {
376
+ const result: unknown = p.check(project);
377
+ if (!Array.isArray(result)) {
378
+ problem(p.name, "plugin-check-invalid", `プラグイン ${p.name} の check が診断の配列を返しませんでした`, `The check of the plugin ${p.name} didn't return an array of diagnostics`, "check は同期の関数にして、診断の配列を返します", "Make check a synchronous function that returns an array of diagnostics");
379
+ continue;
380
+ }
381
+ for (const item of result as PluginDiagnostic[]) {
382
+ const d = pluginDiagnostic(p.name, item);
383
+ if (d) out.push(d);
384
+ else problem(p.name, "plugin-check-invalid", `プラグイン ${p.name} の check が形の合わない診断を返しました: ${JSON.stringify(item)}`, `The check of the plugin ${p.name} returned a malformed diagnostic: ${JSON.stringify(item)}`, "診断には severity(error、warning、info)、code、message を書きます", "A diagnostic needs severity (error, warning or info), code and message");
385
+ }
386
+ } catch (e) {
387
+ const text = e instanceof Error ? e.message : String(e);
388
+ problem(p.name, "plugin-check-failed", `プラグイン ${p.name} の check が失敗しました: ${text}`, `The check of the plugin ${p.name} failed: ${text}`, "プラグインの check を直します(ほかの検査は最後まで行いました)", "Fix the plugin's check (all other checks still ran)");
389
+ }
390
+ }
391
+ return out;
392
+ }
393
+
394
+ export function defineCommandPlugin(plugin: CommandPlugin): CommandPlugin {
395
+ return plugin;
396
+ }
397
+
398
+ /**
399
+ * 複数のプラグインの命令をまとめて、仕様と実装にする。プラグインの式の関数(functions)も、検査(@liminalia/lang)と実行器(@liminalia/runtime)に
400
+ * 入れる(前に入れたものと入れ替える。組み込みと同じ名前のものは入れない)。
401
+ */
402
+ export function combinePlugins(plugins: readonly CommandPlugin[]) {
403
+ const commands = plugins.flatMap((p) => p.commands);
404
+ const functions: Record<string, PluginFunction> = {};
405
+ for (const p of plugins) {
406
+ const own = p.functions ?? {};
407
+ Object.assign(functions, own);
408
+ // プラグインごとに入れ替える(ほかの呼び出しで入れたプラグインの関数は残す)
409
+ const clash = new Set(setPluginFunctions(p.name, Object.fromEntries(Object.entries(own).map(([name, f]) => [name, arityOf(f)]))));
410
+ setPluginFunctionImpls(p.name, Object.fromEntries(Object.entries(own).filter(([name]) => !clash.has(name)).map(([name, f]) => [name, (args: Value[], env: { random(): number }) => f.run(args, env)])));
411
+ }
412
+ return {
413
+ commands,
414
+ specs: commands.map(toSpec),
415
+ implementations: commands.map(toImplementation),
416
+ functions,
417
+ };
418
+ }
419
+
420
+ /** 関数の引数の数を [最小, 最大] にする。 */
421
+ function arityOf(f: PluginFunction): readonly [number, number] {
422
+ if (typeof f.args === "number") return [f.args, f.args];
423
+ return [f.args[0], f.args[1]];
424
+ }