@yutaura/live-spec 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +12 -0
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/dist/cli.d.ts +20 -0
- package/dist/cli.js +180 -0
- package/dist/diff.d.ts +33 -0
- package/dist/diff.js +141 -0
- package/dist/ensure.d.ts +5 -0
- package/dist/ensure.js +10 -0
- package/dist/explore.d.ts +6 -0
- package/dist/explore.js +270 -0
- package/dist/generate.d.ts +15 -0
- package/dist/generate.js +147 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/load.d.ts +52 -0
- package/dist/load.js +74 -0
- package/dist/model.d.ts +402 -0
- package/dist/model.js +175 -0
- package/dist/render/collapse.d.ts +4 -0
- package/dist/render/collapse.js +22 -0
- package/dist/render/escape.d.ts +1 -0
- package/dist/render/escape.js +2 -0
- package/dist/render/html.d.ts +12 -0
- package/dist/render/html.js +685 -0
- package/dist/render/layout.d.ts +37 -0
- package/dist/render/layout.js +74 -0
- package/dist/render/markdown.d.ts +20 -0
- package/dist/render/markdown.js +227 -0
- package/dist/render/summary.d.ts +62 -0
- package/dist/render/summary.js +119 -0
- package/dist/render/wireframe.d.ts +3 -0
- package/dist/render/wireframe.js +62 -0
- package/dist/serve.d.ts +8 -0
- package/dist/serve.js +71 -0
- package/dist/skills.d.ts +8 -0
- package/dist/skills.js +20 -0
- package/dist/static.d.ts +10 -0
- package/dist/static.js +117 -0
- package/dist/surface.d.ts +59 -0
- package/dist/surface.js +44 -0
- package/dist/watch.d.ts +10 -0
- package/dist/watch.js +47 -0
- package/package.json +54 -4
- package/skills/live-spec-authoring/SKILL.md +160 -0
- package/skills/live-spec-from-code/SKILL.md +93 -0
- package/skills/live-spec-review/SKILL.md +65 -0
package/dist/explore.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { isNotAllowed } from "./ensure.js";
|
|
2
|
+
import { canonical } from "./model.js";
|
|
3
|
+
import { buttonsOf } from "./surface.js";
|
|
4
|
+
const DEFAULT_MAX_STATES = 500;
|
|
5
|
+
const run = (fn, state, actor, args) => {
|
|
6
|
+
try {
|
|
7
|
+
// structuredClone を渡す理由: 関数が引数を破壊的に変更しても、探索済みの状態が壊れないようにするため。
|
|
8
|
+
const next = fn(structuredClone(state), structuredClone(actor), ...structuredClone(args));
|
|
9
|
+
if (typeof next !== "object" || next === null || Array.isArray(next))
|
|
10
|
+
return { kind: "invalid-return" };
|
|
11
|
+
return { kind: "ok", next: canonical(next) };
|
|
12
|
+
}
|
|
13
|
+
catch (e) {
|
|
14
|
+
if (isNotAllowed(e))
|
|
15
|
+
return { kind: "not-allowed", reason: e.message };
|
|
16
|
+
return { kind: "error", message: e instanceof Error ? e.message : String(e) };
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
// 例外を違反として扱う理由: 不変条件の関数が想定外の状態で落ちること自体が、
|
|
20
|
+
// その状態が書き手の想定を外れている(=不変条件を満たすと言えない)ことを示すため。
|
|
21
|
+
const invariantHolds = (holds, values) => {
|
|
22
|
+
try {
|
|
23
|
+
return Boolean(holds(structuredClone(values)));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
export const explore = (spec, options = {}) => {
|
|
30
|
+
const maxStates = options.maxStates ?? DEFAULT_MAX_STATES;
|
|
31
|
+
const ids = new Map();
|
|
32
|
+
const valuesById = new Map();
|
|
33
|
+
const queue = [];
|
|
34
|
+
const parents = new Map();
|
|
35
|
+
const violations = [];
|
|
36
|
+
const register = (values, via) => {
|
|
37
|
+
const key = JSON.stringify(values);
|
|
38
|
+
const known = ids.get(key);
|
|
39
|
+
if (known !== undefined)
|
|
40
|
+
return known;
|
|
41
|
+
if (ids.size >= maxStates)
|
|
42
|
+
return undefined;
|
|
43
|
+
const id = `s${ids.size}`;
|
|
44
|
+
ids.set(key, id);
|
|
45
|
+
valuesById.set(id, values);
|
|
46
|
+
queue.push(id);
|
|
47
|
+
if (via !== undefined)
|
|
48
|
+
parents.set(id, via);
|
|
49
|
+
for (const [invariant, holds] of spec.invariants) {
|
|
50
|
+
if (!invariantHolds(holds, values))
|
|
51
|
+
violations.push({ invariant, state: id });
|
|
52
|
+
}
|
|
53
|
+
return id;
|
|
54
|
+
};
|
|
55
|
+
// 幅優先探索で最初に見つけた親をたどるので、得られる手順は初期状態からの最短手順になる。
|
|
56
|
+
const pathTo = (id) => {
|
|
57
|
+
const steps = [];
|
|
58
|
+
for (let p = parents.get(id); p !== undefined; p = parents.get(p.from))
|
|
59
|
+
steps.unshift({ action: p.action, actor: p.actor });
|
|
60
|
+
return steps;
|
|
61
|
+
};
|
|
62
|
+
const transitions = new Map();
|
|
63
|
+
const availability = [];
|
|
64
|
+
const findings = [];
|
|
65
|
+
const processed = new Set();
|
|
66
|
+
// 3 つ目以降の引数がある操作は、inputs に例がなければ実行しない。
|
|
67
|
+
// undefined を渡して実行すると TypeError などが「仕様のバグ」として大量に出て、本当の原因が埋もれるため。
|
|
68
|
+
const missingInputs = spec.actions.filter(([name, fn]) => fn.length > 2 && spec.inputs[name] === undefined).map(([name]) => name);
|
|
69
|
+
const runnable = spec.actions.filter(([name]) => !missingInputs.includes(name));
|
|
70
|
+
const NO_INPUT = [[null, []]];
|
|
71
|
+
register(canonical(spec.initial));
|
|
72
|
+
// 幅優先探索の理由: 状態 ID と表の行の並びを「初期状態からの近さ」順に固定し、
|
|
73
|
+
// spec の書き換えで出力の順序が揺れないようにするため(差分レビューの前提)。
|
|
74
|
+
explore: for (let i = 0; i < queue.length; i++) {
|
|
75
|
+
const from = queue[i];
|
|
76
|
+
const values = valuesById.get(from);
|
|
77
|
+
for (const [action, fn] of runnable) {
|
|
78
|
+
for (const [actor, actorValue] of spec.actors) {
|
|
79
|
+
for (const [input, args] of spec.inputs[action] ?? NO_INPUT) {
|
|
80
|
+
const outcome = run(fn, values, actorValue, args);
|
|
81
|
+
if (outcome.kind !== "ok") {
|
|
82
|
+
if (outcome.kind === "error")
|
|
83
|
+
findings.push({ kind: "action-error", action, actor, state: from, message: outcome.message });
|
|
84
|
+
if (outcome.kind === "invalid-return")
|
|
85
|
+
findings.push({ kind: "invalid-return", action, actor, state: from });
|
|
86
|
+
const reason = outcome.kind === "not-allowed" ? outcome.reason : null;
|
|
87
|
+
availability.push({ state: from, action, actor, input, enabled: false, to: null, reason });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const to = register(outcome.next, { from, action, actor });
|
|
91
|
+
if (to === undefined) {
|
|
92
|
+
findings.push({ kind: "state-limit", maxStates });
|
|
93
|
+
break explore;
|
|
94
|
+
}
|
|
95
|
+
availability.push({ state: from, action, actor, input, enabled: true, to, reason: null });
|
|
96
|
+
const key = `${from}|${action}|${to}`;
|
|
97
|
+
const t = transitions.get(key) ?? { from, to, action, actors: [] };
|
|
98
|
+
if (!t.actors.includes(actor))
|
|
99
|
+
t.actors.push(actor);
|
|
100
|
+
transitions.set(key, t);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
processed.add(from);
|
|
105
|
+
}
|
|
106
|
+
const labelOf = labeler([...valuesById.values()]);
|
|
107
|
+
const states = [...valuesById.entries()].map(([id, values]) => ({
|
|
108
|
+
id,
|
|
109
|
+
label: labelOf(values),
|
|
110
|
+
values,
|
|
111
|
+
initial: id === "s0",
|
|
112
|
+
terminal: processed.has(id) && !availability.some((a) => a.state === id && a.enabled),
|
|
113
|
+
}));
|
|
114
|
+
for (const v of violations)
|
|
115
|
+
findings.push({ kind: "invariant-violation", ...v, path: pathTo(v.state) });
|
|
116
|
+
for (const [field, values] of Object.entries(spec.fields)) {
|
|
117
|
+
for (const value of values) {
|
|
118
|
+
if (!states.some((s) => s.values[field] === value))
|
|
119
|
+
findings.push({ kind: "unreachable-value", field, value });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
for (const action of missingInputs)
|
|
123
|
+
findings.push({ kind: "missing-inputs", action });
|
|
124
|
+
for (const action of Object.keys(spec.inputs)) {
|
|
125
|
+
if (!spec.actions.some(([name]) => name === action))
|
|
126
|
+
findings.push({ kind: "unknown-inputs", action });
|
|
127
|
+
}
|
|
128
|
+
for (const [action] of runnable) {
|
|
129
|
+
if (!availability.some((a) => a.action === action && a.enabled))
|
|
130
|
+
findings.push({ kind: "never-enabled-action", action });
|
|
131
|
+
}
|
|
132
|
+
const surfaces = spec.surface === null ? [] : checkSurfaces(spec.surface, spec, [...processed], valuesById, availability, findings);
|
|
133
|
+
const scenarios = runScenarios(spec, (values) => ids.get(JSON.stringify(values)) ?? null, findings);
|
|
134
|
+
const questions = spec.questions.map((q) => {
|
|
135
|
+
const about = q.about;
|
|
136
|
+
const action = typeof about === "function" ? about.name : null;
|
|
137
|
+
const matched = about === undefined || typeof about === "function"
|
|
138
|
+
? []
|
|
139
|
+
: states
|
|
140
|
+
.filter((s) => Object.entries(about).every(([k, v]) => JSON.stringify(canonical(v)) === JSON.stringify(s.values[k])))
|
|
141
|
+
.map((s) => s.id);
|
|
142
|
+
if (about !== undefined && typeof about !== "function" && matched.length === 0)
|
|
143
|
+
findings.push({ kind: "question-unmatched", ask: q.ask });
|
|
144
|
+
return { ask: q.ask, note: q.note ?? null, action, states: matched };
|
|
145
|
+
});
|
|
146
|
+
const decisions = spec.decisions.map(([name, d]) => {
|
|
147
|
+
const columns = [...new Set(d.cases.flatMap((c) => (typeof c.input === "object" && c.input !== null ? Object.keys(c.input) : ["入力"])))];
|
|
148
|
+
const rows = d.cases.map((c, i) => {
|
|
149
|
+
let result;
|
|
150
|
+
try {
|
|
151
|
+
result = d.decide(structuredClone(c.input));
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
findings.push({ kind: "decision-error", decision: name, row: i + 1, message: e instanceof Error ? e.message : String(e) });
|
|
155
|
+
return { input: c.input, result: null, expect: c.expect ?? null, ok: false };
|
|
156
|
+
}
|
|
157
|
+
const ok = !("expect" in c) || JSON.stringify(canonical(c.expect)) === JSON.stringify(canonical(result));
|
|
158
|
+
if (!ok)
|
|
159
|
+
findings.push({ kind: "decision-mismatch", decision: name, row: i + 1, expected: show(c.expect), actual: show(result) });
|
|
160
|
+
return { input: c.input, result, expect: "expect" in c ? c.expect : null, ok };
|
|
161
|
+
});
|
|
162
|
+
return { name, columns, rows };
|
|
163
|
+
});
|
|
164
|
+
const links = spec.links.map((l) => ({ from: l.from?.name ?? null, to: l.to, action: l.action ?? null, label: l.label }));
|
|
165
|
+
return { states, transitions: [...transitions.values()], availability, findings, surfaces, decisions, links, questions, scenarios };
|
|
166
|
+
};
|
|
167
|
+
const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
|
|
168
|
+
// シナリオは探索とは別に、初期状態から手順どおりに実行する。探索は「到達できるか」を確かめるが、
|
|
169
|
+
// シナリオは「この業務の流れが、この順番で通るか」を名指しで確かめる(受け入れテストの役割)。
|
|
170
|
+
const runScenarios = (spec, idOf, findings) => spec.scenarios.map(([name, steps]) => {
|
|
171
|
+
let values = canonical(spec.initial);
|
|
172
|
+
const records = [];
|
|
173
|
+
for (const [i, step] of steps.entries()) {
|
|
174
|
+
const action = step.do.name;
|
|
175
|
+
const fail = (reason) => {
|
|
176
|
+
records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: null, ok: false, reason });
|
|
177
|
+
findings.push({ kind: "scenario-failed", scenario: name, step: i + 1, reason });
|
|
178
|
+
};
|
|
179
|
+
const actor = spec.actors.find(([n]) => n === step.by);
|
|
180
|
+
if (actor === undefined) {
|
|
181
|
+
fail(`登場人物「${step.by}」は actors にない`);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
if (!spec.actions.some(([n]) => n === action)) {
|
|
185
|
+
fail(`操作「${action}」はこの spec にない`);
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
const examples = spec.inputs[action];
|
|
189
|
+
const args = step.input === undefined ? [] : examples?.find(([label]) => label === step.input)?.[1];
|
|
190
|
+
if (args === undefined) {
|
|
191
|
+
fail(`入力の例「${step.input}」は inputs にない`);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
if (step.input === undefined && step.do.length > 2) {
|
|
195
|
+
fail("この操作には入力の例(input)を指定する");
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
const outcome = run(step.do, values, actor[1], args);
|
|
199
|
+
if (outcome.kind !== "ok") {
|
|
200
|
+
fail(outcome.kind === "not-allowed" ? outcome.reason : outcome.kind === "error" ? `例外: ${outcome.message}` : "オブジェクトを返さなかった");
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
const mismatch = Object.entries(step.expect ?? {}).find(([k, v]) => JSON.stringify(canonical(v)) !== JSON.stringify(outcome.next[k]));
|
|
204
|
+
if (mismatch !== undefined) {
|
|
205
|
+
const [k, v] = mismatch;
|
|
206
|
+
fail(`期待: ${k} = ${show(v)}、実際: ${k} = ${show(outcome.next[k])}`);
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: idOf(outcome.next), ok: true, reason: null });
|
|
210
|
+
values = outcome.next;
|
|
211
|
+
}
|
|
212
|
+
return { name, passed: records.length === steps.length && records.every((r) => r.ok), steps: records };
|
|
213
|
+
});
|
|
214
|
+
// 画面のボタンと探索の結果を突き合わせる。画面と状態遷移が同じ spec から作られているので、
|
|
215
|
+
// 「押しても実行できないボタン」「実行できるのに画面から辿れない操作」を機械的に見つけられる。
|
|
216
|
+
const checkSurfaces = (surface, spec, states, valuesById, availability, findings) => {
|
|
217
|
+
const result = [];
|
|
218
|
+
for (const state of states) {
|
|
219
|
+
for (const [actor, actorValue] of spec.actors) {
|
|
220
|
+
let node;
|
|
221
|
+
try {
|
|
222
|
+
node = surface(structuredClone(valuesById.get(state)), structuredClone(actorValue));
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
findings.push({ kind: "surface-error", state, actor, message: e instanceof Error ? e.message : String(e) });
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
// null は「この人に見える画面はない」(API を呼ばないワーカーなど)。記録も検査もしない。
|
|
229
|
+
if (node === null || node === undefined)
|
|
230
|
+
continue;
|
|
231
|
+
result.push({ state, actor, surface: node });
|
|
232
|
+
const allowed = new Set(availability.filter((a) => a.state === state && a.actor === actor && a.enabled).map((a) => a.action));
|
|
233
|
+
const buttons = buttonsOf(node).filter((b) => b.action !== undefined);
|
|
234
|
+
const shown = new Set(buttons.filter((b) => b.disabled !== true).map((b) => b.action));
|
|
235
|
+
for (const action of shown) {
|
|
236
|
+
if (!allowed.has(action))
|
|
237
|
+
findings.push({ kind: "surface-action-not-allowed", state, actor, action });
|
|
238
|
+
}
|
|
239
|
+
// ボタンの欠落を確かめるのは UI の画面(ui.screen)だけ。API の応答や CLI の出力には
|
|
240
|
+
// ボタンという概念がないので、操作に対応する要素がなくても欠落とは言えない。
|
|
241
|
+
if (node.kind !== "screen")
|
|
242
|
+
continue;
|
|
243
|
+
for (const action of allowed) {
|
|
244
|
+
if (!shown.has(action))
|
|
245
|
+
findings.push({ kind: "surface-action-missing", state, actor, action });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return result;
|
|
250
|
+
};
|
|
251
|
+
// ラベルに「状態によって値が変わる項目」だけを使う理由: authorId のように
|
|
252
|
+
// どの状態でも同じ値の項目まで並べると、状態を区別する情報が埋もれるため。
|
|
253
|
+
// 文字列の項目を先に並べるのは、status のような主たる区分を先頭に見せるため。
|
|
254
|
+
const labeler = (all) => {
|
|
255
|
+
const keys = [...new Set(all.flatMap((v) => Object.keys(v)))]
|
|
256
|
+
.filter((k) => new Set(all.map((v) => JSON.stringify(v[k]))).size > 1)
|
|
257
|
+
.sort((a, b) => rank(all[0][a]) - rank(all[0][b]) || a.localeCompare(b));
|
|
258
|
+
return (values) => {
|
|
259
|
+
const parts = keys.flatMap((k) => {
|
|
260
|
+
const v = values[k];
|
|
261
|
+
if (typeof v === "string")
|
|
262
|
+
return [v];
|
|
263
|
+
if (typeof v === "boolean")
|
|
264
|
+
return v ? [k] : [];
|
|
265
|
+
return [`${k}=${JSON.stringify(v)}`];
|
|
266
|
+
});
|
|
267
|
+
return parts.length > 0 ? parts.join(" · ") : "初期状態";
|
|
268
|
+
};
|
|
269
|
+
};
|
|
270
|
+
const rank = (v) => (typeof v === "string" ? 0 : typeof v === "boolean" ? 1 : 2);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type OutputFormat = "markdown" | "json" | "html";
|
|
2
|
+
export type Output = {
|
|
3
|
+
readonly kind: "text";
|
|
4
|
+
readonly content: string;
|
|
5
|
+
} | {
|
|
6
|
+
readonly kind: "files";
|
|
7
|
+
readonly files: Readonly<Record<string, string>>;
|
|
8
|
+
};
|
|
9
|
+
export declare const specNameOf: (path: string) => string;
|
|
10
|
+
export declare const expandSpecPaths: (paths: ReadonlyArray<string>) => Array<string>;
|
|
11
|
+
export declare const generateProject: (paths: ReadonlyArray<string>, format: OutputFormat, title?: string) => Promise<Output>;
|
|
12
|
+
export declare const failureOutput: (format: OutputFormat, paths: ReadonlyArray<string>, error: unknown) => Output;
|
|
13
|
+
export declare const generate: (path: string, format: OutputFormat) => Promise<string>;
|
|
14
|
+
export declare const writeOutput: (out: string, content: string) => Promise<void>;
|
|
15
|
+
export declare const writeProjectOutput: (out: string, output: Output) => Promise<void>;
|
package/dist/generate.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
10
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
11
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
12
|
+
import { pathToFileURL } from "node:url";
|
|
13
|
+
import { explore } from "./explore.js";
|
|
14
|
+
import { loadSpec } from "./load.js";
|
|
15
|
+
import { normalize } from "./model.js";
|
|
16
|
+
import { renderErrorHtml, renderProjectHtml } from "./render/html.js";
|
|
17
|
+
import { renderIndexMarkdown, renderMarkdown } from "./render/markdown.js";
|
|
18
|
+
export const specNameOf = (path) => basename(path).replace(/(\.spec)?\.[cm]?ts$/, "");
|
|
19
|
+
// ディレクトリを渡せるようにする理由: 1 つの spec ファイルを 1 つのドメインオブジェクトとして扱うので、
|
|
20
|
+
// プロジェクトの仕様は複数のファイルになる。specs/ のようなディレクトリをまとめて渡せる方が自然。
|
|
21
|
+
export const expandSpecPaths = (paths) => paths.flatMap((p) => {
|
|
22
|
+
let isDir = false;
|
|
23
|
+
try {
|
|
24
|
+
isDir = statSync(p).isDirectory();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return [p];
|
|
28
|
+
}
|
|
29
|
+
if (!isDir)
|
|
30
|
+
return [p];
|
|
31
|
+
return readdirSync(p, { recursive: true })
|
|
32
|
+
.filter((f) => f.endsWith(".spec.ts") && !basename(f).startsWith("."))
|
|
33
|
+
.sort()
|
|
34
|
+
.map((f) => join(p, f));
|
|
35
|
+
});
|
|
36
|
+
// import のたびにクエリを変える理由: ESM は同じ URL のモジュールをキャッシュするので、
|
|
37
|
+
// --watch で spec を読み直しても古い内容のまま生成されてしまう。クエリが違えば別モジュールとして読み込まれる。
|
|
38
|
+
// spec から import しているファイル(共通の型など)は読み直されない点に注意。
|
|
39
|
+
let importVersion = 0;
|
|
40
|
+
const loadObject = async (path) => {
|
|
41
|
+
const url = pathToFileURL(resolve(path));
|
|
42
|
+
url.search = `?v=${++importVersion}`;
|
|
43
|
+
const mod = (await import(__rewriteRelativeImportExtension(url.href)));
|
|
44
|
+
const spec = loadSpec(specNameOf(path), mod, { source: await readFile(path, "utf8") });
|
|
45
|
+
return { spec, graph: explore(spec) };
|
|
46
|
+
};
|
|
47
|
+
export const generateProject = async (paths, format, title) => {
|
|
48
|
+
const objects = resolveLinks(await Promise.all(paths.map(loadObject)));
|
|
49
|
+
const names = objects.map((o) => o.spec.name);
|
|
50
|
+
const duplicated = names.find((n, i) => names.indexOf(n) !== i);
|
|
51
|
+
if (duplicated !== undefined)
|
|
52
|
+
throw new Error(`ドメインオブジェクトの名前が重複しています: ${duplicated}(spec のファイル名を変えてください)`);
|
|
53
|
+
const projectTitle = title ?? (objects.length === 1 ? objects[0].spec.name : projectNameOf(paths[0]));
|
|
54
|
+
if (format === "html")
|
|
55
|
+
return { kind: "text", content: await renderProjectHtml(objects, { title: projectTitle }) };
|
|
56
|
+
if (format === "json") {
|
|
57
|
+
const models = objects.map((o) => normalize(o.spec, o.graph));
|
|
58
|
+
return { kind: "text", content: JSON.stringify(models.length === 1 ? models[0] : { objects: models }, null, 2) };
|
|
59
|
+
}
|
|
60
|
+
if (objects.length === 1)
|
|
61
|
+
return { kind: "text", content: renderMarkdown(objects[0].spec, objects[0].graph) };
|
|
62
|
+
return {
|
|
63
|
+
kind: "files",
|
|
64
|
+
files: {
|
|
65
|
+
"README.md": renderIndexMarkdown(objects, projectTitle),
|
|
66
|
+
...Object.fromEntries(objects.map((o) => [`${o.spec.name}.md`, renderMarkdown(o.spec, o.graph, objects)])),
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
// つながりの名前の誤りをプロジェクトを読み込んだ時点で調べる理由: 相手のドメインオブジェクトは別の spec にあり、
|
|
71
|
+
// 1 つの spec を探索するだけでは確かめられないため。spec が 1 つのときは相手がいないので調べない。
|
|
72
|
+
const resolveLinks = (objects) => objects.map((o) => {
|
|
73
|
+
if (objects.length < 2)
|
|
74
|
+
return o;
|
|
75
|
+
const unresolved = o.graph.links.filter((l) => {
|
|
76
|
+
const target = objects.find((t) => t.spec.name === l.to);
|
|
77
|
+
return target === undefined || (l.action !== null && !target.spec.actions.some(([n]) => n === l.action));
|
|
78
|
+
});
|
|
79
|
+
if (unresolved.length === 0)
|
|
80
|
+
return o;
|
|
81
|
+
return {
|
|
82
|
+
spec: o.spec,
|
|
83
|
+
graph: { ...o.graph, findings: [...o.graph.findings, ...unresolved.map((l) => ({ kind: "link-unresolved", to: l.to, action: l.action }))] },
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
// プロジェクトの名前を package.json から取る理由: spec を置くディレクトリは specs/ のような汎用の名前が多く、
|
|
87
|
+
// ディレクトリ名をタイトルにすると、どのプロジェクトの仕様書なのかが分からないため。
|
|
88
|
+
const projectNameOf = (specPath) => {
|
|
89
|
+
for (let dir = dirname(resolve(specPath));; dir = dirname(dir)) {
|
|
90
|
+
const pkg = join(dir, "package.json");
|
|
91
|
+
if (existsSync(pkg)) {
|
|
92
|
+
try {
|
|
93
|
+
const name = JSON.parse(readFileSync(pkg, "utf8")).name;
|
|
94
|
+
if (typeof name === "string" && name !== "")
|
|
95
|
+
return name;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// 壊れた package.json で生成全体を止めない。タイトルはディレクトリ名で十分に代わりになるため。
|
|
99
|
+
}
|
|
100
|
+
return basename(dir);
|
|
101
|
+
}
|
|
102
|
+
if (dirname(dir) === dir)
|
|
103
|
+
return basename(dirname(resolve(specPath)));
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
// 失敗したことを出力そのものに書く理由: Markdown や JSON を前回の内容のまま残すと、読む人が古い仕様を
|
|
107
|
+
// 最新だと取り違えるため(specs/watch-session.spec.ts の未決事項だったもの)。HTML はエラーページにする。
|
|
108
|
+
export const failureOutput = (format, paths, error) => {
|
|
109
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
110
|
+
if (format === "html")
|
|
111
|
+
return { kind: "text", content: renderErrorHtml(paths.length === 1 ? specNameOf(paths[0]) : "仕様書", error) };
|
|
112
|
+
if (format === "json")
|
|
113
|
+
return { kind: "text", content: JSON.stringify({ error: message }, null, 2) };
|
|
114
|
+
const notice = [
|
|
115
|
+
"# 仕様書を生成できませんでした",
|
|
116
|
+
"",
|
|
117
|
+
"spec ファイルを直して保存すると、自動で生成し直します。",
|
|
118
|
+
"",
|
|
119
|
+
"```",
|
|
120
|
+
message,
|
|
121
|
+
"```",
|
|
122
|
+
"",
|
|
123
|
+
];
|
|
124
|
+
if (paths.length === 1)
|
|
125
|
+
return { kind: "text", content: notice.join("\n") };
|
|
126
|
+
return {
|
|
127
|
+
kind: "files",
|
|
128
|
+
files: { "README.md": [...notice, "このディレクトリのほかのファイルは、前回の生成のままです。", ""].join("\n") },
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
export const generate = async (path, format) => {
|
|
132
|
+
const out = await generateProject([path], format);
|
|
133
|
+
if (out.kind !== "text")
|
|
134
|
+
throw new Error("1 つの spec からは 1 つのテキストが生成されるはず");
|
|
135
|
+
return out.content;
|
|
136
|
+
};
|
|
137
|
+
const withNewline = (content) => (content.endsWith("\n") ? content : content + "\n");
|
|
138
|
+
export const writeOutput = async (out, content) => {
|
|
139
|
+
await mkdir(dirname(out), { recursive: true });
|
|
140
|
+
await writeFile(out, withNewline(content));
|
|
141
|
+
};
|
|
142
|
+
export const writeProjectOutput = async (out, output) => {
|
|
143
|
+
if (output.kind === "text")
|
|
144
|
+
return writeOutput(out, output.content);
|
|
145
|
+
await mkdir(out, { recursive: true });
|
|
146
|
+
await Promise.all(Object.entries(output.files).map(([name, content]) => writeFile(join(out, name), withNewline(content))));
|
|
147
|
+
};
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/load.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type FieldValue } from "./static.js";
|
|
2
|
+
export type State = Readonly<Record<string, unknown>>;
|
|
3
|
+
export type ActionFn = (state: never, actor: never) => unknown;
|
|
4
|
+
export type InvariantFn = (state: never) => unknown;
|
|
5
|
+
export type SurfaceFn = (state: never, actor: never) => unknown;
|
|
6
|
+
export interface Question {
|
|
7
|
+
readonly ask: string;
|
|
8
|
+
readonly note?: string;
|
|
9
|
+
readonly about?: ActionFn | Readonly<Record<string, unknown>>;
|
|
10
|
+
}
|
|
11
|
+
export interface Link {
|
|
12
|
+
readonly from?: ActionFn;
|
|
13
|
+
readonly to: string;
|
|
14
|
+
readonly action?: string;
|
|
15
|
+
readonly label: string;
|
|
16
|
+
}
|
|
17
|
+
export interface Decision {
|
|
18
|
+
readonly decide: (input: never) => unknown;
|
|
19
|
+
readonly cases: ReadonlyArray<{
|
|
20
|
+
readonly input: unknown;
|
|
21
|
+
readonly expect?: unknown;
|
|
22
|
+
}>;
|
|
23
|
+
}
|
|
24
|
+
export interface ScenarioStep {
|
|
25
|
+
readonly do: ActionFn;
|
|
26
|
+
readonly by: string;
|
|
27
|
+
readonly input?: string;
|
|
28
|
+
readonly expect?: Readonly<Record<string, unknown>>;
|
|
29
|
+
}
|
|
30
|
+
export interface Spec {
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly initial: State;
|
|
33
|
+
readonly actors: ReadonlyArray<readonly [name: string, actor: unknown]>;
|
|
34
|
+
readonly actions: ReadonlyArray<readonly [name: string, fn: ActionFn]>;
|
|
35
|
+
readonly invariants: ReadonlyArray<readonly [name: string, fn: InvariantFn]>;
|
|
36
|
+
readonly inputs: Readonly<Record<string, ReadonlyArray<readonly [label: string, args: ReadonlyArray<unknown>]>>>;
|
|
37
|
+
readonly surface: SurfaceFn | null;
|
|
38
|
+
readonly scenarios: ReadonlyArray<readonly [name: string, steps: ReadonlyArray<ScenarioStep>]>;
|
|
39
|
+
readonly questions: ReadonlyArray<Question>;
|
|
40
|
+
readonly links: ReadonlyArray<Link>;
|
|
41
|
+
readonly decisions: ReadonlyArray<readonly [name: string, decision: Decision]>;
|
|
42
|
+
readonly docs: Readonly<Record<string, string>>;
|
|
43
|
+
readonly fieldDocs: Readonly<Record<string, string>>;
|
|
44
|
+
readonly evidence: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
45
|
+
readonly glossary: Readonly<Record<string, string>>;
|
|
46
|
+
readonly fields: Readonly<Record<string, ReadonlyArray<FieldValue>>>;
|
|
47
|
+
readonly stateDoc: string | null;
|
|
48
|
+
}
|
|
49
|
+
export interface LoadOptions {
|
|
50
|
+
readonly source?: string;
|
|
51
|
+
}
|
|
52
|
+
export declare const loadSpec: (name: string, mod: Readonly<Record<string, unknown>>, options?: LoadOptions) => Spec;
|
package/dist/load.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { analyze } from "./static.js";
|
|
2
|
+
const RESERVED = new Set([
|
|
3
|
+
"initial",
|
|
4
|
+
"actors",
|
|
5
|
+
"invariants",
|
|
6
|
+
"inputs",
|
|
7
|
+
"surface",
|
|
8
|
+
"scenarios",
|
|
9
|
+
"questions",
|
|
10
|
+
"links",
|
|
11
|
+
"glossary",
|
|
12
|
+
"decisions",
|
|
13
|
+
]);
|
|
14
|
+
const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
|
|
15
|
+
export const loadSpec = (name, mod, options = {}) => {
|
|
16
|
+
const { initial, actors } = mod;
|
|
17
|
+
if (!isRecord(initial))
|
|
18
|
+
throw new Error(`${name}: 初期状態を表す \`export const initial\` が必要です`);
|
|
19
|
+
if (!isRecord(actors))
|
|
20
|
+
throw new Error(`${name}: 登場人物を表す \`export const actors\` が必要です`);
|
|
21
|
+
const info = options.source === undefined ? undefined : analyze(options.source);
|
|
22
|
+
return {
|
|
23
|
+
name,
|
|
24
|
+
initial,
|
|
25
|
+
actors: Object.entries(actors),
|
|
26
|
+
actions: orderActions(Object.entries(mod).filter((e) => !RESERVED.has(e[0]) && typeof e[1] === "function"), info?.order),
|
|
27
|
+
invariants: isRecord(mod.invariants)
|
|
28
|
+
? Object.entries(mod.invariants).filter((e) => typeof e[1] === "function")
|
|
29
|
+
: [],
|
|
30
|
+
inputs: inputsOf(mod.inputs),
|
|
31
|
+
surface: typeof mod.surface === "function" ? mod.surface : null,
|
|
32
|
+
questions: Array.isArray(mod.questions)
|
|
33
|
+
? mod.questions.filter((q) => isRecord(q) && typeof q.ask === "string")
|
|
34
|
+
: [],
|
|
35
|
+
decisions: isRecord(mod.decisions)
|
|
36
|
+
? Object.entries(mod.decisions).filter((e) => isRecord(e[1]) && typeof e[1].decide === "function" && Array.isArray(e[1].cases))
|
|
37
|
+
: [],
|
|
38
|
+
links: Array.isArray(mod.links)
|
|
39
|
+
? mod.links.filter((l) => isRecord(l) && typeof l.to === "string" && typeof l.label === "string")
|
|
40
|
+
: [],
|
|
41
|
+
scenarios: isRecord(mod.scenarios)
|
|
42
|
+
? Object.entries(mod.scenarios).filter((e) => Array.isArray(e[1]))
|
|
43
|
+
: [],
|
|
44
|
+
docs: info?.docs ?? {},
|
|
45
|
+
fieldDocs: info?.fieldDocs ?? {},
|
|
46
|
+
evidence: info?.evidence ?? {},
|
|
47
|
+
glossary: isRecord(mod.glossary)
|
|
48
|
+
? Object.fromEntries(Object.entries(mod.glossary).filter((e) => typeof e[1] === "string"))
|
|
49
|
+
: {},
|
|
50
|
+
fields: info?.fields ?? {},
|
|
51
|
+
stateDoc: info?.stateDoc ?? null,
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
// ソースの順で並べる理由: ES のモジュール名前空間オブジェクトはキーを名前順に並べるので、
|
|
55
|
+
// import した結果からは書かれた順が分からない。仕様書では業務の流れ(edit → submit → publish)の
|
|
56
|
+
// 順に操作を見せたいので、構文解析で得た export の順を使う。
|
|
57
|
+
// ソースがないときに名前順にするのは、実行環境(Node と Vitest など)によって順序が変わらないようにするため。
|
|
58
|
+
const inputsOf = (u) => {
|
|
59
|
+
if (!isRecord(u))
|
|
60
|
+
return {};
|
|
61
|
+
return Object.fromEntries(Object.entries(u).flatMap(([action, examples]) => isRecord(examples)
|
|
62
|
+
? [[action, Object.entries(examples).filter((e) => Array.isArray(e[1]))]]
|
|
63
|
+
: []));
|
|
64
|
+
};
|
|
65
|
+
const orderActions = (actions, order) => {
|
|
66
|
+
const byName = actions.sort(([a], [b]) => a.localeCompare(b));
|
|
67
|
+
if (order === undefined)
|
|
68
|
+
return byName;
|
|
69
|
+
const position = (name) => {
|
|
70
|
+
const i = order.indexOf(name);
|
|
71
|
+
return i === -1 ? Number.POSITIVE_INFINITY : i;
|
|
72
|
+
};
|
|
73
|
+
return byName.sort(([a], [b]) => position(a) - position(b));
|
|
74
|
+
};
|