@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 skyta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,85 @@
1
+ import { SKIP_PARAM } from "@liminalia/lang";
2
+ export function toSpec(c) {
3
+ const params = {};
4
+ for (const [name, p] of Object.entries(c.params)) {
5
+ const spec = { type: p.type, doc: p.doc };
6
+ if (p.docEn !== undefined)
7
+ spec.docEn = p.docEn;
8
+ if (p.default !== undefined)
9
+ spec.default = p.default;
10
+ if (p.required)
11
+ spec.required = true;
12
+ params[name] = spec;
13
+ }
14
+ const waits = c.waits ?? c.params.wait?.default === "true";
15
+ return { name: c.name, summary: c.summary, ...(c.summaryEn ? { summaryEn: c.summaryEn } : {}), positional: c.positional ?? [], ...(c.bare ? { bare: c.bare } : {}), params, example: c.example, ...(c.exampleEn ? { exampleEn: c.exampleEn } : {}), ...(waits ? { waits } : {}), ...(c.ends ? { ends: true } : {}), ...(c.category ? { category: c.category } : {}), ...(c.keywords?.length ? { keywords: c.keywords } : {}), ...(c.keywordsEn?.length ? { keywordsEn: c.keywordsEn } : {}) };
16
+ }
17
+ export function toImplementation(c) {
18
+ return {
19
+ spec: toSpec(c),
20
+ run: async (args, ctx) => {
21
+ if (c.run)
22
+ return c.run(args, ctx);
23
+ c.apply?.(args, ctx.state.stage.extra);
24
+ await ctx.present(args, typeof args.wait === "boolean" ? args.wait : (c.waits ?? false));
25
+ },
26
+ ...(c.autoplay ? { autoplay: c.autoplay } : {}),
27
+ };
28
+ }
29
+ const withDefault = (p, def) => (def === undefined ? p : { ...p, default: def });
30
+ // 定義を短く書くための部品
31
+ export const t = {
32
+ /** suggest は入力の候補(制作画面で一覧から選べる。ほかの値も書ける)。 */
33
+ string: (doc, def, suggest) => {
34
+ const type = suggest ? { kind: "string", suggest } : { kind: "string" };
35
+ return def === undefined ? { type, doc } : { type, default: def, doc };
36
+ },
37
+ /**
38
+ * プレイヤーに見せる文(章題・テロップ・ダイアログの文など)。多言語の作品では、台本に字面で書いた値が訳のファイル(lim i18n)に
39
+ * 「コマンドの文字」として並び、実行するときに遊んでいる言語の訳に替わる(訳が空なら原文のまま)。
40
+ */
41
+ text: (doc, def) => {
42
+ const type = { kind: "string", translate: "text" };
43
+ return def === undefined ? { type, doc } : { type, default: def, doc };
44
+ },
45
+ /** 人の名前(話者や相手の名前)。多言語の作品では、訳のファイルの speakers に並ぶ(訳して見せるのは命令の実装。ctx.runtime.translator?.speaker)。 */
46
+ name: (doc, def) => {
47
+ const type = { kind: "string", translate: "name" };
48
+ return def === undefined ? { type, doc } : { type, default: def, doc };
49
+ },
50
+ /** 数。range の min・max を書くと、その外の値を lim check が知らせ、制作画面の欄もその幅にする。 */
51
+ number: (doc, def, range = {}) => withDefault({ type: { kind: "number", ...range }, doc }, def),
52
+ /** 整数。range は number と同じ。 */
53
+ int: (doc, def, range = {}) => withDefault({ type: { kind: "int", ...range }, doc }, def),
54
+ bool: (doc, def) => ({ type: { kind: "bool" }, default: String(def), doc }),
55
+ duration: (doc, def) => (def === undefined ? { type: { kind: "duration" }, doc } : { type: { kind: "duration" }, default: def, doc }),
56
+ color: (doc, def) => (def === undefined ? { type: { kind: "color" }, doc } : { type: { kind: "color" }, default: def, doc }),
57
+ enum: (values, doc, def) => def === undefined ? { type: { kind: "enum", values }, doc } : { type: { kind: "enum", values }, default: def, doc },
58
+ /**
59
+ * 素材のパス。cg を付けると、この素材を出したときに CG として解放する(liminalia.json の extra.cg か extra.cgAuto のフォルダにある画像なら。
60
+ * @bg と同じく、台本に @cg-unlock を書かなくてよい。章末の扉絵など、作品の命令で一枚絵を出すときに使う)。
61
+ */
62
+ asset: (folder, doc, o = {}) => ({ type: o.cg ? { kind: "asset", folder, cg: true } : { kind: "asset", folder }, doc }),
63
+ required: (p) => ({ ...p, required: true }),
64
+ /** 値を入れる変数(`game.x`・`system.x`・`temp.x`)。命令の結果を受け取るときに。lim check が書き方を確かめ、値を入れる変数として数える。 */
65
+ variable: (doc, def) => withDefault({ type: { kind: "variable" }, doc }, def),
66
+ /** 飛び先(`#ラベル`・`ファイル`・`ファイル#ラベル`)。lim check がラベルとファイルの実在を確かめ、制作画面が候補を出し、地図が矢印を引く。 */
67
+ target: (doc, def) => withDefault({ type: { kind: "target" }, doc }, def),
68
+ /**
69
+ * キャストの名前。lim check がキャストにあるかを確かめ、制作画面が一覧から選ばせる。shown を付けると、表示中の立ち絵の人物に効く引数
70
+ * (消す、動かす、揺らす、漫符を付けるなど)として、制作画面の補完がその行で表示中の人物を上に並べる(ほかの人物も候補に残す。検査と実行は変わらない)。
71
+ */
72
+ cast: (doc, def, o = {}) => withDefault({ type: o.shown ? { kind: "cast", shown: true } : { kind: "cast" }, doc }, def),
73
+ /** 条件。必ず式(`(…)`)で書き、実行するときに評価した真偽が渡る(@if と同じ)。 */
74
+ condition: (doc, def) => withDefault({ type: { kind: "condition" }, doc }, def),
75
+ /**
76
+ * 作品のデータの中の名前(file は paths.data の .json、path はその中の辞書か並びへの道。`places`・`maps/town/spots` のように / で区切る)。
77
+ * 辞書なら鍵、並びなら項目の id を名前とみなし、lim check が実在を確かめ、制作画面が候補を出す。
78
+ */
79
+ dataKey: (file, path, doc, def) => withDefault({ type: { kind: "string", data: { file, path } }, doc }, def),
80
+ /**
81
+ * 演出をクリックで終わりまで飛ばせるか(skip。既定 true)。時間のかかる演出を出す命令に付ける。
82
+ * 描画側は何もしなくてよい(Element.animate の動きと ctx.delay の待ちは早送りで終わる。自分で動かす演出は ctx.onFastForward)。
83
+ */
84
+ skip: () => ({ ...SKIP_PARAM }),
85
+ };
@@ -0,0 +1,91 @@
1
+ import { checkData, checkDataFlags, dataCgImages, dataTranslatables, scriptLabels } from "@liminalia/lang";
2
+ const lab = (label) => (typeof label === "string" ? { label } : (label ?? {}));
3
+ export const d = {
4
+ /** 一行の文字。suggest は候補。translate なら遊ぶ人に見せる文で、lim i18n が訳のファイルに並べる(描画は dataText で訳を引く)。 */
5
+ string: (label, o = {}) => ({ kind: "string", ...lab(label), ...o }),
6
+ /** 複数行の文字(本文・説明)。translate は string と同じ。 */
7
+ text: (label, o = {}) => ({ kind: "string", multiline: true, ...lab(label), ...o }),
8
+ number: (label, o = {}) => ({ kind: "number", ...lab(label), ...o }),
9
+ int: (label, o = {}) => ({ kind: "int", ...lab(label), ...o }),
10
+ bool: (label) => ({ kind: "bool", ...lab(label) }),
11
+ enum: (values, label) => ({ kind: "enum", values, ...lab(label) }),
12
+ /**
13
+ * 素材。cg なら、プラグインがこの画像を CG として解放する(どこからも出ない CG の検査がこれを数える)。
14
+ * also は folder に無ければ探すほかのフォルダ(置き場所を替えた欄で、前の場所に置いた素材も読めるように。描画の側も同じ順に探す)。
15
+ */
16
+ asset: (folder, label, o = {}) => ({ kind: "asset", folder, ...lab(label), ...(o.cg ? { cg: true } : {}), ...(o.also?.length ? { also: o.also } : {}) }),
17
+ /** フラグ。use は、このデータでプラグインが立てる(set)か読む(read)か。 */
18
+ flag: (use, label) => ({ kind: "flag", use, ...lab(label) }),
19
+ /** 条件の式。 */
20
+ expr: (label) => ({ kind: "expr", ...lab(label) }),
21
+ cast: (label) => ({ kind: "cast", ...lab(label) }),
22
+ /** 飛び先。base は `#ラベル` のファイルを決める、外側の記録の欄の名前。 */
23
+ scene: (label, o = {}) => ({ kind: "scene", ...lab(label), ...o }),
24
+ file: (label) => ({ kind: "file", ...lab(label) }),
25
+ /** 同じデータの中の名前(to は一覧の欄への道。`/entries`)。 */
26
+ ref: (to, label) => ({ kind: "ref", to, ...lab(label) }),
27
+ /** 背景の上の矩形。image は背景の素材の欄の名前。 */
28
+ rect: (label, o = {}) => ({ kind: "rect", ...lab(label), ...o }),
29
+ /**
30
+ * 絵の上の点({ x, y }。既定は絵の左上からの割合 0〜100、unit が px なら舞台の px)。image は背景の素材の欄の名前(`ref の欄>素材の欄` なら ref が指す項目の欄)。
31
+ * keys を書くと、同じ記録の二つの欄(`["x", "y"]`)に置く(制作画面は絵を出して、押した所と引きずった所に点を置く)。
32
+ */
33
+ point: (label, o = {}) => ({ kind: "point", ...lab(label), ...o }),
34
+ list: (of, label, o = {}) => ({ kind: "list", of, ...lab(label), ...o }),
35
+ record: (fields, label, o = {}) => ({ kind: "record", fields, ...lab(label), ...o }),
36
+ map: (of, label) => ({ kind: "map", of, ...lab(label) }),
37
+ json: (label) => ({ kind: "json", ...lab(label) }),
38
+ /** 必須にする。 */
39
+ required: (f) => ({ ...f, required: true }),
40
+ };
41
+ /** プラグインのデータの宣言(同じファイルは後のプラグインが勝つ)。 */
42
+ export function dataDeclarations(plugins) {
43
+ const byFile = new Map();
44
+ for (const p of plugins)
45
+ for (const decl of p.data ?? [])
46
+ byFile.set(decl.file, decl);
47
+ return [...byFile.values()];
48
+ }
49
+ /** 宣言のあるデータのうち、作品にあるもの。 */
50
+ export function declaredData(plugins, read, text) {
51
+ const out = [];
52
+ for (const decl of dataDeclarations(plugins)) {
53
+ const value = read(decl.file);
54
+ if (value === undefined)
55
+ continue;
56
+ const t = text?.(decl.file);
57
+ out.push({ decl, value, ...(t !== undefined ? { text: t } : {}) });
58
+ }
59
+ return out;
60
+ }
61
+ /** 作品のデータの訳す文(宣言で translate の印の付いた欄。lim i18n と制作画面の訳の画面が updateTranslation の data に渡す)。 */
62
+ export function projectDataTexts(plugins, read) {
63
+ return dataTranslatables(declaredData(plugins, read));
64
+ }
65
+ /** プラグインが作品のデータから CG として解放する画像(`フォルダ/パス`)。checkExtra に渡す。 */
66
+ export function pluginDataCg(plugins, read) {
67
+ return dataCgImages(declaredData(plugins, read));
68
+ }
69
+ /** データの形の検査とフラグの突き合わせ(runPluginChecks が呼ぶ)。 */
70
+ export function checkDeclaredData(plugins, project) {
71
+ const data = declaredData(plugins, (name) => project.data(name), project.dataText ? (name) => project.dataText(name) : undefined);
72
+ if (data.length === 0)
73
+ return [];
74
+ const folder = project.dataFolder ?? "data";
75
+ const fileName = (decl) => `${folder}/${decl.file}`;
76
+ const labels = scriptLabels(project.scripts);
77
+ const cast = new Set(Object.keys(project.cast));
78
+ const owner = new Map();
79
+ for (const p of plugins)
80
+ for (const decl of p.data ?? [])
81
+ owner.set(decl.file, p.name);
82
+ const out = [];
83
+ for (const x of data) {
84
+ const plugin = owner.get(x.decl.file);
85
+ for (const diag of checkData(x.decl, x.value, { fileName: fileName(x.decl), ...(x.text !== undefined ? { text: x.text } : {}), labels, assetExists: project.assetExists, cast }))
86
+ out.push({ ...diag, ...(plugin ? { plugin } : {}) });
87
+ }
88
+ const variables = (project.config.variables ?? undefined);
89
+ out.push(...checkDataFlags(data, project.scripts, project.registry, { fileName, ...(variables ? { variables } : {}) }));
90
+ return out;
91
+ }
@@ -0,0 +1,10 @@
1
+ export { t, toImplementation, toSpec } from "./command.js";
2
+ export { checkDeclaredData, d, dataDeclarations, declaredData, pluginDataCg, projectDataTexts } from "./data.js";
3
+ export { apiSatisfies, checkPluginManifest, combinePlugins, commandArgs, dataKeys, defineCommandPlugin, engineMismatches, PLUGIN_API_VERSION, pluginWrittenVariables, runPluginChecks, undeclaredOverrides } from "./plugin.js";
4
+ export { defineState } from "./state.js";
5
+ // 作品全体の検査(lim check、制作画面、VS Code、MCP が同じ入力から同じ一覧を作る)
6
+ export { packTranslationScope, parsePacks, pluginTargetHooks, projectDiagnostics } from "./project-check.js";
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 } from "@liminalia/lang";
@@ -0,0 +1,364 @@
1
+ import { CORE_COMMANDS, CORE_FUNCTIONS, dataFlagsSet, normalizeBooleanArgs, PLUGIN_API_VERSION, scriptLabels, setPluginFunctions } from "@liminalia/lang";
2
+ import { setPluginFunctionImpls } from "@liminalia/runtime";
3
+ import { toImplementation, toSpec } from "./command.js";
4
+ import { checkDeclaredData, declaredData } from "./data.js";
5
+ export { PLUGIN_API_VERSION };
6
+ /** プラグインが値を入れる変数(宣言 variables)と、作品のデータが立てるフラグ。変数の綴り違いの検査に渡す。 */
7
+ export function pluginWrittenVariables(plugins, read) {
8
+ return [...plugins.flatMap((p) => p.variables ?? []), ...dataFlagsSet(declaredData(plugins, read))];
9
+ }
10
+ const SEVERITIES = new Set(["error", "warning", "info"]);
11
+ /** プラグインの返したものを診断の形にする(形の合わないものは null)。 */
12
+ function pluginDiagnostic(name, d) {
13
+ if (!d || typeof d !== "object" || typeof d.message !== "string" || !SEVERITIES.has(d.severity) || typeof d.code !== "string")
14
+ return null;
15
+ const { file, line, fix, fixes, ...rest } = d;
16
+ const out = { ...rest, file: typeof file === "string" && file !== "" ? file : "liminalia.json", line: typeof line === "number" && line >= 1 ? line : 1, plugin: name };
17
+ // 直し方は形の合うものだけ(制作画面がそのまま当てる)
18
+ if (fix && validFix(fix))
19
+ out.fix = fix;
20
+ const list = Array.isArray(fixes) ? fixes.filter(validFix) : [];
21
+ if (out.fix && !list.some((f) => JSON.stringify(f) === JSON.stringify(out.fix)))
22
+ list.unshift(out.fix);
23
+ if (list.length > 0)
24
+ out.fixes = list;
25
+ return out;
26
+ }
27
+ /** 直し方の形(DiagnosticFix・ProjectFix)か。 */
28
+ function validFix(f) {
29
+ if (!f || typeof f !== "object")
30
+ return false;
31
+ const x = f;
32
+ switch (x.kind) {
33
+ case "delete-line":
34
+ return typeof x.text === "string";
35
+ case "replace":
36
+ return typeof x.find === "string" && x.find !== "" && typeof x.with === "string";
37
+ case "add-speaker":
38
+ return typeof x.name === "string" && x.name !== "";
39
+ case "add-label":
40
+ return typeof x.file === "string" && typeof x.label === "string" && x.label !== "";
41
+ default:
42
+ return false;
43
+ }
44
+ }
45
+ /** 台本の命令の行(@if・@define・@with の中も)。 */
46
+ function* commandsIn(body) {
47
+ for (const s of body) {
48
+ if (s.kind === "command")
49
+ yield { name: s.name, args: s.args, line: s.line };
50
+ else if (s.kind === "if") {
51
+ if (s.with)
52
+ yield { name: s.with.name, args: s.with.args, line: s.line };
53
+ for (const b of s.branches)
54
+ yield* commandsIn(b.body);
55
+ }
56
+ else if (s.kind === "define")
57
+ yield* commandsIn(s.body);
58
+ }
59
+ }
60
+ /**
61
+ * 命令の行の、書いたままの文字の引数(位置引数も名前で引ける。式で書いた引数は入らない)。
62
+ * spec を渡すと、検査と実行器と同じ読み方(normalizeBooleanArgs)にする(名前なしの値を bare の引数に、真偽値の省略形をその名前に当てる)。
63
+ */
64
+ export function commandArgs(args, positional, spec) {
65
+ const out = {};
66
+ let pos = 0;
67
+ for (const a of spec ? normalizeBooleanArgs(spec, args) : args) {
68
+ const key = a.key ?? positional[pos++];
69
+ if (!key)
70
+ continue;
71
+ if (a.value.kind === "string")
72
+ out[key] = a.value.value;
73
+ else if (a.value.kind === "number" || a.value.kind === "bool")
74
+ out[key] = String(a.value.value);
75
+ }
76
+ return out;
77
+ }
78
+ /** 作品のデータの path(/ で区切る)の下の名前(辞書なら鍵、並びなら項目の id)。道が無ければ null。 */
79
+ export function dataKeys(data, path) {
80
+ let v = data;
81
+ for (const part of path.split("/").filter((p) => p !== "")) {
82
+ if (Array.isArray(v))
83
+ v = v.find((x) => x && typeof x === "object" && x.id === part);
84
+ else if (v && typeof v === "object")
85
+ v = v[part];
86
+ else
87
+ return null;
88
+ }
89
+ if (Array.isArray(v))
90
+ return v.flatMap((x) => (x && typeof x === "object" && typeof x.id === "string" ? [x.id] : []));
91
+ if (v && typeof v === "object")
92
+ return Object.keys(v);
93
+ return null;
94
+ }
95
+ /** 命令ごとの検査(validate)と、データの名前の引数(t.dataKey)の実在。 */
96
+ function checkCommandLines(plugins, project, out) {
97
+ const defs = new Map();
98
+ for (const p of plugins)
99
+ for (const c of p.commands)
100
+ defs.set(c.name, { plugin: p.name, def: c });
101
+ const keyed = [...defs.values()].filter(({ def }) => def.validate || Object.values(def.params).some((p) => p.type.kind === "string" && p.type.data));
102
+ if (keyed.length === 0)
103
+ return;
104
+ const folder = project.dataFolder ?? "data";
105
+ let labels = null;
106
+ const targetExists = (file, target) => {
107
+ labels ??= scriptLabels(project.scripts);
108
+ const [f, l] = target.startsWith("#") ? [file, target.slice(1)] : target.split("#");
109
+ const names = labels.get(f);
110
+ return !!names && (l === undefined || l === "" || names.has(l));
111
+ };
112
+ for (const [file, script] of project.scripts) {
113
+ for (const c of commandsIn(script.body)) {
114
+ const found = defs.get(c.name);
115
+ if (!found)
116
+ continue;
117
+ const { plugin, def } = found;
118
+ const args = commandArgs(c.args, def.positional ?? [], toSpec(def));
119
+ // データの名前(t.dataKey)
120
+ for (const [param, p] of Object.entries(def.params)) {
121
+ const where = p.type.kind === "string" ? p.type.data : undefined;
122
+ const value = args[param];
123
+ if (!where || value === undefined)
124
+ continue;
125
+ const data = project.data(where.file);
126
+ const keys = dataKeys(data, where.path);
127
+ const at = `${folder}/${where.file}`;
128
+ if (data === undefined)
129
+ 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)` });
130
+ else if (keys === null)
131
+ 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 });
132
+ else if (!keys.includes(value))
133
+ 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 ? " …" : ""}` } : {}) });
134
+ }
135
+ if (!def.validate)
136
+ continue;
137
+ try {
138
+ const result = def.validate(args, {
139
+ file,
140
+ line: c.line,
141
+ data: (name) => project.data(name),
142
+ assetExists: (f, path) => project.assetExists(f, path),
143
+ isCast: (name) => Object.hasOwn(project.cast, name),
144
+ targetExists: (target) => targetExists(file, target),
145
+ });
146
+ if (result === undefined)
147
+ continue;
148
+ if (!Array.isArray(result))
149
+ throw new Error("validate が診断の配列を返しませんでした");
150
+ for (const item of result) {
151
+ const d = pluginDiagnostic(plugin, { ...item, file: item.file ?? file, line: item.line ?? c.line });
152
+ if (d)
153
+ out.push(d);
154
+ else
155
+ 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 });
156
+ }
157
+ }
158
+ catch (e) {
159
+ const text = e instanceof Error ? e.message : String(e);
160
+ 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 });
161
+ }
162
+ }
163
+ }
164
+ }
165
+ /** プラグインの口の版(apiVersion)と式の関数の名前。 */
166
+ function checkPluginApi(plugins, out) {
167
+ const builtIn = CORE_FUNCTIONS;
168
+ for (const p of plugins) {
169
+ if (typeof p.apiVersion === "number" && p.apiVersion > PLUGIN_API_VERSION) {
170
+ out.push({
171
+ severity: "warning",
172
+ code: "plugin-api-version",
173
+ message: `プラグイン ${p.name} はプラグイン API バージョン ${p.apiVersion} 向けで、このエンジン(バージョン ${PLUGIN_API_VERSION})より新しい API を使います`,
174
+ messageEn: `The plugin ${p.name} targets plugin API version ${p.apiVersion}, newer than this engine's (${PLUGIN_API_VERSION})`,
175
+ file: "liminalia.json",
176
+ line: 1,
177
+ hint: "Liminalia を新しいバージョンに更新するか、このエンジンに対応するバージョンのプラグインを入れます",
178
+ hintEn: "Update Liminalia, or install a version of the plugin made for this engine",
179
+ plugin: p.name,
180
+ });
181
+ }
182
+ for (const name of Object.keys(p.functions ?? {})) {
183
+ if (!builtIn.has(name))
184
+ continue;
185
+ 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 });
186
+ }
187
+ }
188
+ }
189
+ /**
190
+ * 合うエンジンの宣言(liminalia.api: 要る口の版、engines.liminalia: 合う口の版の範囲)のうち、このエンジンの口の版(PLUGIN_API_VERSION)に
191
+ * 合わないもの("3"、">=3" など、書いたままの形)。合えば、宣言が無ければ、読めなければ空。
192
+ * プラグインの package.json、テーマの theme.json、作品とひな形の liminalia.json で同じ形を読む。
193
+ */
194
+ export function engineMismatches(manifest, version = PLUGIN_API_VERSION) {
195
+ if (!manifest || typeof manifest !== "object")
196
+ return [];
197
+ const m = manifest;
198
+ const out = [];
199
+ const api = m.liminalia?.api;
200
+ if (typeof api === "number" && api > version)
201
+ out.push(String(api));
202
+ const range = m.engines?.liminalia;
203
+ if (typeof range === "string" && range.trim() !== "" && !apiSatisfies(version, range))
204
+ out.push(range.trim());
205
+ return out;
206
+ }
207
+ /**
208
+ * プラグインの package.json の宣言(liminalia.api: 要るプラグインの口の版、engines.liminalia: 合うプラグインの口の版の範囲)を、このエンジンと比べる。
209
+ * spec は liminalia.json の plugins に書いた形(診断に出す)。合わなければ警告(plugin-engine-version)。
210
+ */
211
+ export function checkPluginManifest(spec, manifest) {
212
+ return engineMismatches(manifest).map((need) => ({
213
+ severity: "warning",
214
+ code: "plugin-engine-version",
215
+ message: `プラグイン ${spec} はプラグイン API バージョン ${need} 向けのため、このエンジン(バージョン ${PLUGIN_API_VERSION})では動かないことがあります`,
216
+ messageEn: `The plugin ${spec} needs plugin API version ${need}, but this engine provides version ${PLUGIN_API_VERSION}; it may not work`,
217
+ file: "liminalia.json",
218
+ line: 1,
219
+ hint: "Liminalia を新しいバージョンに更新するか、このエンジンに対応するバージョンのプラグインを入れます",
220
+ hintEn: "Update Liminalia, or install a version of the plugin made for this engine",
221
+ plugin: spec,
222
+ }));
223
+ }
224
+ /**
225
+ * プラグインの口の版 version が範囲 range に入るか。`2`、`>=2`、`>2`、`<=3`、`<3`、`^2`(2 以上 3 未満)、`2 - 4`、`*`、
226
+ * 空白区切り(すべて満たす)と `||`(どれか)を読む。読めない範囲は入るとみなす(知らない書き方で止めない)。
227
+ */
228
+ export function apiSatisfies(version, range) {
229
+ return range.split("||").some((alt) => {
230
+ const part = alt.trim();
231
+ if (part === "" || part === "*" || part === "x")
232
+ return true;
233
+ const hyphen = /^(\d+)(?:\.[\dx*]+)*\s+-\s+(\d+)(?:\.[\dx*]+)*$/.exec(part);
234
+ if (hyphen)
235
+ return version >= Number(hyphen[1]) && version <= Number(hyphen[2]);
236
+ return part.split(/\s+/).every((c) => {
237
+ const m = /^(>=|<=|>|<|=|\^|~)?v?(\d+)(?:\.[\dx*]+)*$/.exec(c);
238
+ if (!m)
239
+ return true;
240
+ const n = Number(m[2]);
241
+ switch (m[1]) {
242
+ case ">=":
243
+ return version >= n;
244
+ case "<=":
245
+ return version <= n;
246
+ case ">":
247
+ return version > n;
248
+ case "<":
249
+ return version < n;
250
+ case "^":
251
+ case "~":
252
+ case "=":
253
+ case undefined:
254
+ return version === n;
255
+ default:
256
+ return true;
257
+ }
258
+ });
259
+ });
260
+ }
261
+ /**
262
+ * 組み込みの命令か、先に読んだプラグインの同じ名前の命令を、宣言(replaces: true)なしに上書きしている命令。後に読んだプラグインの命令が使われる
263
+ * (combinePlugins と実行器)。over は上書きされた側(組み込みならエンジン、そうでなければそのプラグインの名前)。
264
+ */
265
+ export function undeclaredOverrides(plugins, builtIn = CORE_COMMANDS.map((c) => c.name)) {
266
+ const owner = new Map();
267
+ for (const name of builtIn)
268
+ owner.set(name, null);
269
+ const out = [];
270
+ for (const p of plugins) {
271
+ for (const c of p.commands) {
272
+ if (owner.has(c.name) && !c.replaces && owner.get(c.name) !== p.name)
273
+ out.push({ plugin: p.name, name: c.name, over: owner.get(c.name) });
274
+ owner.set(c.name, p.name);
275
+ }
276
+ }
277
+ return out;
278
+ }
279
+ /** プラグインの check を順に呼ぶ。投げたもの・形の合わないものは、チェック全体を止めずにそのプラグインの診断にする。 */
280
+ export function runPluginChecks(plugins, project) {
281
+ const out = [];
282
+ // 宣言なしの上書き(標準の命令が増えて、作品のプラグインの命令と名前がぶつかったときなど)
283
+ for (const o of undeclaredOverrides(plugins)) {
284
+ const over = o.over === null ? "組み込み" : o.over;
285
+ const overEn = o.over === null ? "the built-in" : o.over;
286
+ out.push({
287
+ severity: "warning",
288
+ code: "plugin-replaces-command",
289
+ message: `プラグイン ${o.plugin} の @${o.name} が、${over} の @${o.name} を上書きしています(置き換えの宣言がありません)`,
290
+ messageEn: `The plugin ${o.plugin}'s @${o.name} overrides ${overEn} @${o.name} (it doesn't declare that it replaces it)`,
291
+ file: "liminalia.json",
292
+ line: 1,
293
+ hint: `置き換えるつもりなら、命令の定義に replaces: true を書きます。そうでなければ命令の名前を変えます`,
294
+ hintEn: "If it's meant to replace it, add replaces: true to the command definition. Otherwise rename the command",
295
+ plugin: o.plugin,
296
+ });
297
+ }
298
+ const problem = (name, code, message, messageEn, hint, hintEn) => out.push({ severity: "error", code, message, messageEn, file: "liminalia.json", line: 1, hint, hintEn, plugin: name });
299
+ // プラグインの口の版と、式の関数の名前
300
+ checkPluginApi(plugins, out);
301
+ // 命令ごとの検査(validate)とデータの名前の引数(t.dataKey)
302
+ checkCommandLines(plugins, project, out);
303
+ // データの形の宣言(data)の検査。投げても全体のチェックは止めない
304
+ try {
305
+ out.push(...checkDeclaredData(plugins, project));
306
+ }
307
+ catch (e) {
308
+ const text = e instanceof Error ? e.message : String(e);
309
+ problem("data", "plugin-check-failed", `データの形の検査が失敗しました: ${text}`, `Checking the declared data failed: ${text}`, "データの宣言を直します(ほかの検査は最後まで行いました)", "Fix the data declarations (all other checks still ran)");
310
+ }
311
+ for (const p of plugins) {
312
+ if (!p.check)
313
+ continue;
314
+ try {
315
+ const result = p.check(project);
316
+ if (!Array.isArray(result)) {
317
+ 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");
318
+ continue;
319
+ }
320
+ for (const item of result) {
321
+ const d = pluginDiagnostic(p.name, item);
322
+ if (d)
323
+ out.push(d);
324
+ else
325
+ 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");
326
+ }
327
+ }
328
+ catch (e) {
329
+ const text = e instanceof Error ? e.message : String(e);
330
+ 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)");
331
+ }
332
+ }
333
+ return out;
334
+ }
335
+ export function defineCommandPlugin(plugin) {
336
+ return plugin;
337
+ }
338
+ /**
339
+ * 複数のプラグインの命令をまとめて、仕様と実装にする。プラグインの式の関数(functions)も、検査(@liminalia/lang)と実行器(@liminalia/runtime)に
340
+ * 入れる(前に入れたものと入れ替える。組み込みと同じ名前のものは入れない)。
341
+ */
342
+ export function combinePlugins(plugins) {
343
+ const commands = plugins.flatMap((p) => p.commands);
344
+ const functions = {};
345
+ for (const p of plugins) {
346
+ const own = p.functions ?? {};
347
+ Object.assign(functions, own);
348
+ // プラグインごとに入れ替える(ほかの呼び出しで入れたプラグインの関数は残す)
349
+ const clash = new Set(setPluginFunctions(p.name, Object.fromEntries(Object.entries(own).map(([name, f]) => [name, arityOf(f)]))));
350
+ setPluginFunctionImpls(p.name, Object.fromEntries(Object.entries(own).filter(([name]) => !clash.has(name)).map(([name, f]) => [name, (args, env) => f.run(args, env)])));
351
+ }
352
+ return {
353
+ commands,
354
+ specs: commands.map(toSpec),
355
+ implementations: commands.map(toImplementation),
356
+ functions,
357
+ };
358
+ }
359
+ /** 関数の引数の数を [最小, 最大] にする。 */
360
+ function arityOf(f) {
361
+ if (typeof f.args === "number")
362
+ return [f.args, f.args];
363
+ return [f.args[0], f.args[1]];
364
+ }