@delurio/cli 0.9.0 → 0.11.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/NOTICE +7 -0
  3. package/README.md +16 -15
  4. package/SPEC.md +37 -11
  5. package/js/changes.d.ts +17 -0
  6. package/js/cli.js +6 -0
  7. package/{dist → js}/edges.d.ts +2 -2
  8. package/js/edges.js +40 -0
  9. package/js/expr.js +25 -0
  10. package/js/graph.js +59 -0
  11. package/{dist → js}/html.d.ts +6 -6
  12. package/js/html.js +13 -0
  13. package/js/internal.js +408 -0
  14. package/js/kit.js +54 -0
  15. package/{dist → js}/model.d.ts +2 -2
  16. package/js/model.js +136 -0
  17. package/js/native.cjs +46 -0
  18. package/js/native.d.cts +322 -0
  19. package/{dist → js}/nav.d.ts +1 -1
  20. package/js/nav.js +70 -0
  21. package/{dist → js}/needs.d.ts +3 -2
  22. package/js/needs.js +30 -0
  23. package/{dist → js}/spine.d.ts +3 -3
  24. package/js/spine.js +22 -0
  25. package/{dist → js}/starts.d.ts +1 -3
  26. package/{dist → js}/story.d.ts +2 -2
  27. package/js/story.js +22 -0
  28. package/{dist → js}/wireframe.d.ts +4 -2
  29. package/js/wireframe.js +29 -0
  30. package/js/yaml.d.ts +20 -0
  31. package/js/yaml.js +40 -0
  32. package/package.json +41 -25
  33. package/schemas/domain.schema.json +3 -0
  34. package/dist/changes.d.ts +0 -25
  35. package/dist/changes.js +0 -101
  36. package/dist/check.d.ts +0 -23
  37. package/dist/check.js +0 -574
  38. package/dist/cli.d.ts +0 -2
  39. package/dist/cli.js +0 -194
  40. package/dist/compare.d.ts +0 -34
  41. package/dist/compare.js +0 -143
  42. package/dist/diff-flow.d.ts +0 -33
  43. package/dist/diff-flow.js +0 -547
  44. package/dist/diff-nav.d.ts +0 -20
  45. package/dist/diff-nav.js +0 -401
  46. package/dist/diff.d.ts +0 -25
  47. package/dist/diff.js +0 -331
  48. package/dist/domain-names.d.ts +0 -18
  49. package/dist/domain-names.js +0 -124
  50. package/dist/domain.d.ts +0 -25
  51. package/dist/domain.js +0 -110
  52. package/dist/edges.js +0 -120
  53. package/dist/expr.js +0 -157
  54. package/dist/graph.js +0 -236
  55. package/dist/html.js +0 -311
  56. package/dist/index-page.d.ts +0 -12
  57. package/dist/index-page.js +0 -50
  58. package/dist/invokes.d.ts +0 -10
  59. package/dist/invokes.js +0 -67
  60. package/dist/kit.js +0 -710
  61. package/dist/mermaid.d.ts +0 -3
  62. package/dist/mermaid.js +0 -50
  63. package/dist/model.js +0 -608
  64. package/dist/nav-page.d.ts +0 -15
  65. package/dist/nav-page.js +0 -283
  66. package/dist/nav.js +0 -578
  67. package/dist/needs.js +0 -311
  68. package/dist/pan.d.ts +0 -2
  69. package/dist/pan.js +0 -252
  70. package/dist/schemas.d.ts +0 -10
  71. package/dist/schemas.js +0 -266
  72. package/dist/spine.js +0 -156
  73. package/dist/starts.js +0 -88
  74. package/dist/story.js +0 -109
  75. package/dist/tutorial-check.d.ts +0 -9
  76. package/dist/tutorial-check.js +0 -297
  77. package/dist/ui-check.d.ts +0 -8
  78. package/dist/ui-check.js +0 -136
  79. package/dist/watch.d.ts +0 -5
  80. package/dist/watch.js +0 -114
  81. package/dist/wireframe.js +0 -273
  82. package/dist/yaml.d.ts +0 -19
  83. package/dist/yaml.js +0 -134
  84. /package/{dist → js}/expr.d.ts +0 -0
  85. /package/{dist → js}/graph.d.ts +0 -0
  86. /package/{dist → js}/kit.d.ts +0 -0
