@skillstech/thunderlang 0.5.10 → 0.5.12
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/CHANGELOG.md +450 -0
- package/dist/core.cjs +30434 -7577
- package/dist/index.cjs +28576 -5328
- package/dist/learn.cjs +24201 -5367
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +49 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +65 -14
- package/src/model.mjs +496 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1017 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
package/src/model.mjs
CHANGED
|
@@ -2,16 +2,28 @@
|
|
|
2
2
|
// choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
|
|
3
3
|
// and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
|
|
4
4
|
// them may say more than the model does. Browser-safe: takes [{ path, source }].
|
|
5
|
-
import { readCode } from './read.mjs';
|
|
5
|
+
import { readCode, INFRA_LANGUAGES } from './read.mjs';
|
|
6
6
|
import { readableLanguage, readingOf } from './read-repo.mjs';
|
|
7
7
|
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
8
8
|
import { visualFor, LEVELS, DOES } from './visual.mjs';
|
|
9
9
|
import { makeThingReaders } from './things-langs.mjs';
|
|
10
10
|
import { sqlThings } from './sql.mjs';
|
|
11
|
+
import { rThings } from './rlang.mjs';
|
|
12
|
+
import { psThings } from './powershell.mjs';
|
|
13
|
+
import { splitLogic, closeOf, isCodeWords } from './faithful.mjs';
|
|
14
|
+
import { detailParts } from './meaning.mjs';
|
|
15
|
+
import { linkSystem, callsSummary } from './system.mjs';
|
|
11
16
|
|
|
12
17
|
export const MODEL_SCHEMA = 'thunder-model-v1';
|
|
13
|
-
/**
|
|
14
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Languages whose classes, records, and choices are read today. Others still get every function. Shell is not here
|
|
20
|
+
* because it has no classes: a shell file is its functions and its top-level script.
|
|
21
|
+
*/
|
|
22
|
+
export const THING_LANGUAGES = ['python', 'typescript', 'javascript', 'java', 'csharp', 'kotlin', 'php', 'go', 'rust', 'ruby', 'sql', 'c', 'cpp', 'swift', 'r', 'powershell'];
|
|
23
|
+
|
|
24
|
+
/** Which part of the whole application a file describes (spec section 12). */
|
|
25
|
+
const CATEGORY = { dockerfile: 'infrastructure', 'github-actions': 'delivery', terraform: 'infrastructure', bicep: 'infrastructure', kubernetes: 'infrastructure', 'docker-compose': 'infrastructure' };
|
|
26
|
+
const categoryOf = (language) => CATEGORY[language] ?? 'application';
|
|
15
27
|
|
|
16
28
|
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
17
29
|
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
@@ -23,18 +35,19 @@ function startValue(expr, params = {}) {
|
|
|
23
35
|
if (!e) return null;
|
|
24
36
|
if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, '')} unless told otherwise` : 'given when it starts';
|
|
25
37
|
if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+|array\(\)|new \w*(?:List|Map|Set|Dictionary|HashMap|HashSet|ArrayList|LinkedList)(?:<[^>]*>)?\(\)|(?:mutable)?(?:List|Map|Set|listOf|mapOf|setOf|mutableListOf|mutableMapOf|mutableSetOf|emptyList|emptyMap|arrayListOf)(?:<[^>]*>)?\(\)|(?:List|Set|Map)\.of\(\)|Vec::new\(\)|vec!\[\]|HashMap::new\(\)|String::new\(\)|\[\]\w+\{\}|make\(\[\][^)]*\)|new\(\)|Hash\.new|\{\s*\})$/.test(e)) return 'empty at first';
|
|
26
|
-
if (
|
|
38
|
+
if (/^\[\s*:\s*\]$/.test(e)) return 'empty at first'; // Swift: an empty lookup table
|
|
39
|
+
if (/^(None|null|undefined|nil|NULL|nullptr|Option::None)$/.test(e)) return 'nothing at first';
|
|
27
40
|
if (/^(True|true)$/.test(e)) return 'yes at first';
|
|
28
41
|
if (/^(False|false)$/.test(e)) return 'no at first';
|
|
29
42
|
if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
|
|
30
43
|
if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
|
|
31
|
-
const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/);
|
|
44
|
+
const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/) || e.match(/^(?:[A-Z]\w*)?\.([a-z]\w*)$/); // Swift: .onShelf
|
|
32
45
|
if (en) return `${words(en[1])} at first`;
|
|
33
46
|
return 'worked out when it starts';
|
|
34
47
|
}
|
|
35
48
|
|
|
36
49
|
const KIND_WORDS = [
|
|
37
|
-
[/^(int|float|number|double|long|short|decimal|Decimal|bigint|BigDecimal|BigInteger|Integer|Int|Long|Double|Float|Short|Byte|byte|uint|usize|isize|[iuf](?:8|16|32|64|128)|int(?:8|16|32|64)|uint(?:8|16|32|64)|float(?:32|64)|Number)$/, 'a number'],
|
|
50
|
+
[/^(int|float|number|double|long|short|decimal|Decimal|bigint|BigDecimal|BigInteger|Integer|Int|Long|Double|Float|Short|Byte|byte|uint|usize|isize|[iuf](?:8|16|32|64|128)|int(?:8|16|32|64)|uint(?:8|16|32|64)|float(?:32|64)|Number|U?Int(?:8|16|32|64)|UInt|CGFloat|Float(?:16|32|64|80))$/, 'a number'],
|
|
38
51
|
[/^(str|string|String|text|&str|&'static str|char|Char|Character|rune)$/, 'words'],
|
|
39
52
|
[/^(bool|boolean|Boolean|Bool)$/, 'yes or no'],
|
|
40
53
|
[/^(date|datetime|Date|LocalDate|LocalDateTime|Instant|DateTime|DateTimeOffset|ZonedDateTime|time\.Time|NaiveDate|NaiveDateTime|DateTimeImmutable)$/, 'a date'],
|
|
@@ -52,7 +65,21 @@ function kindWords(type) {
|
|
|
52
65
|
return /^[A-Z]/.test(t) ? `a ${t}` : null;
|
|
53
66
|
}
|
|
54
67
|
|
|
55
|
-
|
|
68
|
+
/** C: a function belongs to a struct it takes first (`library_late_fee(const Library *lib, …)`) or is named after. */
|
|
69
|
+
const snakeOf = (t) => words(t.name).replace(/ /g, '_');
|
|
70
|
+
function cOwns(t, item) {
|
|
71
|
+
const first = String(item.inputs?.[0]?.type ?? '').replace(/\s+/g, '');
|
|
72
|
+
const names = [t.name, t.tag].filter(Boolean);
|
|
73
|
+
if (names.some((n) => first === n || first === `${n}*`)) return true;
|
|
74
|
+
return [snakeOf(t), t.tag].filter(Boolean).some((n) => String(item.name).toLowerCase().startsWith(`${String(n).toLowerCase()}_`));
|
|
75
|
+
}
|
|
76
|
+
function cShortName(t, name) {
|
|
77
|
+
for (const n of [snakeOf(t), t.tag].filter(Boolean)) if (String(name).toLowerCase().startsWith(`${String(n).toLowerCase()}_`) && name.length > n.length + 1) return name.slice(n.length + 1);
|
|
78
|
+
return name;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const THING_HELPERS = { words: (x) => words(x), kindWords: (x) => kindWords(x), startValue: (x, p) => startValue(x, p) };
|
|
82
|
+
const thingsFor = makeThingReaders(THING_HELPERS);
|
|
56
83
|
|
|
57
84
|
// ── Things: classes, records, and choices ───────────────────────────────────────────────────────────
|
|
58
85
|
|
|
@@ -117,7 +144,10 @@ function braceEnd(src, open) {
|
|
|
117
144
|
let depth = 0;
|
|
118
145
|
for (let i = open; i < src.length; i++) {
|
|
119
146
|
const c = src[i];
|
|
120
|
-
|
|
147
|
+
// Comments are skipped: an apostrophe in `// it's` is not the start of a string.
|
|
148
|
+
if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); if (e < 0) return -1; i = e; continue; }
|
|
149
|
+
if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); if (e < 0) return -1; i = e + 1; continue; }
|
|
150
|
+
if (c === '"' || c === "'" || c === '`') { const q = c; for (i++; i < src.length && src[i] !== q && (q === '`' || src[i] !== '\n'); i++) if (src[i] === '\\') i++; continue; }
|
|
121
151
|
if (c === '{') depth++;
|
|
122
152
|
else if (c === '}' && --depth === 0) return i;
|
|
123
153
|
}
|
|
@@ -169,6 +199,41 @@ function tsThings(src, file) {
|
|
|
169
199
|
return out;
|
|
170
200
|
}
|
|
171
201
|
|
|
202
|
+
/**
|
|
203
|
+
* JavaScript Things made by assignment rather than `class`: `Foo.prototype.bar = function` (with `function Foo()` as
|
|
204
|
+
* how a new Foo starts) and an object given two or more methods (`res.json = function`, `res.send = function` for
|
|
205
|
+
* `var res = Object.create(…)`). `exports`, `module`, `window`, and `this` are not Things.
|
|
206
|
+
*/
|
|
207
|
+
function jsAssignedThings(items, src, file, existing) {
|
|
208
|
+
const groups = new Map();
|
|
209
|
+
for (const it of items) {
|
|
210
|
+
const a = String(it.assignedTo || '').match(/^([A-Za-z_$][\w$]*)\.(?:prototype\.)?([A-Za-z_$][\w$]*)$/);
|
|
211
|
+
if (!a || /^(exports|module|window|global|globalThis|this|self|document|console|process)$/.test(a[1])) continue;
|
|
212
|
+
const g = groups.get(a[1]) ?? { proto: false, items: [] };
|
|
213
|
+
g.proto ||= /\.prototype\./.test(it.assignedTo);
|
|
214
|
+
g.items.push(it);
|
|
215
|
+
groups.set(a[1], g);
|
|
216
|
+
}
|
|
217
|
+
const out = [];
|
|
218
|
+
for (const [name, g] of groups) {
|
|
219
|
+
if (existing.some((t) => t.name === name)) continue;
|
|
220
|
+
const ctor = g.proto && items.find((it) => it.name === name && !it.assignedTo && !it.callback && (it.kind === 'function' || it.kind === 'decision'));
|
|
221
|
+
const declared = new RegExp(`(?:^|[^\\w$.])(?:var|let|const)\\s+${name.replace(/\$/g, '\\$')}\\s*=`).test(src);
|
|
222
|
+
if (!(g.proto ? true : g.items.length >= 2 && declared)) continue;
|
|
223
|
+
const lines = g.items.map((it) => it.line);
|
|
224
|
+
const from = ctor?.line ?? Math.min(...lines);
|
|
225
|
+
const thing = { kind: 'thing', name, file, lines: [from, Math.max(from, ...g.items.map((it) => it.anchor?.bodyLines?.[1] ?? it.line))], knows: [], choices: [], assigned: g.items.map((it) => `${it.name}:${it.line}`), spans: [...g.items, ...(ctor ? [ctor] : [])].map((it) => [it.line, it.anchor?.bodyLines?.[1] ?? it.line]), ...(ctor ? { ctor: `${ctor.name}:${ctor.line}` } : {}) };
|
|
226
|
+
// What a new one knows: `this.x = …` in the constructor function.
|
|
227
|
+
if (ctor?.anchor?.bodyLines) {
|
|
228
|
+
const body = src.split('\n').slice(ctor.anchor.bodyLines[0] - 1, ctor.anchor.bodyLines[1]).join('\n');
|
|
229
|
+
const params = Object.fromEntries((ctor.inputs || []).map((p) => [p.name, null]));
|
|
230
|
+
for (const a of body.matchAll(/\bthis\.([A-Za-z_$][\w$]*)\s*=(?!=)\s*([^;\n]+)/g)) if (!thing.knows.some((k) => k.name === a[1])) thing.knows.push({ name: a[1], label: words(a[1]), kind: null, start: startValue(a[2].trim(), params), line: null });
|
|
231
|
+
}
|
|
232
|
+
out.push(thing);
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
|
|
172
237
|
// ── Flow: steps as a graph a person can follow ─────────────────────────────────────────────────────────
|
|
173
238
|
|
|
174
239
|
/**
|
|
@@ -177,6 +242,7 @@ function tsThings(src, file) {
|
|
|
177
242
|
*/
|
|
178
243
|
export function stepDoes(step) {
|
|
179
244
|
const s = step.says || '', c = step.callee || '';
|
|
245
|
+
if (step.library && step.does) return step.does === 'calculate' ? 'calculate' : step.does === 'check' ? 'check' : step.does;
|
|
180
246
|
if (step.restates || step.kind === 'other') return 'code';
|
|
181
247
|
if (step.kind === 'fail') return 'stop';
|
|
182
248
|
if (step.redirect) return 'redirect';
|
|
@@ -184,16 +250,22 @@ export function stepDoes(step) {
|
|
|
184
250
|
if (step.kind === 'return') return 'answer';
|
|
185
251
|
if (step.kind === 'check') return 'check';
|
|
186
252
|
if (step.kind === 'branch') return 'decide';
|
|
187
|
-
if (/^Writes to the database|^(Records|Adds to|Removes)/.test(s)) return 'save';
|
|
188
|
-
if (/^(Sends an email|Announces an event|Writes a log)/.test(s)) return 'send';
|
|
189
|
-
if (/^(Calls another service|Calls Stripe)/.test(s)) return 'ask';
|
|
253
|
+
if (/^Writes to the database|^(Records|Stores|Adds to|Removes)/.test(s)) return 'save';
|
|
254
|
+
if (/^(Sends an email|Announces an event|Writes a log|Writes a message|Writes an error message|Shows a message|Warns:)/.test(s)) return 'send';
|
|
255
|
+
if (/^(Calls another service|Calls Stripe|Sends an? (?:GET|POST|PUT|PATCH|DELETE|HEAD) request)/.test(s)) return 'ask';
|
|
190
256
|
if (/\b(filter|where|select|query|find|get|fetch|load|read|search|lookup|scalars|all)\b/i.test(c) || /the items in .* where|the first item in|the .* entry in|the .* with /.test(s)) return /\b(filter|where)\b/i.test(c) || / where /.test(s) ? 'keep-only' : 'find';
|
|
191
257
|
if (step.kind === 'set') return 'calculate';
|
|
192
258
|
return 'do';
|
|
193
259
|
}
|
|
194
260
|
|
|
195
|
-
/**
|
|
196
|
-
|
|
261
|
+
/**
|
|
262
|
+
* Quoted text ("…"), code (`…`), and placeholders («…») kept exactly as they are, while `fn` rewrites the words
|
|
263
|
+
* between them.
|
|
264
|
+
*/
|
|
265
|
+
const outsideQuotes = (text, fn) => String(text).split(/("(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»)/).map((part, i) => (i % 2 ? part : fn(part))).join('');
|
|
266
|
+
/** "the book's status" for book.status; plain words for everything else. Quoted text is never rewritten. */
|
|
267
|
+
const possessive = (text) => outsideQuotes(text, possessiveWords);
|
|
268
|
+
const possessiveWords = (text) => String(text)
|
|
197
269
|
.replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => (/^(self|this)$/.test(a) ? `the ${words(b)}` : `the ${words(a)}'s ${words(b)}`))
|
|
198
270
|
.replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
|
|
199
271
|
/** An answer as words: NoFee -> "No fee", true -> "Yes". */
|
|
@@ -205,23 +277,53 @@ const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No
|
|
|
205
277
|
* asked by the rule's own name: "Can borrow?".
|
|
206
278
|
*/
|
|
207
279
|
export function askAsQuestion(step, ruleLabel) {
|
|
280
|
+
// " is " inside quoted text or code is not the question's verb: those parts are held aside while the question is
|
|
281
|
+
// shaped, then put back exactly as written.
|
|
282
|
+
// "Running x works?": a command's success is the question; words inside it ("nvm is merged …") are not its verb.
|
|
283
|
+
const run = String(step.says).match(/^If (not: )?([A-Z]?[a-z]+ing\b[^]* (?:works|fails))$/);
|
|
284
|
+
if (run && !ruleLabel) return { text: `${cap(run[2])}?`, flip: !!run[1] };
|
|
285
|
+
const held = [];
|
|
286
|
+
const says = String(step.says).replace(/"(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»/g, (m) => (isCodeWords(String(step.says).replace(/^If (?:not: )?/, '')) ? m : `\u0001${held.push(m) - 1}\u0002`));
|
|
287
|
+
const r = askWords({ ...step, says }, ruleLabel);
|
|
288
|
+
return { ...r, text: r.text.replace(/\u0001(\d+)\u0002/g, (m, k) => held[Number(k)]) };
|
|
289
|
+
}
|
|
290
|
+
function askWords(step, ruleLabel) {
|
|
208
291
|
let c = String(step.says).replace(/^If /, '').replace(/ \(\d+ steps? inside\)$/, '').trim();
|
|
209
292
|
let flip = false;
|
|
210
293
|
if (/^not: /.test(c)) { c = c.slice(5); flip = true; }
|
|
294
|
+
// A step that is already worded as a question (infrastructure readers ask their own) is asked as it is.
|
|
295
|
+
if (/\?$/.test(c) && !ruleLabel) return { text: c, flip };
|
|
296
|
+
// The faithfulness gate gave the code back: ask the code itself, Yes when it is true.
|
|
297
|
+
if (isCodeWords(c)) return { text: `${c}?`, flip, code: true };
|
|
211
298
|
if (ruleLabel) {
|
|
212
299
|
const negated = /^not\b|^!/.test(String(step.code || '').replace(/^\s*if\s*\(?\s*/, '')) || /\bnot\s+(self|this)\./.test(step.code || '') || /!\s*(this|self)\./.test(step.code || '');
|
|
213
300
|
// The negation is read from the code alone; the step's wording may already say "not" for the same reason.
|
|
214
301
|
return { text: `${ruleLabel.replace(/\?$/, '')}?`, flip: negated };
|
|
215
302
|
}
|
|
216
303
|
let m;
|
|
304
|
+
// A compound condition (a and b, a or not b) is asked as written: turning one part positive would flip the
|
|
305
|
+
// whole question and put the Stop on the wrong side.
|
|
306
|
+
if (compoundWords(c)) return { text: `${cap(possessive(c))}?`, flip, holds: { yes: possessive(c), no: `it is not true that ${possessive(c)}` } };
|
|
307
|
+
if ((m = c.match(/^not \((.+)\)$/)) && closeOf(c, 4) === c.length - 1) return { text: `${cap(possessive(m[1]))}?`, flip: !flip };
|
|
217
308
|
if ((m = c.match(/^not (.+)$/))) { c = m[1]; flip = !flip; }
|
|
218
|
-
if ((
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
309
|
+
if (compoundWords(c)) return { text: `Not ${possessive(c)}?`, flip: !flip };
|
|
310
|
+
// `holds`: what is true on each side, as a statement ("the x header is not the KEY setting"), for sentences such
|
|
311
|
+
// as a review's "Now stops with 403 when …". Only where the question splits cleanly into a subject and the rest.
|
|
312
|
+
const is = (a, b) => ({ yes: `${possessive(a)} is ${possessive(b)}`, no: `${possessive(a)} is not ${possessive(b)}` });
|
|
313
|
+
const has = (a, b) => ({ yes: `${possessive(a)} has ${b}`, no: `${possessive(a)} has no ${b}` });
|
|
314
|
+
if ((m = c.match(/^(.+?) is not (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip: !flip, holds: is(m[1], m[2]) };
|
|
315
|
+
if ((m = c.match(/^(.+?) has no (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip: !flip, holds: has(m[1], m[2]) };
|
|
316
|
+
if ((m = c.match(/^(.+?) is (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip, holds: is(m[1], m[2]) };
|
|
317
|
+
if ((m = c.match(/^(.+?) has (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip, holds: has(m[1], m[2]) };
|
|
222
318
|
return { text: `${cap(possessive(c))}?`, flip };
|
|
223
319
|
}
|
|
224
320
|
|
|
321
|
+
/** True when words join two or more conditions with and / or outside brackets. */
|
|
322
|
+
function compoundWords(c) {
|
|
323
|
+
const parts = splitLogic(String(c).replace(/`[^`]*`/g, 'Q').replace(/"[^"]*"/g, 'Q').replace(/'/g, ''));
|
|
324
|
+
return !parts || parts.terms.length > 1;
|
|
325
|
+
}
|
|
326
|
+
|
|
225
327
|
/** A rule's own picture: each rule asked in order, the first Yes gives its answer, otherwise the fallback. */
|
|
226
328
|
export function ruleFlow(item, start) {
|
|
227
329
|
const nodes = [], edges = [];
|
|
@@ -248,20 +350,52 @@ export function ruleFlow(item, start) {
|
|
|
248
350
|
return { nodes, edges, blocks: chain(0) };
|
|
249
351
|
}
|
|
250
352
|
|
|
353
|
+
// A node's `detail` (what the short words leave out) is worked out the first time it is read — by Details, the full
|
|
354
|
+
// Thunder Text, or a serializer — not for every node of every flow. It is an ordinary enumerable field once read.
|
|
355
|
+
const DETAIL_OF = Symbol('detail of');
|
|
356
|
+
function lazyDetail(nd, step) {
|
|
357
|
+
Object.defineProperty(nd, 'detail', {
|
|
358
|
+
enumerable: true, configurable: true,
|
|
359
|
+
get() {
|
|
360
|
+
const parts = detailParts(step);
|
|
361
|
+
const value = parts.length ? parts.map((x) => `${x.label}: ${x.text}`).join('; ') : undefined;
|
|
362
|
+
Object.defineProperty(nd, 'detail', { value, enumerable: value !== undefined, writable: true, configurable: true });
|
|
363
|
+
return value;
|
|
364
|
+
},
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
251
368
|
/** Turn steps into nodes and edges. Deterministic; nothing is added that the steps do not say. */
|
|
252
369
|
export function flowOf(steps, { start = 'Start', memberIndex = new Map(), memberLabel = new Map() } = {}) {
|
|
253
370
|
const nodes = [], edges = [];
|
|
254
371
|
let n = 0;
|
|
255
|
-
const node = (kind, text, extra = {}) => {
|
|
256
|
-
|
|
372
|
+
const node = (kind, text, extra = {}) => {
|
|
373
|
+
const id = `n${n++}`;
|
|
374
|
+
const { [DETAIL_OF]: of, ...rest } = extra;
|
|
375
|
+
const nd = { id, kind, text, ...rest };
|
|
376
|
+
if (of) lazyDetail(nd, of);
|
|
377
|
+
nodes.push(nd);
|
|
378
|
+
return id;
|
|
379
|
+
};
|
|
380
|
+
const connect = (open, to) => { for (const o of open) edges.push({ from: o.id, to, ...(o.label ? { label: o.label } : {}), ...(o.text ? { text: o.text } : {}) }); };
|
|
257
381
|
// The first call in the step to another member of this file: self.can_borrow(...), delivery_fee(...), this.lateFee(...).
|
|
382
|
+
// A method called on some other object (`console.error(…)`, `other.fillBuffer(…)`) is not this file's member.
|
|
258
383
|
const usesOf = (st) => {
|
|
259
|
-
for (const c of String(st.code || '').matchAll(/(?:\b(?:self|this)
|
|
384
|
+
for (const c of String(st.code || '').matchAll(/(?:\b(?:self|this)\.|(?<![\w$.]))([A-Za-z_]\w*)\s*\(/g)) {
|
|
260
385
|
const id = memberIndex.get(c[1].toLowerCase());
|
|
261
386
|
if (id) return id;
|
|
262
387
|
}
|
|
388
|
+
// Shell and PowerShell call a function without parentheses: the step names it as its callee.
|
|
389
|
+
if (st.callee && /^[\w-]+$/.test(st.callee)) return memberIndex.get(String(st.callee).toLowerCase()) ?? null;
|
|
263
390
|
return null;
|
|
264
391
|
};
|
|
392
|
+
// A question is asked by a rule's own name only when the condition is that call and nothing else
|
|
393
|
+
// (`if (!canBorrow(x))`), never when the call is one part of a bigger condition.
|
|
394
|
+
const askedByRule = (st) => {
|
|
395
|
+
const cond = String(st.cond ?? '').trim().replace(/^\((.*)\)$/, '$1');
|
|
396
|
+
const m = cond.match(/^(?:!\s*|not\s+)?(?:(?:self|this)\.)?[A-Za-z_]\w*\s*\(/);
|
|
397
|
+
return !!m && closeOf(cond, m[0].length - 1) === cond.length - 1;
|
|
398
|
+
};
|
|
265
399
|
// walk returns { open, blocks }: open = edges still waiting for the next node; blocks = the same nodes as a tree
|
|
266
400
|
// (each question with its yes and no sides, loops with their body, try with its handlers and always), which is
|
|
267
401
|
// what the picture and Thunder Text are drawn from. The edges are the same flow as a graph, for other tools.
|
|
@@ -269,17 +403,52 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
269
403
|
const blocks = [];
|
|
270
404
|
for (const st of list) {
|
|
271
405
|
const does = stepDoes(st);
|
|
272
|
-
|
|
406
|
+
// Every node keeps its step's meaning tree (`expr`) and, when the short words leave something out, `detail`:
|
|
407
|
+
// the rest, one level down ("with: order, { validate: false }"). Details and the full Thunder Text show it.
|
|
408
|
+
const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}), ...(st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {}) };
|
|
409
|
+
// A choice among several cases (switch, when, match, select): one question with one side per case.
|
|
410
|
+
const arms = st.kind === 'branch' && st.children?.length && st.children.every((c) => c.kind === 'check' && c.caseLabel) ? st.children : null;
|
|
411
|
+
if (arms) {
|
|
412
|
+
const d = node('decision', st.says.replace(/\?$/, ''), { ...base, cases: true });
|
|
413
|
+
connect(open, d);
|
|
414
|
+
const cases = [];
|
|
415
|
+
let after = [];
|
|
416
|
+
for (const arm of arms) {
|
|
417
|
+
const label = arm.says;
|
|
418
|
+
const w = walk(arm.children || [], [{ id: d, label: 'case', text: label }], lane + 1);
|
|
419
|
+
cases.push({ label, line: arm.line, blocks: w.blocks });
|
|
420
|
+
after = [...after, ...w.open];
|
|
421
|
+
}
|
|
422
|
+
// An else after the cases (Ruby `case … else`) is the last case.
|
|
423
|
+
if (st.otherwise?.length) {
|
|
424
|
+
const w = walk(st.otherwise, [{ id: d, label: 'case', text: 'Otherwise' }], lane + 1);
|
|
425
|
+
cases.push({ label: 'Otherwise', line: st.otherwiseLine ?? st.otherwise[0].line, blocks: w.blocks });
|
|
426
|
+
after = [...after, ...w.open];
|
|
427
|
+
}
|
|
428
|
+
// With no "Otherwise", a value that matches no case carries straight on.
|
|
429
|
+
if (!st.otherwise?.length && !arms.some((a) => /^(Otherwise|If none is ready yet|Default)\b/i.test(a.says))) after.push({ id: d, label: 'case', text: 'None of these' });
|
|
430
|
+
blocks.push({ id: d, cases });
|
|
431
|
+
open = after;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
273
434
|
if (st.kind === 'branch') {
|
|
274
|
-
const { text, flip } = askAsQuestion(st, base.uses && memberLabel.get(base.uses));
|
|
435
|
+
const { text, flip, code, holds } = askAsQuestion(st, base.uses && askedByRule(st) && memberLabel.get(base.uses));
|
|
275
436
|
const [into, past] = flip ? ['no', 'yes'] : ['yes', 'no'];
|
|
276
|
-
|
|
437
|
+
// whenTrue: the side the code takes when its condition holds (No when the question is asked the positive way
|
|
438
|
+
// round of a negated condition). Proof by running checks each side against what a run actually did.
|
|
439
|
+
const d = node('decision', text, { ...base, whenTrue: into, ...(code || st.unread ? { code: true } : {}), ...(holds && !code && !st.unread ? { holds } : {}) });
|
|
277
440
|
connect(open, d);
|
|
278
441
|
const inside = walk(st.children || [], [{ id: d, label: into }], lane + 1);
|
|
279
442
|
// The other side of the question: its else (or else-if chain) when the code has one.
|
|
280
443
|
const other = st.otherwise?.length ? walk(st.otherwise, [{ id: d, label: past }], lane + 1) : { open: [{ id: d, label: past }], blocks: [] };
|
|
281
444
|
blocks.push({ id: d, [into]: inside.blocks, [past]: other.blocks });
|
|
282
445
|
open = [...other.open, ...inside.open];
|
|
446
|
+
} else if (st.kind === 'loop' && !st.children?.length) {
|
|
447
|
+
// A loop whose body was not read is shown as its code, not as an empty "For each".
|
|
448
|
+
const k = node('code', st.code ?? st.says, { ...base, does: 'code' });
|
|
449
|
+
connect(open, k);
|
|
450
|
+
open = [{ id: k }];
|
|
451
|
+
blocks.push({ id: k });
|
|
283
452
|
} else if (st.kind === 'loop') {
|
|
284
453
|
const l = node('loop', st.says, base);
|
|
285
454
|
connect(open, l);
|
|
@@ -287,11 +456,22 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
287
456
|
for (const b of body.open) edges.push({ from: b.id, to: l, label: 'next' });
|
|
288
457
|
blocks.push({ id: l, each: body.blocks });
|
|
289
458
|
open = [{ id: l, label: 'done' }];
|
|
459
|
+
if (st.otherwise?.length) {
|
|
460
|
+
// Python `for … else:` / `while … else:` runs only when the loop was not left early.
|
|
461
|
+
const e = node('step', 'If it did not leave the loop early', { line: st.otherwiseLine ?? st.otherwise[0].line, lane, does: 'do' });
|
|
462
|
+
connect(open, e);
|
|
463
|
+
const w = walk(st.otherwise, [{ id: e }], lane + 1);
|
|
464
|
+
blocks.push({ id: e, body: w.blocks });
|
|
465
|
+
open = w.open;
|
|
466
|
+
}
|
|
290
467
|
} else if (st.kind === 'fail') {
|
|
291
468
|
const sn = node('stop', st.says.replace(/^Fails with /, 'Stop: '), base);
|
|
292
469
|
connect(open, sn);
|
|
293
470
|
blocks.push({ id: sn });
|
|
294
471
|
open = [];
|
|
472
|
+
} else if (st.kind === 'return' && !open.length && /^Stops here$/.test(st.says)) {
|
|
473
|
+
// `res.status(403).json(...); return` — the bare return only ends the path the Stop already ended.
|
|
474
|
+
continue;
|
|
295
475
|
} else if (st.kind === 'return') {
|
|
296
476
|
const e = node('end', st.restates ? st.code : st.says.replace(/^Returns /, 'Gives back '), { ...base, ...(st.restates ? { code: true } : {}) });
|
|
297
477
|
connect(open, e);
|
|
@@ -303,9 +483,18 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
303
483
|
connect(open, t);
|
|
304
484
|
const body = walk(st.children || [], [{ id: t }], lane);
|
|
305
485
|
let after = body.open;
|
|
486
|
+
if (st.otherwise?.length) {
|
|
487
|
+
// Python `try … else:` — steps that run only when nothing went wrong in the tried steps (their own errors
|
|
488
|
+
// are not handled here). Drawn at the end of the tried steps, on the path where nothing failed.
|
|
489
|
+
const e = node('step', 'If nothing went wrong', { line: st.otherwiseLine ?? st.otherwise[0].line, lane, does: 'do' });
|
|
490
|
+
connect(after, e);
|
|
491
|
+
const w = walk(st.otherwise, [{ id: e }], lane + 1);
|
|
492
|
+
body.blocks.push({ id: e, body: w.blocks });
|
|
493
|
+
after = w.open;
|
|
494
|
+
}
|
|
306
495
|
const handlers = [];
|
|
307
496
|
for (const h of st.handlers || []) {
|
|
308
|
-
const hn = node('decision', `${h.says}?`, { line: h.line, lane: lane + 1, does: 'decide', handler: true });
|
|
497
|
+
const hn = node('decision', `${h.says}?`, { line: h.line, lane: lane + 1, does: 'decide', handler: true, ...(h.expr ? { expr: h.expr } : {}) });
|
|
309
498
|
edges.push({ from: t, to: hn, label: 'error' });
|
|
310
499
|
const hw = walk(h.steps, [{ id: hn, label: 'yes' }], lane + 1);
|
|
311
500
|
handlers.push({ id: hn, blocks: hw.blocks });
|
|
@@ -324,8 +513,13 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
324
513
|
} else {
|
|
325
514
|
const k = node(does === 'code' ? 'code' : 'step', does === 'code' ? st.code ?? st.says : st.says, base);
|
|
326
515
|
connect(open, k);
|
|
327
|
-
open = [{ id: k }];
|
|
328
|
-
if (st.children?.length) {
|
|
516
|
+
open = st.jump ? [] : [{ id: k }];
|
|
517
|
+
if (st.children?.length && st.nested) {
|
|
518
|
+
// An inner function (a hook, a callback, go/defer, a closure) runs on its own: its steps are its own
|
|
519
|
+
// sub-flow, and a return or stop inside it ends only that function. The outer flow carries on from here.
|
|
520
|
+
const inner = walk(st.children, [{ id: k, label: 'nested' }], lane + 1);
|
|
521
|
+
blocks.push({ id: k, body: inner.blocks, nested: true });
|
|
522
|
+
} else if (st.children?.length) {
|
|
329
523
|
const inner = walk(st.children, open, lane + 1);
|
|
330
524
|
blocks.push({ id: k, body: inner.blocks });
|
|
331
525
|
open = inner.open;
|
|
@@ -355,62 +549,173 @@ const idOf = (...parts) => parts.join('#').replace(/\s+/g, '');
|
|
|
355
549
|
* session), plus the facts a handler unpacks from the request: `const { slug, name } = request.body`,
|
|
356
550
|
* `const { id } = req.params`, `{ email } = await request.json()`.
|
|
357
551
|
*/
|
|
552
|
+
function inputKindsOf(item) {
|
|
553
|
+
const kinds = {};
|
|
554
|
+
for (const p of item.inputs || []) {
|
|
555
|
+
if (/^(self|this|cls)$/.test(p.name) || p.plumbing || !p.type) continue;
|
|
556
|
+
const k = kindWords(p.type) ?? (/^[A-Z]\w*$/.test(String(p.type).trim()) ? `a ${String(p.type).trim()}` : null);
|
|
557
|
+
if (k) kinds[words(p.name)] = k;
|
|
558
|
+
}
|
|
559
|
+
return Object.keys(kinds).length ? kinds : null;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** The names a destructuring pattern takes: `{ a, b: { c, d }, ...rest }: T` -> a, c, d, rest. */
|
|
563
|
+
function destructuredNames(text) {
|
|
564
|
+
const open = text.indexOf('{');
|
|
565
|
+
const close = closeOf(text, open);
|
|
566
|
+
if (close < 0) return [];
|
|
567
|
+
const inner = text.slice(open + 1, close);
|
|
568
|
+
const out = [];
|
|
569
|
+
let d = 0, from = 0;
|
|
570
|
+
const part = (x) => {
|
|
571
|
+
const t = x.trim();
|
|
572
|
+
if (!t) return;
|
|
573
|
+
// `...props`: everything else it is given, under one name.
|
|
574
|
+
if (/^\.\.\.[A-Za-z_$][\w$]*$/.test(t)) { out.push(t.slice(3)); return; }
|
|
575
|
+
const m = t.match(/^([A-Za-z_$][\w$]*)\s*:\s*(\{[\s\S]*\})\s*(?:=.*)?$/);
|
|
576
|
+
if (m) { out.push(...destructuredNames(m[2])); return; }
|
|
577
|
+
const n = t.split(/[:=]/)[0].trim();
|
|
578
|
+
if (/^[A-Za-z_$][\w$]*$/.test(n)) out.push(n);
|
|
579
|
+
};
|
|
580
|
+
for (let i = 0; i < inner.length; i++) {
|
|
581
|
+
const c = inner[i];
|
|
582
|
+
if ('{[('.includes(c)) d++; else if ('}])'.includes(c)) d--;
|
|
583
|
+
else if (c === ',' && d === 0) { part(inner.slice(from, i)); from = i + 1; }
|
|
584
|
+
}
|
|
585
|
+
part(inner.slice(from));
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
|
|
358
589
|
function youGiveOf(item) {
|
|
359
|
-
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing)
|
|
590
|
+
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing)
|
|
591
|
+
// Destructured parameters (React props `{ userId, name }`) give each name.
|
|
592
|
+
// Destructured parameters (React props `{ userId, name }`, `{ route: { href }, onClick }: Props`) give each name.
|
|
593
|
+
.flatMap((p) => (/^\{/.test(String(p.name).trim()) ? destructuredNames(String(p.name).trim()) : [p.name]))
|
|
594
|
+
.map((n) => words(n)).filter(Boolean); // (`_`, a value the code ignores, is not something you give it)
|
|
360
595
|
const codes = [];
|
|
361
596
|
const walk = (steps) => { for (const s of steps || []) { if (s.code) codes.push(s.code); walk(s.children); walk(s.otherwise); } };
|
|
362
597
|
walk(item.steps);
|
|
363
598
|
for (const c of codes) {
|
|
364
|
-
|
|
599
|
+
// Values read straight from the request: a header, a value in the address, or a field it was sent.
|
|
600
|
+
for (const r of c.matchAll(/\b(?:req|request|ctx\.request|c\.req)\s*\.\s*headers\s*(?:\[\s*['"`]([^'"`]+)['"`]\s*\]|\.\s*get\(\s*['"`]([^'"`]+)['"`]\s*\))/g)) { const h = `the ${r[1] || r[2]} header`; if (!given.includes(h)) given.push(h); }
|
|
601
|
+
// (Only in a web handler, where the request is plumbing; `request.body.locked` on a fetch Request is not a field.)
|
|
602
|
+
if ((item.inputs || []).some((p) => !p.plumbing && /^(?:req|request)$/.test(p.name))) continue;
|
|
603
|
+
for (const r of c.matchAll(/\b(?:req|request|ctx\.request|ctx|c\.req)\s*\.\s*(query|params|body)\s*(?:\.\s*([A-Za-z_][\w]*)|\[\s*['"`]([^'"`]+)['"`]\s*\])/g)) { const n = `${words(r[2] || r[3])} ${r[1] === 'body' ? '(sent in the request)' : '(in the address)'}`; if (!given.includes(n)) given.push(n); }
|
|
604
|
+
const m = c.match(/^(?:const|let|var)\s*\{([^}]+)\}\s*=\s*\(?\s*(?:await\s+)?(?:req|request|ctx\.request|c\.req|event)\s*\.\s*(body|query|params|json\(\))/);
|
|
605
|
+
const where = m ? (/^(query|params)$/.test(m[2]) ? ' (in the address)' : ' (sent in the request)') : '';
|
|
365
606
|
if (!m) continue;
|
|
366
607
|
for (const part of m[1].split(',')) {
|
|
367
608
|
const name = part.split(/[:=]/)[0].replace(/^\.\.\./, '').trim();
|
|
368
|
-
if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words(name))) given.push(words(name));
|
|
609
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words(name) + where)) given.push(words(name) + where);
|
|
369
610
|
}
|
|
370
611
|
}
|
|
371
612
|
return given;
|
|
372
613
|
}
|
|
373
614
|
|
|
615
|
+
const dirOf = (p) => (String(p).includes('/') ? String(p).slice(0, String(p).lastIndexOf('/')) : '');
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Links whose other end is in another file, drawn once every file is read. Only exact matches: a Terraform address in
|
|
619
|
+
* the same folder; a Dockerfile's image by its path; a Kubernetes address (in the same folder first, else the one
|
|
620
|
+
* resource in the repository with it); a Kubernetes selector against the workloads whose pods carry those labels.
|
|
621
|
+
* When more than one folder could be meant, nothing is drawn.
|
|
622
|
+
*/
|
|
623
|
+
function resolveAcrossFiles(pending, things, links, linkKeys) {
|
|
624
|
+
const add = (p, to) => {
|
|
625
|
+
const key = `${p.from}>${to}>${p.l.kind}>${p.l.line}`;
|
|
626
|
+
if (to && to !== p.from && !linkKeys.has(key)) { linkKeys.add(key); links.push({ from: p.from, to, kind: p.l.kind, file: p.l.file, line: p.l.line }); }
|
|
627
|
+
};
|
|
628
|
+
const resources = things.filter((t) => t.kind === 'resource' && t.address);
|
|
629
|
+
const byDirAddr = new Map(resources.map((t) => [`${dirOf(t.file)}|${t.address}`, t.id]));
|
|
630
|
+
const byAddr = new Map();
|
|
631
|
+
for (const t of resources) byAddr.set(t.address, [...(byAddr.get(t.address) ?? []), t]);
|
|
632
|
+
const oneDir = (hits, dir) => {
|
|
633
|
+
const here = hits.filter((t) => dirOf(t.file) === dir);
|
|
634
|
+
if (here.length) return here;
|
|
635
|
+
return new Set(hits.map((t) => dirOf(t.file))).size === 1 ? hits : [];
|
|
636
|
+
};
|
|
637
|
+
for (const p of pending) {
|
|
638
|
+
const to = p.l.to;
|
|
639
|
+
if (p.language === 'terraform') { add(p, byDirAddr.get(`${p.dir}|${to}`)); continue; }
|
|
640
|
+
if (typeof to === 'string' && to.startsWith('image:')) { const hit = byAddr.get(to); if (hit?.length === 1) add(p, hit[0].id); continue; }
|
|
641
|
+
if (p.l.selector) {
|
|
642
|
+
const hits = resources.filter((t) => t.podLabels && (t.podLabels.ns ?? null) === (p.l.namespace ?? null) && Object.entries(p.l.selector).every(([k, v]) => t.podLabels.labels[k] === v));
|
|
643
|
+
for (const t of oneDir(hits, p.dir)) add(p, t.id);
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
const hits = oneDir(byAddr.get(to) ?? [], p.dir);
|
|
647
|
+
if (hits.length === 1) add(p, hits[0].id);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
374
651
|
export function thunderModel(files, { name = 'app' } = {}) {
|
|
375
|
-
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
652
|
+
const things = [], members = [], links = [], unknowns = [], fileInfo = [], permissions = [], settings = [], facts = [];
|
|
653
|
+
const linkKeys = new Set(), pending = [];
|
|
376
654
|
for (const f of files) {
|
|
377
|
-
const language = readableLanguage(f.path);
|
|
655
|
+
const language = readableLanguage(f.path, f.source);
|
|
378
656
|
if (!language || !f.source) continue;
|
|
379
657
|
let reading;
|
|
380
|
-
try { reading = readingOf(f, language); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); continue; }
|
|
658
|
+
try { reading = readingOf(f, language); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); fileInfo.push({ path: f.path, language, category: categoryOf(language), skipped: `Could not read this file: ${e.message}` }); continue; }
|
|
659
|
+
const infra = INFRA_LANGUAGES.includes(language) ? reading.infra : null;
|
|
381
660
|
let fileThings = [];
|
|
382
|
-
try { fileThings = language === 'python' ? pythonThings(f.source, f.path) : language === 'typescript' || language === 'javascript' ? tsThings(f.source, f.path) : language === 'sql' ? sqlThings(f.source, f.path) : thingsFor(language, f.source, f.path); }
|
|
661
|
+
try { fileThings = infra ? infra.things.map((t) => ({ ...t, knows: t.knows.map((k) => ({ ...k })) })) : language === 'python' ? pythonThings(f.source, f.path) : language === 'typescript' || language === 'javascript' ? tsThings(f.source, f.path) : language === 'sql' ? sqlThings(f.source, f.path) : language === 'r' ? rThings(f.source, f.path, THING_HELPERS) : language === 'powershell' ? psThings(f.source, f.path, THING_HELPERS) : thingsFor(language, f.source, f.path); }
|
|
383
662
|
catch (e) { unknowns.push({ file: f.path, line: 1, why: `Classes in this file could not be drawn as Things: ${e.message}` }); } // one file never stops the whole app
|
|
384
|
-
if (
|
|
663
|
+
if (language === 'typescript' || language === 'javascript') fileThings.push(...jsAssignedThings(reading.items, f.source, f.path, fileThings));
|
|
664
|
+
// Shell has no classes at all, so a word like "class Foo" in a shell file is text, not a gap.
|
|
665
|
+
if (!infra && !THING_LANGUAGES.includes(language) && language !== 'shell' && /\b(class|struct|record|enum|interface|data class)\s+[A-Z]/.test(f.source)) {
|
|
385
666
|
unknowns.push({ file: f.path, line: 1, why: `Classes, records, and choices in ${language} are not drawn as Things yet; their functions are read.` });
|
|
386
667
|
}
|
|
387
|
-
for (const t of fileThings) { t.id = idOf(f.path, t.name); t.label = cap(words(t.name)); t.can = []; things.push(t); }
|
|
668
|
+
for (const t of fileThings) { t.id = idOf(f.path, t.name); t.label = infra && t.label ? t.label : cap(words(t.name)); t.can = []; things.push(t); }
|
|
388
669
|
const moduleDoc = language === 'python' ? (f.source.match(/^\s*(?:#.*\n|\s*\n)*[rRuU]?("""|''')([\s\S]*?)\1/)?.[2] ?? '').trim().split(/\n\s*\n/)[0].replace(/\s+/g, ' ') : '';
|
|
389
|
-
|
|
670
|
+
const purpose = moduleDoc || reading.purpose || '';
|
|
671
|
+
fileInfo.push({ path: f.path, language, category: categoryOf(language), ...(purpose ? { purpose } : {}) });
|
|
672
|
+
if (infra) {
|
|
673
|
+
permissions.push(...infra.permissions.map((x) => ({ ...x })));
|
|
674
|
+
settings.push(...infra.settings.map((x) => ({ ...x })));
|
|
675
|
+
facts.push(...infra.facts.map((x) => ({ ...x })));
|
|
676
|
+
unknowns.push(...(infra.unknowns ?? []).map((x) => ({ ...x })));
|
|
677
|
+
}
|
|
390
678
|
|
|
391
679
|
const fns = reading.items.filter((i) => i.kind === 'function' || i.kind === 'decision');
|
|
392
|
-
const declaredThing = (item) => fileThings.some((t) => t.name === item.name && t.lines[0] === item.line);
|
|
680
|
+
const declaredThing = (item) => fileThings.some((t) => !t.assigned && t.name === item.name && t.lines[0] === item.line);
|
|
393
681
|
const fileMembers = fns.filter((item) => !declaredThing(item)).map((item) => {
|
|
394
|
-
|
|
682
|
+
// The Thing a member belongs to: the type it is written in (or a Go/Rust/C++/Swift block of its methods), the
|
|
683
|
+
// type it names (C++ Library::lateFee, Swift extension Library), or in C, the struct it takes or is named after.
|
|
684
|
+
const inside = infra ? undefined : fileThings.filter((t) => !t.assigned && ((item.line > t.lines[0] && item.line <= t.lines[1]) || (t.memberRanges || []).some(([a, b]) => item.line >= a && item.line <= b))).sort((a, b) => b.lines[0] - a.lines[0])[0]
|
|
685
|
+
?? (item.qualifier ? fileThings.find((t) => !t.assigned && t.name === item.qualifier && t.kind !== 'choices') : undefined)
|
|
686
|
+
?? (language === 'c' ? fileThings.find((t) => !t.assigned && t.kind !== 'choices' && cOwns(t, item)) : undefined);
|
|
687
|
+
// A JavaScript method given to a Thing by assignment (`Foo.prototype.bar = function`) belongs to it; its id stays
|
|
688
|
+
// the one it had before it had an owner, so links and saved places still find it.
|
|
689
|
+
const key = `${item.name}:${item.line}`;
|
|
690
|
+
// (A callback or function written inside such a method belongs to the same Thing, as it would inside a class.)
|
|
691
|
+
const owner = infra ? undefined : inside ?? fileThings.find((t) => t.assigned && (t.assigned.includes(key) || t.ctor === key || (!item.assignedTo && t.spans.some(([a, b]) => item.line > a && item.line <= b))));
|
|
692
|
+
// C names a struct's functions after it (library_late_fee): the Thing's own name is left out of the label.
|
|
693
|
+
const own = language === 'c' && owner ? cShortName(owner, item.name) : item.name;
|
|
694
|
+
if (language === 'c' && owner && owner.kind === 'record') owner.kind = 'thing';
|
|
395
695
|
const v = visualFor(item);
|
|
396
|
-
const setup = (/^(__init__|constructor|init|New|__construct|initialize|new)$/.test(
|
|
397
|
-
const kind = setup ? 'setup' : v.element === 'action' ? 'action' : v.element === 'decision' ? 'rule' : v.element === 'not-read' ? 'not-read' : 'steps';
|
|
398
|
-
const bodyEnd = item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
|
|
696
|
+
const setup = (/^(__init__|constructor|init|New|__construct|initialize|new)$/.test(own) || (language === 'c' && /^(?:create|make|alloc)$/.test(own)) || (owner && item.name === owner.name)) && owner;
|
|
697
|
+
const kind = language === 'github-actions' ? 'pipeline' : language === 'dockerfile' ? 'image-build' : setup ? 'setup' : v.element === 'action' ? 'action' : v.element === 'decision' ? 'rule' : v.element === 'not-read' ? 'not-read' : 'steps';
|
|
698
|
+
const bodyEnd = item.endLine ?? item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
|
|
399
699
|
let rule = null;
|
|
400
700
|
if (kind === 'rule') { try { rule = plainFromReading(item); } catch { rule = null; } }
|
|
401
701
|
const m = {
|
|
402
|
-
id: idOf(f.path,
|
|
403
|
-
label: setup ? `A new ${owner.label} starts with` : cap(words(
|
|
702
|
+
id: idOf(f.path, inside?.name ?? '', item.name, item.line), kind, name: item.name,
|
|
703
|
+
label: setup ? `A new ${owner.label} starts with` : infra && item.label ? item.label : /^~/.test(item.name) ? 'Clean up' : cap(words(own.replace(/^__|__$/g, ''))),
|
|
404
704
|
...(owner ? { owner: owner.id } : {}), file: f.path, language, lines: [item.line, bodyEnd],
|
|
405
|
-
...(item.doc ? { doc: item.doc } : {}), ...(item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {}),
|
|
705
|
+
...(item.doc ? { doc: item.doc } : {}), ...(item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {}), ...(item.when ? { when: item.when } : {}),
|
|
706
|
+
...(item.assignedTo ? { assignedTo: item.assignedTo } : {}), ...(item.callback ? { callback: true, ...(item.passedTo ? { passedTo: item.passedTo } : {}) } : {}),
|
|
406
707
|
youGive: youGiveOf(item),
|
|
708
|
+
// Each input's kind in words, when the code says it (days late: a number; request: a PingResource).
|
|
709
|
+
...(inputKindsOf(item) ? { inputKinds: inputKindsOf(item) } : {}),
|
|
407
710
|
...(item.returns && kind !== 'rule' ? { youGetBack: kindWords(item.returns) ?? item.returns } : {}),
|
|
408
711
|
...(rule ? { rule, question: rule.question } : {}),
|
|
409
712
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
410
713
|
...(kind === 'rule' ? { yesNo: [...(item.rules || []).map((r) => r.result), item.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {}),
|
|
411
|
-
_steps: item.steps || [], _item: item,
|
|
714
|
+
_steps: item.steps || [], _item: item, ...(item.qualifier && !owner ? { _qualifier: item.qualifier } : {}),
|
|
412
715
|
};
|
|
413
716
|
if (owner) owner.can.push(m.id);
|
|
717
|
+
// How many values it takes (not shown; used to tell overloads apart when a call is linked across files).
|
|
718
|
+
Object.defineProperty(m, 'arity', { value: (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name)).length, enumerable: false });
|
|
414
719
|
if (kind === 'not-read') unknowns.push({ id: m.id, file: f.path, line: item.line, why: 'Thunder cannot explain this function yet; its code is shown instead.' });
|
|
415
720
|
return m;
|
|
416
721
|
});
|
|
@@ -418,14 +723,61 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
418
723
|
const byName = new Map(fileMembers.map((m) => [m.name.toLowerCase(), m.id]));
|
|
419
724
|
const labels = new Map(fileMembers.map((m) => [m.id, m.label]));
|
|
420
725
|
for (const m of fileMembers) {
|
|
421
|
-
const start = m.youGive.length ? `You give it: ${m.youGive.join(', ')}` : 'Start';
|
|
726
|
+
const start = m.when ?? (m.youGive.length ? `You give it: ${m.youGive.join(', ')}` : 'Start');
|
|
422
727
|
m.flow = m.kind === 'rule' || (m._item.kind === 'decision' && m._item.rules?.length) ? ruleFlow(m._item, start) : flowOf(m._steps, { start, memberIndex: byName, memberLabel: labels });
|
|
728
|
+
if (m.when) { const s0 = m.flow.nodes.find((nd) => nd.kind === 'start'); if (s0) s0.does = 'when'; }
|
|
423
729
|
for (const nd of m.flow.nodes) if (nd.uses && nd.uses !== m.id) links.push({ from: m.id, to: nd.uses, kind: 'uses', node: nd.id });
|
|
424
730
|
delete m._steps; delete m._item;
|
|
731
|
+
// An action's "You get back": every way it ends, from its flow (what it sends back, and the statuses it can stop
|
|
732
|
+
// with), rather than only a declared return type a web handler rarely has.
|
|
733
|
+
if (m.route && m.kind !== 'setup') {
|
|
734
|
+
// (An ending shown as code is not a value in words: it is not listed here, so code never poses as an answer.)
|
|
735
|
+
const ends = [...new Set(m.flow.nodes.filter((nd) => nd.kind === 'end' && !nd.code && !/^(?:Stops here|Done)$/.test(nd.text)).map((nd) => nd.text.replace(/^Gives back /, '')))];
|
|
736
|
+
const stopsWith = [...new Set(m.flow.nodes.filter((nd) => nd.kind === 'stop').map((nd) => (nd.text.match(/^Stop:\s*(\d{3})\b/) || [])[1] ?? nd.text.replace(/^Stop:\s*/, '').split(':')[0].trim()))];
|
|
737
|
+
const parts = [ends.length ? ends.join(', or ') : null, stopsWith.length ? `it stops with ${stopsWith.join(' or ')}` : null].filter(Boolean);
|
|
738
|
+
if (parts.length) m.youGetBack = parts.join('; or ');
|
|
739
|
+
}
|
|
425
740
|
members.push(m);
|
|
426
741
|
}
|
|
742
|
+
// Links the file states (a stage that starts from another, a job that needs another), by member id.
|
|
743
|
+
if (infra) {
|
|
744
|
+
const byItem = new Map(fileMembers.map((m) => [`${m.name}:${m.lines[0]}`, m.id]));
|
|
745
|
+
const byThing = new Map(fileThings.map((t) => [t.name, t.id]));
|
|
746
|
+
for (const l of infra.links) {
|
|
747
|
+
const from = byItem.get(l.from) ?? byThing.get(l.from), to = byItem.get(l.to) ?? byThing.get(l.to);
|
|
748
|
+
const key = `${from}>${to}>${l.kind}>${l.line}`;
|
|
749
|
+
if (from && to && !linkKeys.has(key)) { linkKeys.add(key); links.push({ from, to, kind: l.kind, file: l.file, line: l.line }); }
|
|
750
|
+
// A Terraform module is a folder: a reference to a resource in another file of it is drawn once all are read.
|
|
751
|
+
// Kubernetes and Compose resources (and the Dockerfile a Compose service builds) can be in other files too.
|
|
752
|
+
else if (from && !to && (language === 'terraform' || language === 'kubernetes' || language === 'docker-compose')) pending.push({ dir: dirOf(f.path), from, l, language });
|
|
753
|
+
}
|
|
754
|
+
}
|
|
427
755
|
}
|
|
428
|
-
|
|
756
|
+
if (pending.length) resolveAcrossFiles(pending, things, links, linkKeys);
|
|
757
|
+
// A Kubernetes workload whose image has exactly the name of the folder a Dockerfile in the repository is in uses
|
|
758
|
+
// that image (`image: gcr.io/shop/cart:1.2` and `cart/Dockerfile`). Exact names only, and only one such folder.
|
|
759
|
+
const dockerImages = things.filter((t) => t.resourceType === 'docker-image');
|
|
760
|
+
for (const t of things) for (const im of t.images ?? []) {
|
|
761
|
+
const hits = dockerImages.filter((d) => dirOf(d.address.slice('image:'.length)).split('/').pop() === im.name);
|
|
762
|
+
const key = hits.length === 1 && `${t.id}>${hits[0].id}>uses>${im.line}`;
|
|
763
|
+
if (key && !linkKeys.has(key)) { linkKeys.add(key); links.push({ from: t.id, to: hits[0].id, kind: 'uses', file: t.file, line: im.line }); }
|
|
764
|
+
}
|
|
765
|
+
// A method written in another file (Library::lateFee in library.cpp, extension Library in Library+Fees.swift)
|
|
766
|
+
// belongs to the one Thing with that name, wherever it is declared.
|
|
767
|
+
const thingsNamed = new Map();
|
|
768
|
+
for (const t of things) if (t.kind !== 'choices') thingsNamed.set(t.name, [...(thingsNamed.get(t.name) || []), t]);
|
|
769
|
+
for (const mem of members) {
|
|
770
|
+
const q = mem._qualifier;
|
|
771
|
+
delete mem._qualifier;
|
|
772
|
+
const found = q && !mem.owner ? thingsNamed.get(q) : null;
|
|
773
|
+
if (!found || found.length !== 1) continue;
|
|
774
|
+
const t = found[0];
|
|
775
|
+
mem.owner = t.id;
|
|
776
|
+
t.can.push(mem.id);
|
|
777
|
+
if (mem.name === t.name || /^(?:init|__init__)$/.test(mem.name)) { mem.kind = 'setup'; mem.label = `A new ${t.label} starts with`; }
|
|
778
|
+
if (t.kind === 'record') t.kind = 'thing';
|
|
779
|
+
}
|
|
780
|
+
for (const t of things) { delete t.memberRanges; delete t.images; delete t.podLabels; delete t.selects; delete t.assigned; delete t.ctor; delete t.spans; } // only used while the model is made
|
|
429
781
|
// An empty class (no facts, nothing it can do) is not a Thing a person needs to see: an error type is already shown
|
|
430
782
|
// where it stops a path, and any other empty class is a named record with no facts.
|
|
431
783
|
const owners = new Set(members.map((x) => x.owner).filter(Boolean));
|
|
@@ -434,22 +786,26 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
434
786
|
if (t.kind !== 'thing' || t.knows.length || owners.has(t.id)) continue;
|
|
435
787
|
if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1); else t.kind = 'record';
|
|
436
788
|
}
|
|
437
|
-
|
|
789
|
+
const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts };
|
|
790
|
+
// The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
|
|
791
|
+
try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
|
|
792
|
+
return model;
|
|
438
793
|
}
|
|
439
794
|
|
|
440
795
|
// ── Thunder Text, projected from the model (the picture is projected from the same nodes) ──────────────
|
|
441
796
|
|
|
442
|
-
/** Thunder Text lines from a flow's blocks: the same tree the picture is drawn from. */
|
|
443
|
-
function flowLines(flow, depth = 1) {
|
|
797
|
+
/** Thunder Text lines from a flow's blocks: the same tree the picture is drawn from. `full`: every detail too. */
|
|
798
|
+
function flowLines(flow, depth = 1, note = null, full = false) {
|
|
444
799
|
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
445
800
|
const out = [];
|
|
446
801
|
const pad = (d) => ' '.repeat(d);
|
|
447
|
-
|
|
448
|
-
const
|
|
802
|
+
// `note` (optional) adds words after a node: the running system's counts (running.mjs).
|
|
803
|
+
const at = (n) => `${n.line ? ` (line ${n.line})` : ''}${(note && note(n)) || ''}`;
|
|
804
|
+
const say = (n) => (n.kind === 'code' || (n.kind === 'end' && n.code) ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' && n.cases ? n.text : n.kind === 'decision' ? `Ask: ${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
|
|
449
805
|
const go = (blocks, d) => {
|
|
450
806
|
for (const b of blocks || []) {
|
|
451
807
|
const n = byId.get(b.id);
|
|
452
|
-
out.push(`${pad(d)}- ${say(n)}${at(n)}`);
|
|
808
|
+
out.push(`${pad(d)}- ${say(n)}${full && n.detail ? ` — ${n.detail}` : ''}${at(n)}`);
|
|
453
809
|
if (n.kind === 'decision') {
|
|
454
810
|
for (const side of ['yes', 'no']) {
|
|
455
811
|
if (!(side in b)) continue;
|
|
@@ -457,9 +813,13 @@ function flowLines(flow, depth = 1) {
|
|
|
457
813
|
else out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}: continue`);
|
|
458
814
|
}
|
|
459
815
|
}
|
|
816
|
+
for (const c of b.cases || []) {
|
|
817
|
+
if (c.blocks.length) { out.push(`${pad(d + 1)}${c.label}:`); go(c.blocks, d + 2); }
|
|
818
|
+
else out.push(`${pad(d + 1)}${c.label}: nothing`);
|
|
819
|
+
}
|
|
460
820
|
if (b.each) { out.push(`${pad(d + 1)}For each:`); go(b.each, d + 2); }
|
|
461
821
|
if (b.body) go(b.body, d + 1);
|
|
462
|
-
for (const h of b.handlers || []) {
|
|
822
|
+
for (const h of b.handlers || []) { const t = byId.get(h.id).text.replace(/\?$/, ''); if (h.blocks.length) { out.push(`${pad(d + 1)}${t}:`); go(h.blocks, d + 2); } else out.push(`${pad(d + 1)}${t}: nothing (the error is ignored)`); }
|
|
463
823
|
if (b.always) { out.push(`${pad(d + 1)}Always, at the end:`); go(b.always.blocks, d + 2); }
|
|
464
824
|
}
|
|
465
825
|
};
|
|
@@ -471,37 +831,53 @@ function flowLines(flow, depth = 1) {
|
|
|
471
831
|
* Thunder Text for a Thing or a member, made from the same model nodes the picture is drawn from, so the two
|
|
472
832
|
* cannot disagree. Pass the model and an id.
|
|
473
833
|
*/
|
|
474
|
-
export function modelText(model, id) {
|
|
834
|
+
export function modelText(model, id, { note = null, full = false } = {}) {
|
|
475
835
|
const t = model.things.find((x) => x.id === id);
|
|
476
836
|
if (t) {
|
|
477
|
-
const lines = [`${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
|
|
837
|
+
const lines = [t.kind === 'resource' ? `Resource ${t.label} (${t.resourceType})` : `${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
|
|
478
838
|
if (t.doc) lines.push(` Author's note: ${t.doc}`);
|
|
479
839
|
if (t.choices.length) lines.push(` One of: ${t.choices.join(', ')}`);
|
|
480
840
|
if (t.knows.length) { lines.push(' It knows'); for (const k of t.knows) lines.push(` ${k.label}: ${[k.kind, k.start].filter(Boolean).join(', ') || 'a value'}`); }
|
|
481
|
-
|
|
841
|
+
const can = t.can.map((c) => model.members.find((m) => m.id === c)).filter((m) => m && !m.callback);
|
|
842
|
+
if (can.length) { lines.push(' It can'); for (const m of can) lines.push(` ${m.label}`); }
|
|
482
843
|
return `${lines.join('\n')}\n`;
|
|
483
844
|
}
|
|
484
845
|
const m = model.members.find((x) => x.id === id);
|
|
485
846
|
if (!m) throw new Error(`Nothing in the model has id ${id}.`);
|
|
486
847
|
const owner = m.owner && model.things.find((x) => x.id === m.owner);
|
|
487
848
|
const lines = [`${m.label}${owner && m.kind !== 'setup' ? ` (${owner.label})` : ''}${m.kind === 'rule' ? ': a rule' : ''}`];
|
|
488
|
-
if (m.
|
|
849
|
+
if (m.when) lines.push(` ${m.when}`);
|
|
850
|
+
else if (m.route) lines.push(` When someone calls ${m.route}`);
|
|
489
851
|
if (m.doc) lines.push(` Author's note: ${m.doc}`);
|
|
490
852
|
if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(', ')}`);
|
|
491
853
|
if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
|
|
492
|
-
lines.push(...flowLines(m.flow));
|
|
854
|
+
lines.push(...flowLines(m.flow, 1, note, full));
|
|
493
855
|
return `${lines.join('\n')}\n`;
|
|
494
856
|
}
|
|
495
857
|
|
|
496
858
|
// ── The five reading levels: what each one shows, decided here so every product shows the same thing ─────────
|
|
497
859
|
|
|
498
|
-
const SYMBOL_OF = { action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices' };
|
|
860
|
+
const SYMBOL_OF = { action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
|
|
861
|
+
|
|
862
|
+
const SETTING_WORDS = { parameter: 'given when it starts or is built', variable: 'a variable kept outside the file', secret: 'a secret (only its name is shown)', literal: 'written in the file', computed: 'worked out when it runs' };
|
|
863
|
+
const APPLIED_WORDS = { parameter: 'given when it is applied', computed: 'worked out when it is applied' };
|
|
864
|
+
/** A setting in words: where it comes from, its default when the file writes one, and whether it is a secret. */
|
|
865
|
+
function settingWords(x, model) {
|
|
866
|
+
const lang = model.files.find((f) => f.path === x.file)?.language;
|
|
867
|
+
const applied = lang === 'terraform' || lang === 'bicep';
|
|
868
|
+
if (x.output) return `given back once it is applied${x.from?.length ? `, from ${x.from.join(', ')}` : ''}${x.secret ? ' (a secret: only its name is shown)' : ''}`;
|
|
869
|
+
const base = (applied && APPLIED_WORDS[x.source]) || (SETTING_WORDS[x.source] ?? x.source);
|
|
870
|
+
if (x.secret && x.source !== 'secret') return `${base}, a secret (only its name is shown)`;
|
|
871
|
+
return `${base}${x.default != null && x.source === 'parameter' ? ` (${x.default} unless told otherwise)` : ''}`;
|
|
872
|
+
}
|
|
499
873
|
|
|
500
874
|
/** Every step of a flow in reading order, with how deep it sits and which path it is on (Yes, No, For each, …). */
|
|
501
875
|
function detailSteps(flow) {
|
|
502
876
|
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
503
877
|
const out = [];
|
|
504
|
-
const push = (n, depth, via, text = n.text) => out.push({ id: n.id, text, does: n.does, mark: DOES[n.does]?.mark ?? '·', line: n.line ?? null, depth, ...(via ? { via } : {}), ...(n.kind === 'code' ? { notExplained: true } : {})
|
|
878
|
+
const push = (n, depth, via, text = n.text) => out.push({ id: n.id, text, does: n.does, mark: DOES[n.does]?.mark ?? '·', line: n.line ?? null, depth, ...(via ? { via } : {}), ...(n.kind === 'code' || n.code ? { notExplained: true } : {}),
|
|
879
|
+
// One level down: the full meaning, and what the short words leave out.
|
|
880
|
+
...(n.expr ? { expr: n.expr } : {}), ...(n.detail ? { detail: n.detail, full: `${text} — ${n.detail}` } : {}) });
|
|
505
881
|
// `via` (Yes, No, For each) labels only the first step of each path, the way Thunder Text writes "Yes:" once.
|
|
506
882
|
const walk = (blocks, depth, via) => {
|
|
507
883
|
for (const b of blocks || []) {
|
|
@@ -510,6 +886,7 @@ function detailSteps(flow) {
|
|
|
510
886
|
walk(b.yes, depth + 1, 'Yes');
|
|
511
887
|
walk(b.no, depth + 1, 'No');
|
|
512
888
|
walk(b.each, depth + 1, 'For each');
|
|
889
|
+
for (const c of b.cases || []) walk(c.blocks, depth + 1, c.label);
|
|
513
890
|
walk(b.body, depth + 1, null);
|
|
514
891
|
for (const h of b.handlers || []) { const hn = byId.get(h.id); if (hn) push(hn, depth, null, hn.text.replace(/\?$/, '')); walk(h.blocks, depth + 1, null); }
|
|
515
892
|
if (b.always) { const an = byId.get(b.always.id); if (an) push(an, depth, null); walk(b.always.blocks, depth + 1, null); }
|
|
@@ -525,27 +902,34 @@ function detailSteps(flow) {
|
|
|
525
902
|
const CHANGES = /^(Sets|Adds|Removes|Subtracts|Clears|Marks|Saves|Deletes|Updates|Appends|Increases|Decreases|Sends|Records|Stores|Writes)\b/;
|
|
526
903
|
|
|
527
904
|
/** Each step with the answers that lead to it: [{ question, answer }] from the top of the flow. */
|
|
528
|
-
function pathsOf(flow) {
|
|
905
|
+
export function pathsOf(flow) {
|
|
529
906
|
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
530
907
|
const out = [];
|
|
531
908
|
const ends = (blocks) => { const last = byId.get((blocks || []).at(-1)?.id); return !!last && (last.kind === 'stop' || last.kind === 'end'); };
|
|
532
909
|
const walk = (blocks, when) => {
|
|
533
910
|
for (const b of blocks || []) {
|
|
534
911
|
const n = byId.get(b.id);
|
|
912
|
+
// Nothing after a Stop or an answer on the same path can happen: those steps are not endings.
|
|
913
|
+
if (out.ended?.has(blocks)) break;
|
|
535
914
|
if (n && n.kind !== 'start') out.push({ node: n, when });
|
|
915
|
+
if (n && (n.kind === 'stop' || n.kind === 'end')) (out.ended ||= new Set()).add(blocks);
|
|
536
916
|
const q = n?.text ?? '';
|
|
537
|
-
|
|
538
|
-
|
|
917
|
+
const yes = { question: q, answer: 'Yes', ...(n?.holds ? { says: n.holds.yes } : {}) };
|
|
918
|
+
const no = { question: q, answer: 'No', ...(n?.holds ? { says: n.holds.no } : {}) };
|
|
919
|
+
walk(b.yes, [...when, yes]);
|
|
920
|
+
walk(b.no, [...when, no]);
|
|
539
921
|
walk(b.each, [...when, { question: q, answer: 'For each' }]);
|
|
540
|
-
|
|
922
|
+
for (const c of b.cases || []) walk(c.blocks, [...when, { question: q, answer: c.label }]);
|
|
923
|
+
// An inner function's steps end only that function: not one of this action's endings.
|
|
924
|
+
if (!b.nested) walk(b.body, when);
|
|
541
925
|
for (const h of b.handlers || []) { const hn = byId.get(h.id); walk(h.blocks, [...when, { question: (hn?.text ?? '').replace(/\?$/, ''), answer: 'Yes' }]); }
|
|
542
926
|
if (b.always) walk(b.always.blocks, when);
|
|
543
927
|
// A question whose one side ends the path (a Stop or an answer) guards everything after it: what follows only
|
|
544
928
|
// happens on the other side. "Gives back org" happens when "Is org set?" is Yes, not always.
|
|
545
929
|
if (n?.kind === 'decision' && (b.yes || b.no)) {
|
|
546
930
|
const yesEnds = ends(b.yes), noEnds = ends(b.no);
|
|
547
|
-
if (yesEnds && !noEnds) when = [...when,
|
|
548
|
-
else if (noEnds && !yesEnds) when = [...when,
|
|
931
|
+
if (yesEnds && !noEnds) when = [...when, no];
|
|
932
|
+
else if (noEnds && !yesEnds) when = [...when, yes];
|
|
549
933
|
}
|
|
550
934
|
}
|
|
551
935
|
};
|
|
@@ -586,28 +970,44 @@ function ruleRanges(rule) {
|
|
|
586
970
|
return { fact: rule.inputs[0].label.replace(/^the /, ''), ranges };
|
|
587
971
|
}
|
|
588
972
|
|
|
973
|
+
/** What a link adds to the member it points at: another file, or the request or event it sends. */
|
|
974
|
+
function linkFacts(l, other, member) {
|
|
975
|
+
const out = {};
|
|
976
|
+
if (l.kind !== 'uses') out.kind = l.kind;
|
|
977
|
+
if (other && other.file !== member.file) { out.file = other.file; out.crossFile = true; }
|
|
978
|
+
if (l.line != null && l.crossFile) out.line = l.line;
|
|
979
|
+
if (l.kind === 'sends-to') out.service = l.method ? `${l.method} ${l.path}` : l.event ? `event ${l.event}` : l.task ? `task ${l.task}` : 'a message';
|
|
980
|
+
if (l.route) out.route = l.route;
|
|
981
|
+
return out;
|
|
982
|
+
}
|
|
983
|
+
|
|
589
984
|
function detailsFacts(model, member) {
|
|
590
985
|
const paths = pathsOf(member.flow);
|
|
591
986
|
const memberOf = (id) => model.members.find((m) => m.id === id);
|
|
592
987
|
const inputs = member.youGive.map((label) => {
|
|
593
988
|
const re = new RegExp(`\\b${label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
|
|
594
989
|
const lines = [...new Set(paths.filter((p) => re.test(p.node.text) && p.node.line).map((p) => p.node.line))];
|
|
595
|
-
return { label, lines };
|
|
990
|
+
return { label, lines, ...(member.inputKinds?.[label] ? { kind: member.inputKinds[label] } : {}) };
|
|
596
991
|
});
|
|
597
992
|
const changes = paths.filter((p) => p.node.kind !== 'decision' && p.node.kind !== 'stop' && p.node.kind !== 'end' && (p.node.does === 'save' || p.node.does === 'send' || (CHANGES.test(p.node.text) && /'s\b|\bto\b|\bfrom\b/.test(p.node.text))))
|
|
598
993
|
.map((p) => ({ text: p.node.text, line: p.node.line ?? null, does: p.node.does, when: p.when }));
|
|
599
994
|
const stops = paths.filter((p) => p.node.kind === 'stop').map((p) => {
|
|
600
|
-
|
|
995
|
+
// `Stop: Error: "the code's message"`, or `Stop: Refused by the database: why` (a reason Thunder words itself,
|
|
996
|
+
// never quoted, since the code holds no such message).
|
|
997
|
+
const m = p.node.text.match(/^Stop:\s*([^:]+?)(?::\s*"(.*)")?$/) ?? p.node.text.match(/^Stop:\s*(Refused by the database):\s*(.+)$/);
|
|
601
998
|
return { error: m ? m[1].trim() : p.node.text, ...(m?.[2] ? { message: m[2] } : {}), line: p.node.line ?? null, when: p.when };
|
|
602
999
|
});
|
|
603
1000
|
const givesBack = paths.filter((p) => p.node.kind === 'end' || p.node.answer).map((p) => ({ text: p.node.answer ? answerWords(p.node.text) : p.node.text, line: p.node.line ?? null, when: p.node.otherwise ? [{ question: 'none of the above', answer: 'Otherwise' }] : p.when }));
|
|
604
|
-
|
|
1001
|
+
// Each link once per member and kind; a call to another file says which file, a request or event says what it sends.
|
|
1002
|
+
const relied = new Map();
|
|
1003
|
+
for (const l of model.links) if (l.from === member.id && !relied.has(`${l.to}|${l.kind}`)) relied.set(`${l.to}|${l.kind}`, l);
|
|
1004
|
+
const reliesOn = [...relied.values()].map((l) => [l, memberOf(l.to)]).filter(([, t]) => t).map(([l, t]) => {
|
|
605
1005
|
const answers = t.rule ? ruleAnswers(t.rule) : null;
|
|
606
1006
|
const flowAnswers = [...new Set(t.flow.nodes.filter((n) => n.answer).map((n) => n.text))];
|
|
607
1007
|
const list = answers ? answers.map((a) => a.answer) : flowAnswers;
|
|
608
1008
|
const says = list.length ? `Answers ${list.join(', ').replace(/, ([^,]*)$/, list.length > 2 ? ', or $1' : ' or $1')}.`
|
|
609
1009
|
: t.youGetBack ? `Gives back ${t.youGetBack}.` : t.flow.nodes.some((n) => n.kind === 'stop') ? `Can stop with ${t.flow.nodes.filter((n) => n.kind === 'stop').map((n) => n.text.replace(/^Stop:\s*/, '').split(':')[0]).join(', ')}.` : `${t.flow.nodes.filter((n) => n.kind !== 'start').length} steps.`;
|
|
610
|
-
return { id: t.id, label: t.label + (t.yesNo ? '?' : ''), symbol: SYMBOL_OF[t.kind], says };
|
|
1010
|
+
return { id: t.id, label: t.label + (t.yesNo ? '?' : ''), symbol: SYMBOL_OF[t.kind], says, ...linkFacts(l, t, member) };
|
|
611
1011
|
});
|
|
612
1012
|
const answers = member.rule ? ruleAnswers(member.rule) : null;
|
|
613
1013
|
const limits = member.rule ? ruleRanges(member.rule) : null;
|
|
@@ -620,7 +1020,7 @@ function detailsFacts(model, member) {
|
|
|
620
1020
|
* Thing or member id, or nothing for the whole model. Flow and Details need an action or rule; without one they
|
|
621
1021
|
* give back `needsFocus` and the list to choose from. Deterministic; built only from the model.
|
|
622
1022
|
*/
|
|
623
|
-
export function readLevel(model, level, focus) {
|
|
1023
|
+
export function readLevel(model, level, focus, { full = false } = {}) {
|
|
624
1024
|
const lv = LEVELS.find((l) => l.id === level);
|
|
625
1025
|
if (!lv) throw new Error(`Unknown reading level "${level}". Use one of: ${LEVELS.map((l) => l.id).join(', ')}.`);
|
|
626
1026
|
const member = focus ? model.members.find((m) => m.id === focus) : undefined;
|
|
@@ -634,8 +1034,10 @@ export function readLevel(model, level, focus) {
|
|
|
634
1034
|
? { scope: 'member', id: member.id, title: member.label + (member.yesNo ? '?' : ''), symbol: SYMBOL_OF[member.kind], file: member.file, lines: member.lines }
|
|
635
1035
|
: thing ? { scope: 'thing', id: thing.id, title: thing.label, symbol: SYMBOL_OF[thing.kind], file: thing.file, lines: thing.lines }
|
|
636
1036
|
: { scope: 'app', id: null, title: model.name, symbol: 'app', file: model.files[0]?.path ?? null, lines: null };
|
|
637
|
-
const
|
|
638
|
-
const
|
|
1037
|
+
const memberById = (id) => model.members.find((m) => m.id === id);
|
|
1038
|
+
const once = (ls, key) => { const seen = new Set(); return ls.filter((l) => { const k = `${l[key]}|${l.kind}`; if (seen.has(k)) return false; seen.add(k); return true; }); };
|
|
1039
|
+
const uses = member ? once(model.links.filter((l) => l.from === member.id), 'to').map((l) => ({ id: l.to, label: labelOf(l.to), ...linkFacts(l, memberById(l.to), member) })) : [];
|
|
1040
|
+
const usedBy = member ? once(model.links.filter((l) => l.to === member.id), 'from').map((l) => ({ id: l.from, label: labelOf(l.from), ...linkFacts(l, memberById(l.from), member) })) : [];
|
|
639
1041
|
|
|
640
1042
|
if (!member && (lv.id === 'flow' || lv.id === 'details')) {
|
|
641
1043
|
const inScope = model.members.filter((m) => m.kind !== 'setup' && (!thing || m.owner === thing.id));
|
|
@@ -647,26 +1049,40 @@ export function readLevel(model, level, focus) {
|
|
|
647
1049
|
...(owner ? { owner: { id: owner.id, label: owner.label } } : {}), youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), uses, usedBy };
|
|
648
1050
|
}
|
|
649
1051
|
const inScope = (m) => m.kind !== 'setup' && (thing ? m.owner === thing.id : true);
|
|
650
|
-
const
|
|
1052
|
+
const resourceCard = (t) => ({ id: t.id, label: t.label, symbol: 'resource', resourceType: t.resourceType, address: t.address, file: t.file,
|
|
1053
|
+
knows: t.knows.map((k) => ({ label: k.label, value: k.kind, ...(k.computed ? { computed: true } : {}), ...(k.secret ? { secret: true } : {}), line: k.line })),
|
|
1054
|
+
links: (model.links || []).filter((l) => l.from === t.id || l.to === t.id).map((l) => ({ from: l.from, to: l.to, kind: l.kind, ...(l.line ? { line: l.line } : {}) })) });
|
|
1055
|
+
const resource = thing?.kind === 'resource' ? thing : null;
|
|
1056
|
+
const thingCard = (t) => ({ id: t.id, label: t.label, ...(t.doc ? { doc: t.doc } : {}), knows: t.knows.map((k) => ({ label: k.label, ...(k.start ? { start: k.start } : {}) })), can: model.members.filter((m) => m.owner === t.id && m.kind !== 'setup' && !m.callback).map(short) });
|
|
651
1057
|
return { ...base, ...about,
|
|
652
1058
|
...(thing?.doc ?? model.files[0]?.purpose ? { purpose: thing?.doc ?? model.files[0]?.purpose } : {}),
|
|
653
|
-
things: (thing ? [thing] : model.things.filter((t) => t.kind === 'thing')).map(thingCard),
|
|
654
|
-
|
|
1059
|
+
things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing')).map(thingCard),
|
|
1060
|
+
resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === 'resource')).map(resourceCard),
|
|
1061
|
+
...(thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] }),
|
|
1062
|
+
data: thing ? [] : model.things.filter((t) => t.kind !== 'thing' && t.kind !== 'resource').map((t) => ({ id: t.id, label: t.label, symbol: SYMBOL_OF[t.kind], ...(t.choices.length ? { choices: t.choices } : {}), knows: t.knows.map((k) => k.label) })),
|
|
655
1063
|
actions: model.members.filter((m) => inScope(m) && m.kind === 'action').map(short),
|
|
656
1064
|
rules: model.members.filter((m) => inScope(m) && m.kind === 'rule').map(short),
|
|
657
|
-
|
|
658
|
-
|
|
1065
|
+
// (A callback is reached from the step that passes it, not listed on its own.)
|
|
1066
|
+
loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
|
|
1067
|
+
unknowns: thing ? [] : model.unknowns,
|
|
1068
|
+
// The app's map: which areas (folders) call which, and send requests or events to which.
|
|
1069
|
+
...(thing ? {} : { calls: callsSummary(model), notLinked: model.notLinked ?? [] }) };
|
|
659
1070
|
}
|
|
660
1071
|
if (lv.id === 'flow') return { ...base, ...about, flow: member.flow };
|
|
661
1072
|
if (lv.id === 'details') {
|
|
662
1073
|
const steps = detailSteps(member.flow);
|
|
663
1074
|
return { ...base, ...about, youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), ...(member.doc ? { doc: member.doc } : {}),
|
|
664
1075
|
...detailsFacts(model, member), steps,
|
|
1076
|
+
// Calls and requests worth linking that could not be, with the reason (never guessed).
|
|
1077
|
+
notLinked: (model.notLinked ?? []).filter((x) => x.from === member.id),
|
|
665
1078
|
notExplained: steps.filter((s) => s.notExplained).length, uses, usedBy, tryable: !!member.rule, ...(member.rule ? { rule: member.rule } : {}),
|
|
666
1079
|
source: 'Read from code by the Thunder compiler, with no AI.' };
|
|
667
1080
|
}
|
|
668
1081
|
if (lv.id === 'text') {
|
|
669
|
-
const
|
|
1082
|
+
const extra = [];
|
|
1083
|
+
if (!focus && model.permissions?.length) extra.push(`Permissions\n${model.permissions.map((p) => ` ${p.says ?? `${p.who} can ${p.can} ${p.on}`}${p.wide && !/\(wide\)/.test(p.says ?? '') ? ' (wide)' : ''} (line ${p.line})`).join('\n')}\n`);
|
|
1084
|
+
if (!focus && model.settings?.length) extra.push(`Settings\n${model.settings.map((x) => ` Setting ${x.name}: ${settingWords(x, model)} (line ${x.line})`).join('\n')}\n`);
|
|
1085
|
+
const text = focus ? modelText(model, focus, { full }) : [...model.things.map((t) => modelText(model, t.id)), ...model.members.filter((m) => !m.owner && m.kind !== 'setup').map((m) => modelText(model, m.id, { full })), ...extra].join('\n');
|
|
670
1086
|
return { ...base, ...about, text };
|
|
671
1087
|
}
|
|
672
1088
|
return { ...base, ...about, language: (member ?? thing) ? (member?.language ?? model.files.find((f) => f.path === thing.file)?.language ?? null) : (model.files[0]?.language ?? null) };
|