@delurio/cli 0.7.0 → 0.9.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/dist/needs.js ADDED
@@ -0,0 +1,311 @@
1
+ // A flow's needs and a product's gaps (SPEC.md §13). needs.yaml, beside a flow, is a closed list of what must exist for
2
+ // the flow's users: each need names the evidence that it does, or says `missing` and why. needs.gaps.yaml, at the root
3
+ // of a product's graphs, lists every need of its flows that is missing. `checkNeeds` holds each piece of evidence to
4
+ // what it names, each missing need to the gaps file above it, and each entry of a gaps file to a need under its folder
5
+ // that is still missing, so the list only shrinks on its own. `planned` gives a tool that walks a flow on the app the
6
+ // states and nodes that only missing needs are drawn as, for it to leave out.
7
+ import { existsSync, readFileSync, statSync } from 'node:fs';
8
+ import { basename, dirname, isAbsolute, join } from 'node:path';
9
+ import { keyAt, readYaml } from './yaml.js';
10
+ export const NEEDS_FILE = 'needs.yaml';
11
+ export const GAPS_FILE = 'needs.gaps.yaml';
12
+ const FORMAT = 'delurio-graph/0';
13
+ const KINDS = ['source', 'test', 'scenario', 'state', 'node', 'setting'];
14
+ // what the graph draws: it shows where a need is, and alone meets nothing
15
+ const IN_GRAPH = new Set(['state', 'node']);
16
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
17
+ const text = (v) => (typeof v === 'string' && v.trim() !== '' ? v : null);
18
+ const kindOf = (e) => KINDS.find((k) => typeof e[k] === 'string');
19
+ const isMissing = (n) => text(n.missing) !== null;
20
+ // the value of a graph file, or null when it cannot be read: the schema rule says why
21
+ function readDoc(file) {
22
+ try {
23
+ const raw = readFileSync(file, 'utf8');
24
+ const doc = readYaml(raw);
25
+ if (!isMap(doc))
26
+ return null;
27
+ if (typeof doc.schema === 'string' && doc.schema !== FORMAT)
28
+ return null;
29
+ return { text: raw, doc };
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ // the needs.yaml beside a flow, read; null when there is none
36
+ export function readNeeds(dir) {
37
+ const file = join(dir, NEEDS_FILE);
38
+ if (!existsSync(file))
39
+ return null;
40
+ const doc = readYaml(readFileSync(file, 'utf8'));
41
+ return isMap(doc) && Array.isArray(doc.needs) ? doc : null;
42
+ }
43
+ // what a tool that walks the flow on the app leaves out (SPEC.md §13): the states and the nodes that missing needs are
44
+ // drawn as and that no met need names, each with the ids of those needs
45
+ export function planned(needs) {
46
+ const out = { states: new Map(), nodes: new Map() };
47
+ const built = { states: new Set(), nodes: new Set() };
48
+ for (const n of (needs?.needs ?? [])) {
49
+ if (!isMap(n) || typeof n.id !== 'string')
50
+ continue;
51
+ for (const e of Array.isArray(n.evidence) ? n.evidence : []) {
52
+ if (!isMap(e))
53
+ continue;
54
+ for (const [key, into] of [['state', 'states'], ['node', 'nodes']]) {
55
+ const name = e[key];
56
+ if (typeof name !== 'string')
57
+ continue;
58
+ if (!isMissing(n))
59
+ built[into].add(name);
60
+ else
61
+ out[into].set(name, [...(out[into].get(name) ?? []), n.id]);
62
+ }
63
+ }
64
+ }
65
+ for (const into of ['states', 'nodes'])
66
+ for (const name of built[into])
67
+ out[into].delete(name);
68
+ return out;
69
+ }
70
+ // the nearest gaps file at or above a folder, up to the repository's root (the first folder that holds .git)
71
+ function nearestGaps(dir) {
72
+ for (let d = dir;; d = dirname(d)) {
73
+ if (existsSync(join(d, GAPS_FILE)))
74
+ return join(d, GAPS_FILE);
75
+ if (existsSync(join(d, '.git')) || dirname(d) === d)
76
+ return null;
77
+ }
78
+ }
79
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
80
+ // the text holds the name, not as a part of a longer word: an identifier, or a test's name in quotes
81
+ const holds = (body, name) => new RegExp(`(?<![\\w$])${escapeRe(name)}(?![\\w$])`).test(body);
82
+ // a line of the file sets the variable and is not commented out: NAME=, export NAME=, NAME: or - NAME=
83
+ const sets = (body, name) => new RegExp(`^[ \\t]*(?:-[ \\t]*)?(?:export[ \\t]+)?${escapeRe(name)}[ \\t]*[=:]`, 'm').test(body);
84
+ const lineCount = (body) => body.split('\n').length - (body.endsWith('\n') ? 1 : 0);
85
+ const fileAt = (ctx, path) => {
86
+ const abs = isAbsolute(path) ? path : join(ctx.app, path);
87
+ return existsSync(abs) && statSync(abs).isFile() ? abs : null;
88
+ };
89
+ // a binding's scenarios, those of the bindings it extends included (each named relative to the one that extends it)
90
+ function scenariosOf(file, seen = new Set()) {
91
+ const out = new Set();
92
+ if (seen.has(file) || !existsSync(file))
93
+ return out;
94
+ seen.add(file);
95
+ const read = readDoc(file);
96
+ if (read === null)
97
+ return out;
98
+ if (isMap(read.doc.scenarios))
99
+ for (const s of Object.keys(read.doc.scenarios))
100
+ out.add(s);
101
+ if (typeof read.doc.extends === 'string')
102
+ for (const s of scenariosOf(join(dirname(file), read.doc.extends), seen))
103
+ out.add(s);
104
+ return out;
105
+ }
106
+ // why a piece of evidence does not resolve, or null when it does (or when what it names cannot be read, which is
107
+ // reported where it is)
108
+ function unresolved(ctx, kind, e) {
109
+ const value = e[kind];
110
+ const name = text(e.name);
111
+ switch (kind) {
112
+ case 'source': {
113
+ const m = /^(.*?)(?::(\d+))?$/.exec(value);
114
+ const abs = fileAt(ctx, m[1]);
115
+ if (abs === null)
116
+ return `source ${m[1]} does not exist`;
117
+ const body = readFileSync(abs, 'utf8');
118
+ if (m[2] !== undefined && Number(m[2]) > lineCount(body))
119
+ return `source ${value} is past the file's end: it has ${lineCount(body)} lines`;
120
+ return name !== null && !holds(body, name) ? `source ${m[1]} holds no ${name}` : null;
121
+ }
122
+ case 'test': {
123
+ const abs = fileAt(ctx, value);
124
+ if (abs === null)
125
+ return `test ${value} does not exist`;
126
+ return name !== null && !holds(readFileSync(abs, 'utf8'), name) ? `test ${value} holds no test named "${name}"` : null;
127
+ }
128
+ case 'scenario': {
129
+ const given = text(e.binding);
130
+ const abs = given === null ? join(ctx.dir, 'binding.yaml') : fileAt(ctx, given);
131
+ const said = given === null ? "the flow's own binding.yaml" : `the binding ${given}`;
132
+ if (abs === null || !existsSync(abs))
133
+ return `scenario ${value}: ${said} does not exist`;
134
+ const read = readDoc(abs);
135
+ if (read === null)
136
+ return `scenario ${value}: ${said} cannot be read`;
137
+ if (read.doc.kind !== 'binding')
138
+ return `scenario ${value}: ${said} is not a binding (kind: binding)`;
139
+ if (ctx.flowId !== null && read.doc.flow !== ctx.flowId)
140
+ return `scenario ${value}: ${said} binds ${String(read.doc.flow ?? 'no flow')}, not ${ctx.flowId}`;
141
+ const scenarios = scenariosOf(abs);
142
+ return scenarios.has(value) ? null : `scenario ${value} is not a scenario of ${said}${scenarios.size > 0 ? ` (it has ${[...scenarios].sort().join(', ')})` : ''}`;
143
+ }
144
+ case 'state':
145
+ return ctx.states === null || ctx.states.has(value) ? null : `state ${value} is not a state of ${ctx.flowId ?? 'the flow'}`;
146
+ case 'node':
147
+ if (ctx.nodes === 'none')
148
+ return `node ${value}: the flow has no screens, as there is no ui.yaml beside it`;
149
+ return ctx.nodes === null || ctx.nodes.has(value) ? null : `node ${value} is not a node of the flow's ui.yaml`;
150
+ case 'setting': {
151
+ const where = text(e.in);
152
+ if (where === null)
153
+ return null; // the schema says it is missing
154
+ const abs = fileAt(ctx, where);
155
+ if (abs === null)
156
+ return `setting ${value}: ${where} does not exist`;
157
+ return sets(readFileSync(abs, 'utf8'), value) ? null : `setting ${value} is not set in ${where}: no line sets it, or the one that does is commented out`;
158
+ }
159
+ }
160
+ }
161
+ // the nodes of a ui.yaml, or null when it cannot be read
162
+ function nodesOf(file) {
163
+ const read = readDoc(file);
164
+ return read === null ? null : new Set(isMap(read.doc.nodes) ? Object.keys(read.doc.nodes) : []);
165
+ }
166
+ // a gaps file, read once per run; null when it cannot be read (the schema rule says why)
167
+ function gapsReader() {
168
+ const seen = new Map();
169
+ return (file) => {
170
+ if (!seen.has(file)) {
171
+ const read = readDoc(file);
172
+ const gaps = new Map();
173
+ if (read !== null && isMap(read.doc.gaps)) {
174
+ for (const [flow, ids] of Object.entries(read.doc.gaps))
175
+ gaps.set(flow, Array.isArray(ids) ? ids.filter((x) => typeof x === 'string') : []);
176
+ }
177
+ seen.set(file, read === null ? null : { id: typeof read.doc.id === 'string' ? read.doc.id : basename(dirname(file)), gaps, text: read.text });
178
+ }
179
+ return seen.get(file) ?? null;
180
+ };
181
+ }
182
+ // every needs file and gaps file among `files` (the graph files under the folders checked), with the application's
183
+ // repository root that evidence paths are relative to
184
+ export function checkNeeds(files, app) {
185
+ const out = { problems: [], files: 0, needs: 0, gaps: 0 };
186
+ const gapsOf = gapsReader();
187
+ // each needs file's flow and the state of each of its needs, by the gaps file that covers it; null for a needs file
188
+ // that cannot be read, whose entries are then not judged
189
+ const covered = new Map();
190
+ const cover = (gapsFile, flow, states) => {
191
+ if (gapsFile === null)
192
+ return;
193
+ const byFlow = covered.get(gapsFile) ?? new Map();
194
+ byFlow.set(flow, states);
195
+ covered.set(gapsFile, byFlow);
196
+ };
197
+ const problem = (rule, file, body, path, message, graph, element) => {
198
+ out.problems.push({ rule, file, ...keyAt(body, path), message, graph, element });
199
+ };
200
+ for (const file of files.filter((f) => basename(f) === NEEDS_FILE)) {
201
+ const read = readDoc(file);
202
+ if (read === null || !Array.isArray(read.doc.needs)) {
203
+ const beside = readDoc(join(dirname(file), 'flow.yaml'))?.doc.id;
204
+ if (typeof beside === 'string')
205
+ cover(nearestGaps(dirname(file)), beside, null);
206
+ continue;
207
+ }
208
+ out.files++;
209
+ const { doc, text: body } = read;
210
+ const dir = dirname(file);
211
+ const flowFile = join(dir, 'flow.yaml');
212
+ const flow = existsSync(flowFile) ? readDoc(flowFile) : null;
213
+ const flowId = typeof flow?.doc.id === 'string' ? flow.doc.id : null;
214
+ const ownId = typeof doc.id === 'string' ? doc.id : null;
215
+ const graph = flowId ?? ownId ?? basename(dir);
216
+ if (!existsSync(flowFile)) {
217
+ problem('needs-place', file, body, ['id'], `needs.yaml is beside no flow: it sits in a flow's folder, beside its flow.yaml, and lists that flow's needs (SPEC.md §13)`, graph, 'needs');
218
+ }
219
+ else if (flowId !== null && ownId !== null && ownId !== flowId) {
220
+ problem('needs-place', file, body, ['id'], `needs.yaml is the needs of ${ownId}, and the flow beside it is ${flowId}: its id is the id of the flow beside it (SPEC.md §13)`, graph, 'needs/id');
221
+ }
222
+ const uiFile = join(dir, 'ui.yaml');
223
+ const ctx = {
224
+ app,
225
+ dir,
226
+ flowId,
227
+ states: flow === null ? null : new Set(isMap(flow.doc.states) ? Object.keys(flow.doc.states) : []),
228
+ nodes: !existsSync(flowFile) ? null : existsSync(uiFile) ? nodesOf(uiFile) : 'none',
229
+ };
230
+ const key = flowId ?? ownId ?? graph; // the flow, as the gaps name it
231
+ const gapsFile = nearestGaps(dir);
232
+ const listed = gapsFile === null ? null : gapsOf(gapsFile);
233
+ const states = new Map();
234
+ const firstAt = new Map();
235
+ read.doc.needs.forEach((item, i) => {
236
+ if (!isMap(item) || typeof item.id !== 'string')
237
+ return;
238
+ const id = item.id;
239
+ out.needs++;
240
+ const at = ['needs', String(i)];
241
+ const first = firstAt.get(id);
242
+ if (first !== undefined) {
243
+ problem('need-twice', file, body, [...at, 'id'], `need ${id} is given twice: it is given first at line ${keyAt(body, ['needs', String(first), 'id']).line}, and a need's id comes once in its flow (SPEC.md §13)`, graph, `needs/${id}/twice`);
244
+ }
245
+ else
246
+ firstAt.set(id, i);
247
+ const evidence = Array.isArray(item.evidence) ? item.evidence : [];
248
+ let outside = false;
249
+ let kinds = 0;
250
+ evidence.forEach((e, j) => {
251
+ if (!isMap(e))
252
+ return;
253
+ const kind = kindOf(e);
254
+ if (kind === undefined)
255
+ return; // the schema says it names no kind
256
+ kinds++;
257
+ if (!IN_GRAPH.has(kind))
258
+ outside = true;
259
+ const why = unresolved(ctx, kind, e);
260
+ if (why !== null)
261
+ problem('evidence-unresolved', file, body, [...at, 'evidence', String(j), kind], `need ${id}: ${why} (SPEC.md §13)`, graph, `needs/${id}/evidence/${kind}:${String(e[kind])}`);
262
+ });
263
+ const missing = isMissing(item);
264
+ const state = missing ? 'missing' : outside ? 'met' : 'unproven';
265
+ if (first === undefined)
266
+ states.set(id, state);
267
+ if (state === 'unproven' && kinds > 0 && kinds === evidence.length) {
268
+ problem('need-no-evidence', file, body, [...at, 'evidence'], `need ${id} is not missing and names no evidence outside the graph: what it is drawn as shows nothing built; name a source, a test, a scenario or a setting, or say why it is missing (SPEC.md §13)`, graph, `needs/${id}`);
269
+ }
270
+ if (!missing)
271
+ return;
272
+ out.gaps++;
273
+ const why = text(item.missing);
274
+ if (listed === null) {
275
+ problem('need-unlisted', file, body, [...at, 'missing'], `need ${id} is missing, and there is no ${GAPS_FILE} above it: list it in the product's gaps, at the root of its graphs (SPEC.md §13)`, graph, `needs/${id}`);
276
+ }
277
+ else if (!(listed.gaps.get(key) ?? []).includes(id)) {
278
+ problem('need-unlisted', file, body, [...at, 'missing'], `need ${id} is missing, and ${GAPS_FILE} does not list it under ${key}: list it there, or name its evidence and take out missing (SPEC.md §13)`, graph, `needs/${id}`);
279
+ }
280
+ else {
281
+ problem('need-gap', file, body, [...at, 'missing'], `need ${id} is missing: ${why}`, graph, `needs/${id}`);
282
+ }
283
+ });
284
+ cover(gapsFile, key, states);
285
+ }
286
+ // each gaps file among the files checked, held to the needs under its folder that it covers
287
+ for (const file of files.filter((f) => basename(f) === GAPS_FILE)) {
288
+ const listed = gapsOf(file);
289
+ if (listed === null)
290
+ continue;
291
+ const byFlow = covered.get(file) ?? new Map();
292
+ for (const [flow, ids] of listed.gaps) {
293
+ const states = byFlow.get(flow);
294
+ if (states === null)
295
+ continue;
296
+ if (states === undefined) {
297
+ problem('gap-unknown', file, listed.text, ['gaps', flow], `${GAPS_FILE} lists gaps of ${flow}, which is no flow with a needs.yaml under its folder: take them out, or name the flow by its id (SPEC.md §13)`, listed.id, `gaps/${flow}`);
298
+ continue;
299
+ }
300
+ ids.forEach((id, k) => {
301
+ const state = states.get(id);
302
+ const at = ['gaps', flow, String(k)];
303
+ if (state === undefined)
304
+ problem('gap-unknown', file, listed.text, at, `${GAPS_FILE} lists ${id} of ${flow}, which is no need of its needs.yaml: take it out, or name the need by its id (SPEC.md §13)`, listed.id, `gaps/${flow}/${id}`);
305
+ else if (state === 'met')
306
+ problem('gap-met', file, listed.text, at, `${GAPS_FILE} lists ${id} of ${flow}, which is met now: take it out, as the list only shrinks (SPEC.md §13)`, listed.id, `gaps/${flow}/${id}`);
307
+ });
308
+ }
309
+ }
310
+ return out;
311
+ }
package/dist/schemas.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type SchemaKind = 'flow' | 'ui' | 'domain' | 'nav' | 'catalog';
1
+ export type SchemaKind = 'flow' | 'ui' | 'domain' | 'nav' | 'catalog' | 'needs' | 'gaps';
2
2
  export interface SchemaFinding {
3
3
  line: number;
4
4
  column: number;
package/dist/schemas.js CHANGED
@@ -11,15 +11,17 @@ import { isMap, isSeq, LineCounter, parseDocument } from 'yaml';
11
11
  import { readYaml, unsupported } from './yaml.js';
12
12
  import { isDomainText, mayBeDomain } from './domain.js';
13
13
  const FORMAT = 'delurio-graph/0';
14
- const KINDS = ['flow', 'ui', 'domain', 'nav', 'catalog'];
14
+ const KINDS = ['flow', 'ui', 'domain', 'nav', 'catalog', 'needs', 'gaps'];
15
15
  // the kind of graph file, by its name, and a domain also by its `kind` (a domain may be split across files, SPEC.md
16
16
  // §5): null for a file no schema covers (binding, tutorial, kit, anchors.lock)
17
17
  export function schemaKindOf(file) {
18
18
  const name = basename(file);
19
- if (name === 'flow.yaml' || name === 'ui.yaml' || name === 'domain.yaml')
19
+ if (name === 'flow.yaml' || name === 'ui.yaml' || name === 'domain.yaml' || name === 'needs.yaml')
20
20
  return name.slice(0, -'.yaml'.length);
21
21
  if (name === 'nav.yaml' || name === 'nav.extracted.yaml')
22
22
  return 'nav';
23
+ if (name === 'needs.gaps.yaml')
24
+ return 'gaps';
23
25
  if (name.endsWith('.json') && basename(dirname(file)) === 'catalog')
24
26
  return 'catalog';
25
27
  if (mayBeDomain(name) && existsSync(file) && isDomainText(readFileSync(file, 'utf8')))
package/dist/starts.js CHANGED
@@ -13,10 +13,17 @@ function rootOf(dir) {
13
13
  return d;
14
14
  return dirname(dir);
15
15
  }
16
+ // every flow under root by its id; a flow.yaml that cannot be read is left out, as its own check reports it
16
17
  function flowsUnder(root, depth = 4, out = new Map()) {
17
18
  const file = join(root, 'flow.yaml');
18
19
  if (existsSync(file)) {
19
- const f = readYaml(readFileSync(file, 'utf8'));
20
+ let f = null;
21
+ try {
22
+ f = readYaml(readFileSync(file, 'utf8'));
23
+ }
24
+ catch {
25
+ f = null;
26
+ }
20
27
  if (typeof f?.id === 'string')
21
28
  out.set(f.id, { ...f, context: f.context ?? {} });
22
29
  }
@@ -0,0 +1,9 @@
1
+ import type { Graph } from './graph.ts';
2
+ import type { Exploration, Model } from './model.ts';
3
+ export interface TutorialProblem {
4
+ path: string[];
5
+ line?: number;
6
+ column?: number;
7
+ message: string;
8
+ }
9
+ export declare function checkTutorial(g: Graph, m: Model, ex: Exploration, text: string): TutorialProblem[];
@@ -0,0 +1,297 @@
1
+ // A flow's tutorial.yaml held to the flow and its ui (SPEC.md §7). First every name a tutorial uses: the flow it is
2
+ // written against, the variables and values of its `scenario` and of each step's `then`, the states of `show`, `cut`
3
+ // and `end`, the nodes of `press`, `reveal` and `focus`, the events of `after`, and each `{word}` its words fill. Then,
4
+ // when every name is one, its steps are replayed on the flow from the scenario as the video plays them, and the first
5
+ // step that no longer holds is where it stops: a tutorial that no longer matches the graph stops at that step.
6
+ import { kindOf } from './edges.js';
7
+ import { shownIn } from './graph.js';
8
+ import { readYaml } from './yaml.js';
9
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
10
+ const names = (v) => (Array.isArray(v) ? v : v === undefined ? [] : [v]);
11
+ const shown = (v) => JSON.stringify(v);
12
+ class Stop extends Error {
13
+ path;
14
+ constructor(path, message) {
15
+ super(message);
16
+ this.path = path;
17
+ }
18
+ }
19
+ export function checkTutorial(g, m, ex, text) {
20
+ let t;
21
+ try {
22
+ t = readYaml(text);
23
+ }
24
+ catch (err) {
25
+ const at = err.linePos?.[0];
26
+ return [{ path: [], line: at?.line ?? 1, column: at?.col ?? 1, message: `tutorial.yaml cannot be read: ${err.message.split('\n')[0]}` }];
27
+ }
28
+ if (!isMap(t) || t.kind !== 'tutorial')
29
+ return [{ path: isMap(t) ? ['kind'] : [], message: 'tutorial.yaml is not a tutorial: it says kind: tutorial (SPEC.md §1, §7)' }];
30
+ if (t.flow !== g.flow.id)
31
+ return [{ path: ['flow'], message: `the tutorial is written against ${String(t.flow)}, and the flow beside it is ${g.flow.id} (SPEC.md §7)` }];
32
+ const stage = t.stage ?? 'screen';
33
+ if (stage !== 'screen' && stage !== 'diagram')
34
+ return [{ path: ['stage'], message: `stage is screen or diagram, not ${String(stage)} (SPEC.md §7)` }];
35
+ const steps = Array.isArray(t.steps) ? t.steps : [];
36
+ const out = [];
37
+ const flow = g.flow;
38
+ const nodes = g.ui.nodes;
39
+ const events = new Set(Object.values(flow.states).flatMap((st) => Object.keys(st.on ?? {})));
40
+ const samples = new Set([...Object.keys(g.ui.samples), ...(isMap(t.samples) ? Object.keys(t.samples) : [])]);
41
+ const problem = (path, message) => {
42
+ out.push({ path, message });
43
+ };
44
+ const values = (where, given, what) => {
45
+ if (given === undefined)
46
+ return;
47
+ if (!isMap(given))
48
+ return problem(where, `${what} is a map of variables to values`);
49
+ for (const [name, v] of Object.entries(given)) {
50
+ const cv = flow.context[name];
51
+ if (cv === undefined)
52
+ problem([...where, name], `${what} names ${name}, which is not a variable of ${flow.id}`);
53
+ else if (!cv.values.includes(v))
54
+ problem([...where, name], `${what}: ${shown(v)} is not a value of ${name} (${cv.values.map(shown).join(', ')})`);
55
+ }
56
+ };
57
+ // the start: a value of the scenario's for each variable that starts from any value, and the fixed one of the others
58
+ values(['scenario'], t.scenario, 'scenario');
59
+ const scenario = isMap(t.scenario) ? t.scenario : {};
60
+ for (const v of m.vars) {
61
+ const cv = flow.context[v];
62
+ const given = scenario[v];
63
+ if (cv.initial === 'any' && given === undefined)
64
+ problem(['scenario'], `scenario gives no value for ${v}, and the flow starts from any value of it`);
65
+ else if (cv.initial !== 'any' && given !== undefined && given !== cv.initial)
66
+ problem(['scenario', v], `scenario gives ${v} = ${shown(given)}, and ${flow.id} always starts with ${v} = ${shown(cv.initial)}`);
67
+ }
68
+ const words = (where, s, step) => {
69
+ if (typeof s !== 'string')
70
+ return;
71
+ for (const [, name] of s.matchAll(/\{(\w+)\}/g)) {
72
+ if (samples.has(name))
73
+ continue;
74
+ const n = nodes[name];
75
+ if (n === undefined)
76
+ problem(where, `${step}{${name}} is neither a sample value nor a node of ui.yaml`);
77
+ else if (n.text === undefined)
78
+ problem(where, `${step}{${name}} names the node ${name}, which has no visible text to say`);
79
+ }
80
+ };
81
+ words(['title'], t.title, 'title: ');
82
+ steps.forEach((s0, i) => {
83
+ if (!isMap(s0))
84
+ return;
85
+ const s = s0;
86
+ const at = (...rest) => ['steps', String(i), ...rest];
87
+ const step = `step ${i + 1}`;
88
+ for (const key of ['show', 'cut', 'end']) {
89
+ const v = s[key];
90
+ if (typeof v === 'string' && flow.states[v] === undefined)
91
+ problem(at(key), `${step}: ${key} ${v}, which is not a state of ${flow.id}`);
92
+ }
93
+ for (const key of ['press', 'reveal', 'focus']) {
94
+ names(s[key]).forEach((id, j) => {
95
+ const where = Array.isArray(s[key]) ? at(key, String(j)) : at(key);
96
+ if (stage === 'diagram')
97
+ problem(where, `${step}: ${key} points at a node, and a tutorial on the diagram has none (SPEC.md §7)`);
98
+ else if (typeof id !== 'string' || nodes[id] === undefined)
99
+ problem(where, `${step}: ${key} ${String(id)}, which is not a node of ui.yaml`);
100
+ });
101
+ }
102
+ names(s.after).forEach((e, j) => {
103
+ if (typeof e !== 'string' || !events.has(e))
104
+ problem(Array.isArray(s.after) ? at('after', String(j)) : at('after'), `${step}: after ${String(e)}, which no state of ${flow.id} handles`);
105
+ });
106
+ values(at('then'), s.then, `${step}: then`);
107
+ words(at('say'), s.say, `${step}: `);
108
+ words(at('chapter'), s.chapter, `${step}: `);
109
+ if (isMap(s.card)) {
110
+ words(at('card', 'title'), s.card.title, `${step}: `);
111
+ words(at('card', 'body'), s.card.body, `${step}: `);
112
+ }
113
+ });
114
+ if (out.length > 0)
115
+ return out;
116
+ try {
117
+ if (stage === 'diagram')
118
+ replayDiagram(g, m, ex, steps, scenario);
119
+ else
120
+ replayScreens(g, m, ex, steps, scenario);
121
+ }
122
+ catch (err) {
123
+ if (!(err instanceof Stop))
124
+ throw err;
125
+ return [{ path: err.path, message: err.message }];
126
+ }
127
+ return [];
128
+ }
129
+ function start(g, m, scenario) {
130
+ return { state: g.flow.initial, ctx: m.vars.map((v) => (g.flow.context[v].initial === 'any' ? scenario[v] : g.flow.context[v].initial)) };
131
+ }
132
+ // the step's `then`: of the cases its transitions can take, the one with these values; without it, the first
133
+ function thenOf(m, s) {
134
+ return isMap(s.then) ? Object.entries(s.then).map(([name, v]) => [m.vars.indexOf(name), v]) : [];
135
+ }
136
+ const pick = (cases, then) => cases.find((c) => then.every(([i, v]) => c.ctx[i] === v)) ?? cases[0];
137
+ function thenHolds(m, s, cur, path, step) {
138
+ for (const [i, v] of thenOf(m, s)) {
139
+ if (cur.ctx[i] !== v)
140
+ throw new Stop([...path, 'then', m.vars[i]], `${step}: no case of this step has ${m.vars[i]} = ${shown(v)}`);
141
+ }
142
+ }
143
+ function replayScreens(g, m, ex, steps, scenario) {
144
+ const flow = g.flow;
145
+ const nodes = g.ui.nodes;
146
+ const hasScreen = (state) => Object.values(nodes).some((n) => shownIn(n, state));
147
+ let then = [];
148
+ const take = (cur, event, path, step) => {
149
+ const hit = pick(m.steps(cur.state, cur.ctx).filter((x) => x.event === event), then);
150
+ if (hit === undefined)
151
+ throw new Stop(path, `${step}: the flow is in ${cur.state}, which does not handle ${event}`);
152
+ return settle({ state: hit.target, ctx: hit.ctx }, path, step);
153
+ };
154
+ // a step with no screen passes on its own along its normal way (a transition with no event, then DONE); one with no
155
+ // such way waits for an event the tutorial gives with `after`
156
+ const settle = (cur, path, step) => {
157
+ let c = cur;
158
+ for (let hops = 0; hops < 50 && kindOf(g, c.state) === 'server'; hops++) {
159
+ const ways = m.steps(c.state, c.ctx);
160
+ const next = pick(ways.filter((x) => x.event === null || x.event === 'DONE'), then);
161
+ if (next === undefined && ways.length > 0)
162
+ return c;
163
+ if (next === undefined)
164
+ throw new Stop(path, `${step}: the flow stops in ${c.state}, which has no screen and no way on`);
165
+ c = { state: next.target, ctx: next.ctx };
166
+ }
167
+ return c;
168
+ };
169
+ let cur = settle(start(g, m, scenario), ['scenario'], 'the start');
170
+ steps.forEach((s0, i) => {
171
+ if (!isMap(s0))
172
+ return;
173
+ const s = s0;
174
+ const path = ['steps', String(i)];
175
+ const step = `step ${i + 1}`;
176
+ then = thenOf(m, s);
177
+ if (s.intro === true) {
178
+ names(s.after).forEach((e, j) => {
179
+ cur = take(cur, e, Array.isArray(s.after) ? [...path, 'after', String(j)] : [...path, 'after'], step);
180
+ });
181
+ thenHolds(m, s, cur, path, step);
182
+ return;
183
+ }
184
+ const reveal = [...names(s.reveal)];
185
+ if (typeof s.press === 'string' && nodes[s.press].when !== undefined && !reveal.includes(s.press))
186
+ reveal.push(s.press);
187
+ let state = cur.state; // the state whose screen the step shows; null for a card
188
+ if (typeof s.cut === 'string') {
189
+ const wanted = s.cut;
190
+ let hit;
191
+ try {
192
+ hit = ex.configs.find((c) => c.state === wanted && reveal.every((id) => nodes[id].when === undefined || m.test(nodes[id].when, c.state, c.ctx)));
193
+ }
194
+ catch (err) {
195
+ throw new Stop([...path, 'reveal'], `${step}: ${err.message}`);
196
+ }
197
+ if (hit === undefined)
198
+ throw new Stop([...path, 'cut'], `${step}: no situation the flow reaches is in ${wanted}${reveal.length > 0 ? ` and shows ${reveal.join(', ')}` : ''}`);
199
+ cur = { state: hit.state, ctx: hit.ctx };
200
+ state = cur.state;
201
+ }
202
+ else if (s.end !== undefined) {
203
+ if (typeof s.end === 'string' && s.end !== cur.state)
204
+ throw new Stop([...path, 'end'], `${step}: the tutorial ends in ${s.end}, and the flow is in ${cur.state} here`);
205
+ if (flow.states[cur.state].type === 'final')
206
+ state = null;
207
+ else if (typeof s.end !== 'string')
208
+ throw new Stop([...path, 'end'], `${step}: the flow is in ${cur.state} here, which is no exit`);
209
+ if (isMap(s.card))
210
+ state = null;
211
+ }
212
+ else if (typeof s.show === 'string') {
213
+ if (s.show !== cur.state)
214
+ throw new Stop([...path, 'show'], `${step}: shows ${s.show}, and the flow is in ${cur.state} here`);
215
+ }
216
+ else if (s.card !== undefined) {
217
+ state = null;
218
+ }
219
+ if (state !== null && !hasScreen(state))
220
+ throw new Stop([...path, typeof s.cut === 'string' ? 'cut' : typeof s.show === 'string' ? 'show' : 'end'], `${step}: ${state} has no screen to show`);
221
+ for (const key of ['reveal', 'focus']) {
222
+ names(s[key]).forEach((id, j) => {
223
+ const where = Array.isArray(s[key]) ? [...path, key, String(j)] : [...path, key];
224
+ const n = nodes[id];
225
+ if (state === null)
226
+ throw new Stop(where, `${step}: ${key} ${String(id)} on a card, which shows no node`);
227
+ if (!shownIn(n, state))
228
+ throw new Stop(where, `${step}: ${key} ${String(id)}, which ${state} does not show`);
229
+ if (key === 'focus' && n.when !== undefined && !reveal.includes(id))
230
+ throw new Stop(where, `${step}: ${String(id)} is shown only when ${n.when}: list it under reveal`);
231
+ });
232
+ }
233
+ if (typeof s.press === 'string') {
234
+ const n = nodes[s.press];
235
+ const where = [...path, 'press'];
236
+ if (!shownIn(n, cur.state))
237
+ throw new Stop(where, `${step}: press ${s.press}, which ${cur.state} does not show`);
238
+ if ((n.disabledIn ?? []).includes(cur.state))
239
+ throw new Stop(where, `${step}: press ${s.press}, which is disabled in ${cur.state}`);
240
+ if (n.emits === undefined)
241
+ throw new Stop(where, `${step}: press ${s.press}, which sends no event`);
242
+ cur = take(cur, n.emits, where, step);
243
+ }
244
+ names(s.after).forEach((e, j) => {
245
+ cur = take(cur, e, Array.isArray(s.after) ? [...path, 'after', String(j)] : [...path, 'after'], step);
246
+ });
247
+ thenHolds(m, s, cur, path, step);
248
+ });
249
+ }
250
+ // On the diagram no state passes on its own: `show` and `end` walk the flow to their state along its normal way (a
251
+ // transition with no event, then DONE), and every other event is given with `after`
252
+ function replayDiagram(g, m, ex, steps, scenario) {
253
+ let cur = start(g, m, scenario);
254
+ let then = [];
255
+ const walkTo = (wanted, path, step) => {
256
+ const from = cur.state;
257
+ for (let hops = 0; cur.state !== wanted; hops++) {
258
+ const next = hops < 50 ? pick(m.steps(cur.state, cur.ctx).filter((x) => x.event === null || x.event === 'DONE'), then) : undefined;
259
+ if (next === undefined)
260
+ throw new Stop(path, `${step}: ${wanted} is not reached from ${from} without an event${cur.state === from ? '' : ` (the way stops in ${cur.state})`}`);
261
+ cur = { state: next.target, ctx: next.ctx };
262
+ }
263
+ };
264
+ steps.forEach((s0, i) => {
265
+ if (!isMap(s0))
266
+ return;
267
+ const s = s0;
268
+ const path = ['steps', String(i)];
269
+ const step = `step ${i + 1}`;
270
+ then = thenOf(m, s);
271
+ if (s.intro === true)
272
+ return;
273
+ if (typeof s.cut === 'string') {
274
+ const wanted = s.cut;
275
+ const hit = ex.configs.find((c) => c.state === wanted);
276
+ if (hit === undefined)
277
+ throw new Stop([...path, 'cut'], `${step}: no situation the flow reaches is in ${wanted}`);
278
+ cur = { state: hit.state, ctx: hit.ctx };
279
+ }
280
+ else if (typeof s.end === 'string') {
281
+ walkTo(s.end, [...path, 'end'], step);
282
+ if (g.flow.states[s.end].type !== 'final')
283
+ throw new Stop([...path, 'end'], `${step}: ends in ${s.end}, which is no exit`);
284
+ }
285
+ else if (typeof s.show === 'string') {
286
+ walkTo(s.show, [...path, 'show'], step);
287
+ }
288
+ names(s.after).forEach((e, j) => {
289
+ const where = Array.isArray(s.after) ? [...path, 'after', String(j)] : [...path, 'after'];
290
+ const hit = pick(m.steps(cur.state, cur.ctx).filter((x) => x.event === e), then);
291
+ if (hit === undefined)
292
+ throw new Stop(where, `${step}: the flow is in ${cur.state}, which does not handle ${String(e)}`);
293
+ cur = { state: hit.target, ctx: hit.ctx };
294
+ });
295
+ thenHolds(m, s, cur, path, step);
296
+ });
297
+ }