package/dist/check.js DELETED
@@ -1,574 +0,0 @@
1
- // `check`: every graph under a folder, as a project's CI runs it (graphs/agents/cli.check, SPEC.md §10). It reads the
2
- // files and nothing else, writes no page, and gives each finding as a GNU error line, or as SARIF 2.1.0 with
3
- // --format sarif. Exit 0 when clean, 1 when a graph cannot be loaded or is written for a newer format, 2 when an error
4
- // is found under --strict (and, with --baseline, new since that run).
5
- import { createHash } from 'node:crypto';
6
- import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
- import { basename, dirname, join, relative, resolve } from 'node:path';
8
- import { keyAt, parsingOnce, readYaml } from './yaml.js';
9
- import { alternatives, GraphError, load, placed } from './graph.js';
10
- import { checkAssertions, explore, Model, ModelError } from './model.js';
11
- import { stepsByEvents } from './story.js';
12
- import { renderScreens } from './wireframe.js';
13
- import { checkStarts } from './starts.js';
14
- import { checkChanges, flowDomain } from './changes.js';
15
- import { checkUi } from './ui-check.js';
16
- import { checkInvokes } from './invokes.js';
17
- import { checkTutorial } from './tutorial-check.js';
18
- import { KitError, resolveKit } from './kit.js';
19
- import { checkGoals, findings, loadNav, viewOf } from './nav.js';
20
- import { schemaKindOf, validateFile } from './schemas.js';
21
- import { inReadingOrder, mergeDomain } from './domain.js';
22
- import { checkDomainNames } from './domain-names.js';
23
- import { checkNeeds } from './needs.js';
24
- export const CHECK_USAGE = [
25
- ' node src/cli.ts check <graphs folder>... [--strict] [--baseline <sarif>] [--format sarif --output <file>] [--app <dir>]',
26
- ' checks every graph under the folders and writes nothing else: GNU error lines on stdout, or SARIF 2.1.0;',
27
- ' exit 0 clean, 1 a graph cannot be loaded or needs a newer format, 2 an error under --strict (new since --baseline);',
28
- ' the evidence of needs is found under --app, the application\'s repository root (default: the working directory)',
29
- ].join('\n');
30
- const FORMAT = 'delurio-graph/0';
31
- const SKIP = new Set(['viz', 'video', 'recording', 'node_modules', '.git']);
32
- const RULES = [
33
- { id: 'load', text: 'The graph cannot be loaded', level: 'error' },
34
- { id: 'format-newer', text: 'The graph is written for a newer format than this checker reads', level: 'error' },
35
- { id: 'schema', text: "A graph file does not follow its kind's schema (SPEC.md)", level: 'error' },
36
- { id: 'domain-twice', text: 'A value of a domain is given in two of its files (SPEC.md §5)', level: 'error' },
37
- { id: 'domain-place', text: 'A domain file is not with the rest of its domain (SPEC.md §1)', level: 'error' },
38
- { id: 'server-fn-http', text: 'A server function is given a route, a query or an operationId, which only an HTTP operation has (SPEC.md §5)', level: 'error' },
39
- { id: 'entity-unknown', text: "An action's returns or a references names an entity its domain does not have (SPEC.md §5)", level: 'error' },
40
- { id: 'field-unknown', text: "An entity's key or required names a field the entity does not have (SPEC.md §5)", level: 'error' },
41
- { id: 'assertion-violated', text: 'A guarantee of the flow is broken by a reachable situation', level: 'error' },
42
- { id: 'main-story-unwalkable', text: 'The declared main story cannot be walked', level: 'error' },
43
- { id: 'catalog-key-missing', text: "A catalog key the screens use is missing from a locale's catalog", level: 'error' },
44
- { id: 'sample-missing', text: 'A catalog message has a placeholder with no sample value', level: 'error' },
45
- { id: 'no-renderer', text: 'A component has no renderer', level: 'error' },
46
- { id: 'kit-uncovered', text: "The kit does not cover a component or an intent", level: 'error' },
47
- { id: 'list-item-outside-list', text: 'A list item is drawn outside a list', level: 'error' },
48
- { id: 'hand-over', text: 'A started flow cannot begin with what it is given', level: 'error' },
49
- { id: 'changes-note-missing', text: 'A flow whose steps write has no changes note (SPEC.md §4)', level: 'error' },
50
- { id: 'changes-note-locale', text: "The changes note is missing from a locale's catalog", level: 'error' },
51
- { id: 'changes-note-gap', text: 'A writing flow says why it has no changes note yet: counted, and fails nothing (SPEC.md §4)', level: 'note' },
52
- { id: 'task-locale', text: "The flow's name for its users is missing from a locale's catalog (SPEC.md §4)", level: 'error' },
53
- { id: 'source-missing', text: 'A state of a captured flow names no code (SPEC.md §9)', level: 'error' },
54
- { id: 'focus-not-shown', text: 'A focus or a returnsFocus gives the focus to a node that is not shown there (SPEC.md §4)', level: 'error' },
55
- { id: 'returns-focus-not-dialog', text: 'A returnsFocus does not start at a dialog (SPEC.md §4)', level: 'error' },
56
- { id: 'state-no-way-out', text: 'A state that is not an exit has no way out (SPEC.md §2)', level: 'error' },
57
- { id: 'state-unreachable', text: 'No situation the flow starts in reaches the state (SPEC.md §2)', level: 'error' },
58
- { id: 'tutorial-mismatch', text: 'A tutorial no longer matches its flow (SPEC.md §7)', level: 'error' },
59
- { id: 'evidence-unresolved', text: "A need's evidence names what is not there (SPEC.md §13)", level: 'error' },
60
- { id: 'need-no-evidence', text: 'A need that is not missing names no evidence outside the graph (SPEC.md §13)', level: 'error' },
61
- { id: 'need-unlisted', text: "A missing need is not in the product's gaps (SPEC.md §13)", level: 'error' },
62
- { id: 'need-twice', text: "A need's id is given twice in its flow's needs (SPEC.md §13)", level: 'error' },
63
- { id: 'needs-place', text: 'A needs file is beside no flow, or is the needs of another one (SPEC.md §13)', level: 'error' },
64
- { id: 'gap-met', text: 'The gaps list a need that is met (SPEC.md §13)', level: 'error' },
65
- { id: 'gap-unknown', text: 'The gaps list a need that no flow under them has (SPEC.md §13)', level: 'error' },
66
- { id: 'need-gap', text: 'A need that is missing, listed in the gaps: counted, and fails nothing (SPEC.md §13)', level: 'note' },
67
- { id: 'invoke-unknown', text: "An invoke or a failures entry names an action its flow's domain does not have, or the domain is not found (SPEC.md §5)", level: 'error' },
68
- { id: 'refusal-unknown', text: 'A failure class lists a code that is neither a refusal of its action nor a transport code (SPEC.md §2, §5)', level: 'error' },
69
- { id: 'policy-unknown', text: 'A policy names an action or an entity its domain does not have (SPEC.md §5)', level: 'error' },
70
- { id: 'graph-warning', text: 'Another warning of the graph', level: 'error' },
71
- { id: 'nav-problem', text: 'A problem of the navigation graph', level: 'error' },
72
- { id: 'nav-note', text: 'A note on the navigation graph', level: 'warning' },
73
- ];
74
- const LEVEL = new Map(RULES.map((r) => [r.id, r.level]));
75
- // the rules whose errors stop the run (exit 1) however --strict and --baseline read them
76
- const BREAKING = new Set(['load', 'format-newer']);
77
- export const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
78
- // the 1-based line and column of the first occurrence of `needle`, else the file's start
79
- function placeOf(abs, needle) {
80
- if (needle === null || !existsSync(abs))
81
- return { line: 1, column: 1 };
82
- const lines = readFileSync(abs, 'utf8').split('\n');
83
- for (let i = 0; i < lines.length; i++) {
84
- const c = lines[i].indexOf(needle);
85
- if (c >= 0)
86
- return { line: i + 1, column: c + 1 };
87
- }
88
- return { line: 1, column: 1 };
89
- }
90
- // every graph folder at or under root, in path order
91
- export function graphDirs(root, out = []) {
92
- if (existsSync(join(root, 'flow.yaml')) || existsSync(join(root, 'nav.yaml')))
93
- out.push(root);
94
- for (const name of readdirSync(root).sort()) {
95
- if (SKIP.has(name) || name.startsWith('.'))
96
- continue;
97
- const sub = join(root, name);
98
- if (statSync(sub).isDirectory())
99
- graphDirs(sub, out);
100
- }
101
- return out;
102
- }
103
- // every file under root that a schema covers (flow, ui, nav, nav.extracted, domain, catalog), in path order
104
- function graphFiles(root, out = []) {
105
- for (const name of readdirSync(root).sort()) {
106
- if (SKIP.has(name) || name.startsWith('.'))
107
- continue;
108
- const path = join(root, name);
109
- if (statSync(path).isDirectory())
110
- graphFiles(path, out);
111
- else if (schemaKindOf(path) !== null)
112
- out.push(path);
113
- }
114
- return out;
115
- }
116
- // the format the file says it is written in: null when it is this one
117
- function newerFormat(abs) {
118
- const doc = readYaml(readFileSync(abs, 'utf8'));
119
- const s = typeof doc?.schema === 'string' ? doc.schema : FORMAT;
120
- return s === FORMAT ? null : s;
121
- }
122
- function rel(abs) {
123
- return relative(process.cwd(), abs) || '.';
124
- }
125
- function result(rule, file, at, message, graph, element, notes = []) {
126
- return { rule, level: LEVEL.get(rule) ?? 'error', file: rel(file), line: at.line, column: at.column, message, graph, element, notes };
127
- }
128
- // a warning raised while checking a flow, sorted into its rule and placed in its file
129
- function fromWarning(dir, graph, w) {
130
- const flow = join(dir, 'flow.yaml');
131
- const ui = join(dir, 'ui.yaml');
132
- let m;
133
- if ((m = /^catalog key (\S+) is missing/.exec(w)))
134
- return result('catalog-key-missing', ui, placeOf(ui, m[1]), w, graph, m[1]);
135
- if ((m = /^no sample value for \{(\w+)\} in (\S+)/.exec(w)))
136
- return result('sample-missing', ui, placeOf(ui, m[2]), w, graph, `${m[2]}/${m[1]}`);
137
- if ((m = /^(\S+): ListItem outside a List/.exec(w)))
138
- return result('list-item-outside-list', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
139
- if ((m = /\(node (\S+?)\)/.exec(w)) && /^kit /.test(w))
140
- return result('kit-uncovered', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
141
- if ((m = /^(\S+): component .* has no wireframe renderer/.exec(w)))
142
- return result('no-renderer', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
143
- if (/declared main story cannot be walked/.test(w))
144
- return result('main-story-unwalkable', flow, placeOf(flow, 'main:'), w, graph, 'main');
145
- if ((m = /^(\S+) starts (\S+): (.*)$/.exec(w)))
146
- return result('hand-over', flow, placeOf(flow, `flow: ${m[2]}`), w, graph, `${m[1]}->${m[2]}`);
147
- if (/has no changes note/.test(w))
148
- return result('changes-note-missing', ui, placeOf(ui, 'samples:'), w, graph, 'changes');
149
- if ((m = /^the changes note (\S+) is not in the (\w+) catalog/.exec(w)))
150
- return result('changes-note-locale', ui, placeOf(ui, 'changes:'), w, graph, `changes/${m[2]}`);
151
- return result('graph-warning', existsSync(ui) ? ui : flow, { line: 1, column: 1 }, w, graph, w);
152
- }
153
- // the words of the screens in each locale but the one ui.yaml names (SPEC.md §4): a key the screens use that a locale's
154
- // catalog lacks, at the key's line, as for the catalog ui.yaml names; a locale whose catalog is not there, at `locales`
155
- function checkLocales(g, dir) {
156
- if (g.ui.absent === true)
157
- return [];
158
- const ui = join(dir, 'ui.yaml');
159
- const named = join(dir, g.ui.catalog);
160
- const out = [];
161
- for (const locale of g.ui.locales ?? []) {
162
- const name = join(dirname(g.ui.catalog), `${locale}.json`);
163
- const abs = join(dir, name);
164
- if (abs === named)
165
- continue;
166
- let catalog;
167
- try {
168
- catalog = JSON.parse(readFileSync(abs, 'utf8'));
169
- }
170
- catch (err) {
171
- const text = readFileSync(ui, 'utf8');
172
- const why = existsSync(abs) ? `is not JSON: ${err.message}` : 'does not exist';
173
- out.push(result('catalog-key-missing', ui, keyAt(text, ['locales']), `the ${locale} catalog, ${name}, ${why}: every word the screens use is missing in ${locale}`, g.flow.id, `catalog/${locale}`));
174
- continue;
175
- }
176
- const missing = [];
177
- const collect = (m) => {
178
- const key = /^catalog key (\S+) is missing/.exec(m)?.[1];
179
- if (key !== undefined && !missing.includes(key))
180
- missing.push(key);
181
- };
182
- const other = { ...g, catalog: catalog !== null && typeof catalog === 'object' ? catalog : {} };
183
- renderScreens(other, collect, null);
184
- checkUi(other, collect);
185
- for (const key of missing)
186
- out.push(result('catalog-key-missing', ui, placeOf(ui, key), `catalog key ${key} is missing from the ${locale} catalog, ${name}`, g.flow.id, `${key}/${locale}`));
187
- }
188
- return out;
189
- }
190
- // the states that some transition leads to, whatever its guard
191
- function targeted(g) {
192
- const out = new Set();
193
- for (const st of Object.values(g.flow.states)) {
194
- for (const a of st.always ?? [])
195
- out.add(a.target);
196
- for (const spec of Object.values(st.on ?? {}))
197
- for (const a of alternatives(spec))
198
- out.add(a.target);
199
- }
200
- return out;
201
- }
202
- function checkFlow(dir, domains) {
203
- const file = join(dir, 'flow.yaml');
204
- const g = load(dir);
205
- let kit;
206
- try {
207
- kit = resolveKit(dir, g.ui.kit, undefined);
208
- }
209
- catch (err) {
210
- throw g.ui.kit === undefined ? err : placed(err, { file: 'ui.yaml', path: ['kit'] });
211
- }
212
- const model = new Model(g.flow);
213
- const ex = explore(model);
214
- const out = [];
215
- const flowText = readFileSync(file, 'utf8');
216
- // a state the flow stops in for good though it is no exit, and a state no situation reaches (SPEC.md §2)
217
- const led = targeted(g);
218
- for (const [name, st] of Object.entries(g.flow.states)) {
219
- const at = () => keyAt(flowText, ['states', name]);
220
- const element = `states/${name}`;
221
- const ways = Object.keys(st.on ?? {}).length + (st.always ?? []).length;
222
- if (st.type !== 'final' && ways === 0 && st.invoke === undefined) {
223
- out.push(result('state-no-way-out', file, at(), `state ${name} is not an exit and has no way out: it has no on, always or invoke, so the flow stops there; make it an exit (type: final) or give it a transition (SPEC.md §2)`, g.flow.id, element));
224
- }
225
- if (!ex.atState.has(name)) {
226
- const why = led.has(name) ? 'the transitions that lead to it are never taken: the states they leave are not reached, or their guards never hold' : 'no transition leads to it';
227
- out.push(result('state-unreachable', file, at(), `state ${name} is reached by no situation the flow starts in: ${why} (SPEC.md §2)`, g.flow.id, element));
228
- }
229
- }
230
- const warnings = [];
231
- const warn = (m) => {
232
- if (!warnings.includes(m))
233
- warnings.push(m);
234
- };
235
- for (const a of checkAssertions(model, ex)) {
236
- if (a.violation === undefined)
237
- continue;
238
- const at = placeOf(file, `id: ${a.id}`);
239
- const start = Object.entries(a.violation.start).map(([k, v]) => `${k} = ${String(v)}`).join(', ');
240
- const notes = [{ file: rel(file), ...at, message: `start: ${start || 'the initial context'}` }];
241
- a.violation.events.forEach((e, i) => notes.push({ file: rel(file), ...at, message: `step ${i + 1}: ${e}` }));
242
- notes.push({ file: rel(file), ...at, message: `reached: ${a.violation.state}` });
243
- out.push(result('assertion-violated', file, at, `${a.id} is broken: ${a.say ?? a.never}`, g.flow.id, a.id, notes));
244
- }
245
- if (g.flow.main !== undefined && stepsByEvents(model, g.flow.main) === null)
246
- warn('the declared main story cannot be walked: an event is not possible where it is sent');
247
- renderScreens(g, warn, kit);
248
- if (g.ui.absent !== true) {
249
- const ui = join(dir, 'ui.yaml');
250
- const text = readFileSync(ui, 'utf8');
251
- for (const p of checkUi(g, warn))
252
- out.push(result(p.rule, ui, keyAt(text, p.path), p.message, g.flow.id, p.element));
253
- }
254
- out.push(...checkLocales(g, dir));
255
- for (const h of checkStarts(g, model, ex))
256
- for (const p of h.problems)
257
- warn(`${h.from} starts ${h.flow}: ${p}`);
258
- // the flow's domain, looked up once for the rules that read it
259
- let domain;
260
- const domainOf = () => (domain === undefined ? (domain = flowDomain(g, domains)) : domain);
261
- const changes = checkChanges(g, domainOf);
262
- for (const p of changes?.problems ?? [])
263
- warn(p);
264
- for (const w of warnings)
265
- out.push(fromWarning(dir, g.flow.id, w));
266
- // a writing flow whose app has no changes message yet says why: a gap of the flow, at the level note (SPEC.md §4)
267
- if (changes !== null && changes.missing !== null) {
268
- const ui = join(dir, 'ui.yaml');
269
- const message = `its steps write (${changes.writes.join(', ')}), and its changes note is missing: ${changes.missing}; Rehber does not guide its writing steps (SPEC.md §4)`;
270
- out.push(result('changes-note-gap', ui, keyAt(readFileSync(ui, 'utf8'), ['changes', 'missing']), message, g.flow.id, 'changes/missing'));
271
- }
272
- for (const p of checkInvokes(g, domainOf))
273
- out.push(result(p.rule, file, keyAt(flowText, p.path), p.message, g.flow.id, p.element));
274
- const tutorial = join(dir, 'tutorial.yaml');
275
- if (existsSync(tutorial)) {
276
- const text = readFileSync(tutorial, 'utf8');
277
- for (const p of checkTutorial(g, model, ex, text)) {
278
- const at = p.line === undefined ? keyAt(text, p.path) : { line: p.line, column: p.column ?? 1 };
279
- out.push(result('tutorial-mismatch', tutorial, at, p.message, g.flow.id, `tutorial.yaml#/${p.path.join('/')}`));
280
- }
281
- }
282
- // a captured flow is read from code, so every state names the code that makes it true; an exit may leave it out, as
283
- // the transition into it names that code (SPEC.md §9)
284
- if (g.flow.status === 'captured') {
285
- for (const [name, st] of Object.entries(g.flow.states)) {
286
- if (st.source !== undefined || st.type === 'final')
287
- continue;
288
- out.push(result('source-missing', file, keyAt(flowText, ['states', name]), `state ${name} names no code: in a captured flow every state but an exit carries source: <path>:<line> (SPEC.md §9)`, g.flow.id, `states/${name}`));
289
- }
290
- }
291
- return out;
292
- }
293
- // what only an HTTP operation has (SPEC.md §5), and why a server function has none of it
294
- const HTTP_ONLY = {
295
- route: 'a route is an operation that others call over HTTP, and a server function is called only by the product\'s own pages: give one of them',
296
- query: 'a server function\'s input is its body, whatever its method',
297
- operationId: 'a server function is no operation of an OpenAPI document',
298
- };
299
- // a server function that is also given what only an HTTP operation has (SPEC.md §5), at its `serverFn` with a note at
300
- // the other key; the two may come from two files of a split domain, so the domain is read as one first
301
- function checkServerFunctions(parts, doc, id) {
302
- const out = [];
303
- const read = parts.map((p) => {
304
- try {
305
- return readYaml(p.text);
306
- }
307
- catch {
308
- return null;
309
- }
310
- });
311
- // the part that gives the action's key, and where in it
312
- const given = (name, key) => {
313
- const i = read.findIndex((d) => d?.actions?.[name]?.[key] !== undefined);
314
- return i < 0 ? null : { file: parts[i].file, ...keyAt(parts[i].text, ['actions', name, key]) };
315
- };
316
- const actions = (doc.actions ?? {});
317
- for (const [name, a] of Object.entries(actions)) {
318
- if (a === null || typeof a !== 'object' || a.serverFn === undefined)
319
- continue;
320
- const at = given(name, 'serverFn');
321
- if (at === null)
322
- continue;
323
- for (const [key, why] of Object.entries(HTTP_ONLY)) {
324
- if (a[key] === undefined)
325
- continue;
326
- const other = given(name, key);
327
- const said = key === 'route' ? `a route, ${String(a.route)}` : key === 'query' ? 'a query' : `an operationId, ${String(a.operationId)}`;
328
- const notes = other === null ? [] : [{ file: rel(other.file), line: other.line, column: other.column, message: `its ${key} is given here` }];
329
- out.push(result('server-fn-http', at.file, at, `the action ${name} is a server function (serverFn: ${String(a.serverFn)}) and has ${said}: ${why} (SPEC.md §5)`, id, `actions/${name}/${key}`, notes));
330
- }
331
- }
332
- return out;
333
- }
334
- // whether a domain's file gives the entity
335
- function givesEntity(text, entity) {
336
- try {
337
- const entities = readYaml(text)?.entities;
338
- return entities !== null && typeof entities === 'object' && Object.hasOwn(entities, entity);
339
- }
340
- catch {
341
- return false;
342
- }
343
- }
344
- // the domains under root, each the domain files of one directory read as one (SPEC.md §5): a value given in two of
345
- // them, a file whose id is not its directory's, a domain whose files sit in two directories, a server function given
346
- // what only an HTTP operation has, and a name of an entity, a field or an action that the domain does not have
347
- function checkDomains(files) {
348
- const byDir = new Map();
349
- for (const f of files)
350
- if (schemaKindOf(f) === 'domain')
351
- byDir.set(dirname(f), [...(byDir.get(dirname(f)) ?? []), f]);
352
- const out = [];
353
- const dirsOf = new Map(); // a domain's id -> the directories that hold it
354
- const domains = [...byDir].map(([dir, list]) => {
355
- const parts = inReadingOrder(list).map((file) => ({ file, text: readFileSync(file, 'utf8') }));
356
- return { dir, parts, merged: mergeDomain(parts) };
357
- });
358
- // an entity of another domain, for the note of a name that this one does not have
359
- const elsewhere = (self) => (entity) => {
360
- for (const { dir, parts, merged } of domains) {
361
- const id = merged.id ?? rel(dir);
362
- const entities = merged.doc.entities;
363
- if (id === self || entities === null || typeof entities !== 'object' || !Object.hasOwn(entities, entity))
364
- continue;
365
- const part = parts.find((p) => givesEntity(p.text, entity)) ?? parts[0];
366
- return { domain: id, file: part.file, ...keyAt(part.text, ['entities', entity]) };
367
- }
368
- return null;
369
- };
370
- for (const { dir, parts, merged } of domains) {
371
- const id = merged.id ?? rel(dir);
372
- for (const p of merged.problems) {
373
- const notes = p.first === undefined ? [] : [{ file: rel(p.first.file), line: p.first.line, column: p.first.column, message: 'given first here' }];
374
- out.push(result(p.rule, p.file, p, p.message, id, p.element, notes));
375
- }
376
- out.push(...checkServerFunctions(parts, merged.doc, id));
377
- for (const p of checkDomainNames(parts, merged.doc, id, elsewhere(id))) {
378
- out.push(result(p.rule, p.file, p, p.message, id, p.element, p.notes.map((n) => ({ ...n, file: rel(n.file) }))));
379
- }
380
- if (merged.id !== null)
381
- dirsOf.set(merged.id, [...(dirsOf.get(merged.id) ?? []), dir]);
382
- }
383
- for (const [id, dirs] of dirsOf) {
384
- for (const dir of dirs.slice(1)) {
385
- const file = inReadingOrder(byDir.get(dir) ?? [])[0];
386
- out.push(result('domain-place', file, placeOf(file, 'id:'), `the domain ${id} is in ${rel(dirs[0])}/ too: a domain sits in one directory, so every flow that names it reads all of it (SPEC.md §1)`, id, `${basename(file)}#/id`));
387
- }
388
- }
389
- return out;
390
- }
391
- function checkNav(dir) {
392
- const file = join(dir, 'nav.yaml');
393
- const { g, warnings } = loadNav(dir, undefined);
394
- const views = g.personas.map((p) => viewOf(g, p));
395
- const found = findings(g, views, checkGoals(g, views));
396
- const out = found.map((f) => result(f.level === 'problem' ? 'nav-problem' : 'nav-note', file, { line: 1, column: 1 }, `${f.say} (${f.code})`, g.id, f.code, f.detail.map((d) => ({ file: rel(file), line: 1, column: 1, message: d }))));
397
- for (const w of warnings)
398
- out.push(result('graph-warning', file, { line: 1, column: 1 }, w, g.id, w));
399
- return out;
400
- }
401
- // the level a finding is printed at, and counted at: an error known from the baseline is a warning, as it fails no
402
- // run, but one that stops the run (it cannot be loaded) is an error however often it was seen
403
- const printedLevel = (r) => (r.level === 'error' && r.baselineState === 'unchanged' && !BREAKING.has(r.rule) ? 'warning' : r.level);
404
- // where a load error is (SPEC.md §10): the place the loader or the model gave it, at the keys it names or the line a
405
- // parser gave, in the file it names; else the line a YAML parser gave; else the start of the graph's own file
406
- function loadPlace(dir, file, err) {
407
- const place = err.place;
408
- const at = place === undefined ? file : join(dir, place.file);
409
- if (place?.line !== undefined)
410
- return { file: at, line: place.line, column: place.column ?? 1 };
411
- const linePos = err.linePos?.[0];
412
- if (linePos !== undefined)
413
- return { file: at, line: linePos.line, column: linePos.col };
414
- if (place?.path !== undefined && existsSync(at))
415
- return { file: at, ...keyAt(readFileSync(at, 'utf8'), place.path) };
416
- return { file: at, line: 1, column: 1 };
417
- }
418
- const fingerprint = (r) => createHash('sha256').update(`${r.rule}|${r.graph}|${r.element}`).digest('hex').slice(0, 32);
419
- function baselinePrints(file) {
420
- const doc = JSON.parse(readFileSync(file, 'utf8'));
421
- const out = new Set();
422
- for (const run of doc.runs ?? [])
423
- for (const r of run.results ?? [])
424
- if (r.fingerprints?.['delurio/v1'] !== undefined)
425
- out.add(r.fingerprints['delurio/v1']);
426
- return out;
427
- }
428
- function toolVersion() {
429
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
430
- return pkg.version ?? '0.0.0';
431
- }
432
- function sarif(results, exitCode) {
433
- const used = RULES.filter((r) => results.some((x) => x.rule === r.id));
434
- return {
435
- $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
436
- version: '2.1.0',
437
- runs: [
438
- {
439
- tool: {
440
- driver: {
441
- name: 'delurio',
442
- version: toolVersion(),
443
- informationUri: 'https://delur.io',
444
- rules: used.map((r) => ({ id: r.id, shortDescription: { text: r.text }, defaultConfiguration: { level: r.level } })),
445
- },
446
- },
447
- automationDetails: { id: 'delurio/check/' },
448
- invocations: [{ executionSuccessful: exitCode !== 1, exitCode }],
449
- results: results.map((r) => ({
450
- ruleId: r.rule,
451
- ruleIndex: used.findIndex((u) => u.id === r.rule),
452
- level: r.level,
453
- message: { text: r.message },
454
- locations: [
455
- {
456
- physicalLocation: { artifactLocation: { uri: r.file.split('\\').join('/') }, region: { startLine: r.line, startColumn: r.column } },
457
- logicalLocations: [{ fullyQualifiedName: `${r.graph}/${r.element}` }],
458
- },
459
- ],
460
- fingerprints: { 'delurio/v1': fingerprint(r) },
461
- ...(r.notes.length > 0 && r.rule === 'assertion-violated'
462
- ? { codeFlows: [{ threadFlows: [{ locations: r.notes.map((n) => ({ location: { message: { text: n.message } } })) }] }] }
463
- : {}),
464
- ...(r.baselineState === undefined ? {} : { baselineState: r.baselineState }),
465
- })),
466
- },
467
- ],
468
- };
469
- }
470
- // every text the check reads is parsed once in it (`parsingOnce`), however many graphs read it
471
- export function checkMain(args) {
472
- return parsingOnce(() => checkRun(args));
473
- }
474
- function checkRun(args) {
475
- const flag = (name) => {
476
- const i = args.indexOf(name);
477
- return i >= 0 ? args[i + 1] : undefined;
478
- };
479
- const withValue = ['--baseline', '--format', '--output', '--app'];
480
- const dirs = args.filter((a, i) => !a.startsWith('--') && !withValue.includes(args[i - 1] ?? ''));
481
- if (dirs.length === 0) {
482
- console.error(`usage:\n${CHECK_USAGE}`);
483
- return 1;
484
- }
485
- const notFolder = dirs.find((d) => !existsSync(d) || !statSync(d).isDirectory());
486
- if (notFolder !== undefined) {
487
- console.error(`${notFolder} is not a folder\nusage:\n${CHECK_USAGE}`);
488
- return 1;
489
- }
490
- // every folder given, each graph and file once though one folder holds another
491
- const roots = dirs.map((d) => resolve(d));
492
- const dirsOfGraphs = [...new Set(roots.flatMap((r) => graphDirs(r)))];
493
- const strict = args.includes('--strict');
494
- const format = flag('--format') ?? 'text';
495
- const output = flag('--output');
496
- const baseline = flag('--baseline');
497
- if (format !== 'text' && format !== 'sarif') {
498
- console.error(`--format is text or sarif, not ${format}`);
499
- return 1;
500
- }
501
- const appGiven = flag('--app');
502
- if (appGiven !== undefined && (!existsSync(appGiven) || !statSync(appGiven).isDirectory())) {
503
- console.error(`--app ${appGiven} is not a folder\nusage:\n${CHECK_USAGE}`);
504
- return 1;
505
- }
506
- const app = resolve(appGiven ?? '.');
507
- const results = [];
508
- const domains = new Map(); // the domains found, for every flow that names one
509
- let broken = false;
510
- for (const d of dirsOfGraphs) {
511
- const file = existsSync(join(d, 'flow.yaml')) ? join(d, 'flow.yaml') : join(d, 'nav.yaml');
512
- try {
513
- const newer = newerFormat(file);
514
- if (newer !== null) {
515
- broken = true;
516
- results.push(result('format-newer', file, placeOf(file, 'schema:'), `written in ${newer}; this checker reads ${FORMAT}: pin a version that reads it`, rel(d), 'schema'));
517
- continue;
518
- }
519
- results.push(...(file.endsWith('flow.yaml') ? checkFlow(d, domains) : checkNav(d)));
520
- }
521
- catch (err) {
522
- if (!(err instanceof GraphError || err instanceof ModelError || err instanceof KitError || (err instanceof Error && err.name === 'YAMLParseError')))
523
- throw err;
524
- broken = true;
525
- const at = loadPlace(d, file, err);
526
- results.push(result('load', at.file, at, err.message.split('\n')[0], rel(d), 'load'));
527
- }
528
- }
529
- // every graph file against its kind's schema: what an editor with the schemas marks, check reports
530
- const files = [...new Set(roots.flatMap((r) => graphFiles(r)))];
531
- for (const file of files) {
532
- for (const f of validateFile(file))
533
- results.push(result('schema', file, f, f.message, f.graph ?? rel(file), f.element));
534
- }
535
- results.push(...checkDomains(files));
536
- // each flow's needs held to their evidence, and the product's gaps to its needs (SPEC.md §13)
537
- const needs = checkNeeds(files, app);
538
- for (const p of needs.problems)
539
- results.push(result(p.rule, p.file, p, p.message, p.graph, p.element));
540
- results.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column || a.rule.localeCompare(b.rule) || a.message.localeCompare(b.message));
541
- if (baseline !== undefined) {
542
- const prints = baselinePrints(baseline);
543
- for (const r of results)
544
- r.baselineState = prints.has(fingerprint(r)) ? 'unchanged' : 'new';
545
- }
546
- const failing = results.filter((r) => r.level === 'error' && !BREAKING.has(r.rule) && (r.baselineState === undefined || r.baselineState === 'new'));
547
- const exitCode = broken ? 1 : strict && failing.length > 0 ? 2 : 0;
548
- if (format === 'sarif') {
549
- const text = `${JSON.stringify(sarif(results, exitCode), null, 2)}\n`;
550
- if (output === undefined)
551
- process.stdout.write(text);
552
- else
553
- writeFileSync(output, text);
554
- }
555
- if (format === 'text' || output !== undefined) {
556
- for (const r of results) {
557
- console.log(`${r.file}:${r.line}:${r.column}: ${printedLevel(r)}: ${r.message} [${r.rule}]`);
558
- for (const n of r.notes)
559
- console.log(`${n.file}:${n.line}:${n.column}: note: ${n.message}`);
560
- }
561
- const graphs = dirsOfGraphs.length;
562
- const errors = results.filter((r) => printedLevel(r) === 'error').length;
563
- const warnings = results.filter((r) => printedLevel(r) === 'warning').length;
564
- // the gaps, once a flow has needs: every need that is missing, listed or not, and those the base run did not have
565
- const fresh = results.filter((r) => r.rule === 'need-gap' && r.baselineState === 'new').length;
566
- const gaps = needs.files === 0 ? '' : `, ${count(needs.gaps, 'gap')} of ${count(needs.needs, 'need')}${fresh > 0 ? ` (${fresh} new)` : ''}`;
567
- // the changes notes that writing flows say are missing (SPEC.md §4), once there is one
568
- const notes = results.filter((r) => r.rule === 'changes-note-gap');
569
- const newNotes = notes.filter((r) => r.baselineState === 'new').length;
570
- const missingNotes = notes.length === 0 ? '' : `, ${count(notes.length, 'missing changes note')}${newNotes > 0 ? ` (${newNotes} new)` : ''}`;
571
- console.error(`delurio check: ${count(graphs, 'graph')}, ${count(errors, 'error')}, ${count(warnings, 'warning')}${gaps}${missingNotes}; exit ${exitCode}`);
572
- }
573
- return exitCode;
574
- }
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};