@skillstech/thunderlang 0.5.4 → 0.5.6
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 +112 -0
- package/README.md +3 -0
- package/dist/core.cjs +2240 -424
- package/dist/index.cjs +1247 -113
- package/dist/learn.cjs +6066 -0
- package/package.json +10 -1
- package/src/cli.mjs +45 -2
- package/src/core.d.ts +14 -0
- package/src/core.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/learn-lessons.mjs +458 -0
- package/src/learn.d.mts +34 -0
- package/src/learn.mjs +77 -0
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- package/src/read.d.mts +25 -1
- package/src/read.mjs +280 -23
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.mjs +351 -49
- package/src/thunder-repo.mjs +1 -1
- package/src/thunderize.d.mts +14 -0
- package/src/thunderize.mjs +82 -0
- package/src/visual.d.mts +40 -0
- package/src/visual.mjs +304 -0
package/src/model.mjs
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
// thunder-model-v1: the one meaning that every Thunder view is drawn from. Things (classes), Data (records and
|
|
2
|
+
// choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
|
|
3
|
+
// and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
|
|
4
|
+
// them may say more than the model does. Browser-safe: takes [{ path, source }].
|
|
5
|
+
import { readCode } from './read.mjs';
|
|
6
|
+
import { readableLanguage } from './read-repo.mjs';
|
|
7
|
+
import { plainFromReading } from './plain-contract.mjs';
|
|
8
|
+
import { visualFor } from './visual.mjs';
|
|
9
|
+
|
|
10
|
+
export const MODEL_SCHEMA = 'thunder-model-v1';
|
|
11
|
+
/** Languages whose classes, records, and choices are read today. Others still get every function. */
|
|
12
|
+
export const THING_LANGUAGES = ['python', 'typescript', 'javascript'];
|
|
13
|
+
|
|
14
|
+
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
15
|
+
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
16
|
+
const stripQuotes = (v) => v.replace(/^[rbuf]*(["'`])(.*)\1$/s, '$2');
|
|
17
|
+
|
|
18
|
+
/** How a starting value reads: "3 unless told otherwise", "empty at first", "on shelf at first". */
|
|
19
|
+
function startValue(expr, params = {}) {
|
|
20
|
+
const e = String(expr ?? '').trim();
|
|
21
|
+
if (!e) return null;
|
|
22
|
+
if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, '')} unless told otherwise` : 'given when it starts';
|
|
23
|
+
if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+)$/.test(e)) return 'empty at first';
|
|
24
|
+
if (/^(None|null|undefined)$/.test(e)) return 'nothing at first';
|
|
25
|
+
if (/^(True|true)$/.test(e)) return 'yes at first';
|
|
26
|
+
if (/^(False|false)$/.test(e)) return 'no at first';
|
|
27
|
+
if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
|
|
28
|
+
if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
|
|
29
|
+
const en = e.match(/^[A-Z]\w*\.([A-Z][A-Z0-9_]+)$/);
|
|
30
|
+
if (en) return `${words(en[1])} at first`;
|
|
31
|
+
return 'worked out when it starts';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const KIND_WORDS = [
|
|
35
|
+
[/^(int|float|number|double|long|decimal|Decimal|bigint)$/i, 'a number'],
|
|
36
|
+
[/^(str|string|String|text)$/i, 'words'],
|
|
37
|
+
[/^(bool|boolean)$/i, 'yes or no'],
|
|
38
|
+
[/^(date|datetime|Date|LocalDate|Instant)$/i, 'a date'],
|
|
39
|
+
];
|
|
40
|
+
function kindWords(type) {
|
|
41
|
+
const t = String(type ?? '').trim();
|
|
42
|
+
if (!t) return null;
|
|
43
|
+
for (const [re, w] of KIND_WORDS) if (re.test(t)) return w;
|
|
44
|
+
const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^Array<(.+)>$|^(.+)\[\]$/);
|
|
45
|
+
if (list) return `a list of ${(list[1] || list[2] || list[3]).trim()}s`;
|
|
46
|
+
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
|
|
47
|
+
if (opt) return `${kindWords(opt[1] || opt[2] || opt[3]) ?? `a ${opt[1] || opt[2] || opt[3]}`}, or nothing`;
|
|
48
|
+
return /^[A-Z]/.test(t) ? `a ${t}` : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ── Things: classes, records, and choices ───────────────────────────────────────────────────────────────
|
|
52
|
+
|
|
53
|
+
function pythonThings(src, file) {
|
|
54
|
+
const lines = src.split('\n');
|
|
55
|
+
const out = [];
|
|
56
|
+
for (let i = 0; i < lines.length; i++) {
|
|
57
|
+
const m = lines[i].match(/^(\s*)class\s+(\w+)\s*(?:\(([^)]*)\))?\s*:/);
|
|
58
|
+
if (!m) continue;
|
|
59
|
+
const indent = m[1].length;
|
|
60
|
+
const decorators = [];
|
|
61
|
+
for (let k = i - 1; k >= 0 && /^\s*@/.test(lines[k]); k--) decorators.unshift(lines[k].trim());
|
|
62
|
+
let end = i;
|
|
63
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
64
|
+
if (!lines[j].trim() || /^\s*#/.test(lines[j])) continue;
|
|
65
|
+
if (lines[j].match(/^\s*/)[0].length <= indent) break;
|
|
66
|
+
end = j;
|
|
67
|
+
}
|
|
68
|
+
const body = lines.slice(i + 1, end + 1);
|
|
69
|
+
const bodyIndent = (body.find((l) => l.trim()) || '').match(/^\s*/)[0].length;
|
|
70
|
+
const top = body.map((l, k) => ({ text: l, line: i + 2 + k })).filter((l) => l.text.trim() && l.text.match(/^\s*/)[0].length === bodyIndent);
|
|
71
|
+
const bases = (m[3] || '').split(',').map((b) => b.trim());
|
|
72
|
+
const isEnum = bases.some((b) => /(^|\.)(Enum|IntEnum|StrEnum|Flag)$/.test(b));
|
|
73
|
+
const isRecord = !isEnum && (decorators.some((d) => /@(dataclasses\.)?dataclass\b|@attr\.s\b|@define\b/.test(d)) || bases.some((b) => /(BaseModel|NamedTuple|TypedDict|Schema)$/.test(b)));
|
|
74
|
+
const docLine = top[0] && top[0].text.trim().match(/^[rRuU]?("""|'''|"|')(.*?)(\1)?$/);
|
|
75
|
+
const doc = docLine ? (docLine[3] ? docLine[2].trim() : docLine[2].trim()) || null : null;
|
|
76
|
+
const thing = { kind: isEnum ? 'choices' : isRecord ? 'record' : 'thing', name: m[2], file, lines: [i + 1, end + 1], indent, ...(doc ? { doc } : {}), knows: [], choices: [] };
|
|
77
|
+
for (const l of top) {
|
|
78
|
+
const t = l.text.trim();
|
|
79
|
+
if (/^(def|async def|class|@|"""|'''|#)/.test(t)) continue;
|
|
80
|
+
let f;
|
|
81
|
+
if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes(f[2].trim()) : words(f[1]));
|
|
82
|
+
else if ((f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/))) thing.knows.push({ name: f[1], label: words(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
|
|
83
|
+
}
|
|
84
|
+
// Facts set when a Thing starts: self.x = ... inside __init__.
|
|
85
|
+
const init = body.findIndex((l) => /^\s*def\s+__init__\s*\(/.test(l));
|
|
86
|
+
if (init >= 0) {
|
|
87
|
+
const sig = body.slice(init).join('\n').match(/def\s+__init__\s*\(([^)]*)\)/s);
|
|
88
|
+
const params = {};
|
|
89
|
+
for (const p of (sig?.[1] || '').split(',').map((x) => x.trim()).filter((x) => x && x !== 'self')) {
|
|
90
|
+
const pm = p.match(/^(\w+)(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/);
|
|
91
|
+
if (pm) params[pm[1]] = pm[2] ?? null;
|
|
92
|
+
}
|
|
93
|
+
const initIndent = body[init].match(/^\s*/)[0].length;
|
|
94
|
+
for (let k = init + 1; k < body.length; k++) {
|
|
95
|
+
const ln = body[k];
|
|
96
|
+
if (ln.trim() && ln.match(/^\s*/)[0].length <= initIndent) break;
|
|
97
|
+
const a = ln.trim().match(/^self\.(\w+)\s*(?::\s*([^=]+))?=\s*(.+)$/);
|
|
98
|
+
if (a && !thing.knows.some((x) => x.name === a[1])) {
|
|
99
|
+
// The parameter's declared type, when the value is a plain parameter name (never code in a pattern).
|
|
100
|
+
const pType = /^\w+$/.test(a[3].trim()) ? (sig?.[1] || '').match(new RegExp(`\\b${a[3].trim()}\\s*:\\s*([\\w\\[\\]. |]+)`))?.[1] : undefined;
|
|
101
|
+
thing.knows.push({ name: a[1], label: words(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? 'a list' : null), start: startValue(a[3], params), line: i + 2 + k });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
out.push(thing);
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function braceEnd(src, open) {
|
|
111
|
+
let depth = 0;
|
|
112
|
+
for (let i = open; i < src.length; i++) {
|
|
113
|
+
const c = src[i];
|
|
114
|
+
if (c === '"' || c === "'" || c === '`') { const q = c; for (i++; i < src.length && src[i] !== q; i++) if (src[i] === '\\') i++; continue; }
|
|
115
|
+
if (c === '{') depth++;
|
|
116
|
+
else if (c === '}' && --depth === 0) return i;
|
|
117
|
+
}
|
|
118
|
+
return -1;
|
|
119
|
+
}
|
|
120
|
+
const lineOf = (src, idx) => src.slice(0, idx).split('\n').length;
|
|
121
|
+
|
|
122
|
+
function tsThings(src, file) {
|
|
123
|
+
const out = [];
|
|
124
|
+
const re = /(?:^|\n)[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|enum)\s+(\w+)[^{]*\{/g;
|
|
125
|
+
let m;
|
|
126
|
+
while ((m = re.exec(src))) {
|
|
127
|
+
const open = m.index + m[0].length - 1;
|
|
128
|
+
const close = braceEnd(src, open);
|
|
129
|
+
if (close < 0) continue;
|
|
130
|
+
const body = src.slice(open + 1, close);
|
|
131
|
+
const startLine = lineOf(src, m.index + (m[0].startsWith('\n') ? 1 : 0));
|
|
132
|
+
const before = src.slice(0, m.index).split('\n').slice(-4).join('\n');
|
|
133
|
+
const docm = before.match(/\/\*\*([\s\S]*?)\*\/\s*$/);
|
|
134
|
+
const doc = docm ? docm[1].split('\n').map((l) => l.replace(/^\s*\*\s?/, '').trim()).filter((l) => l && !l.startsWith('@')).join(' ') || null : null;
|
|
135
|
+
const thing = { kind: m[1] === 'enum' ? 'choices' : m[1] === 'interface' ? 'record' : 'thing', name: m[2], file, lines: [startLine, lineOf(src, close)], ...(doc ? { doc } : {}), knows: [], choices: [] };
|
|
136
|
+
if (m[1] === 'enum') {
|
|
137
|
+
for (const part of body.split(',')) { const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s); if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes(e[2].trim()) : words(e[1])); }
|
|
138
|
+
} else {
|
|
139
|
+
// Only the class's own lines, not the bodies of its methods.
|
|
140
|
+
let depth = 0, own = '';
|
|
141
|
+
for (const c of body) { if (c === '{') depth++; if (depth === 0) own += c; if (c === '}') depth--; }
|
|
142
|
+
const ownLines = own.split(/[;\n]/).map((l) => l.trim()).filter(Boolean);
|
|
143
|
+
for (const l of ownLines) {
|
|
144
|
+
const f = l.match(/^(?:(?:public|private|protected|readonly|static|declare)\s+)*(\w+)(\?)?\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/) || l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*(\w+)()\s*=\s*(.+)$/);
|
|
145
|
+
if (!f || /\(/.test(f[1])) continue;
|
|
146
|
+
const hasType = f.length > 4 && f[3] && !l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*\w+\s*=/);
|
|
147
|
+
thing.knows.push({ name: f[1], label: words(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? (f[4] ? startValue(f[4]) : null) : startValue(f[3]), line: null });
|
|
148
|
+
}
|
|
149
|
+
const ctor = body.match(/constructor\s*\(([^)]*)\)\s*\{/);
|
|
150
|
+
if (ctor) {
|
|
151
|
+
const params = {};
|
|
152
|
+
for (const p of ctor[1].split(',').map((x) => x.trim()).filter(Boolean)) { const pm = p.match(/^(?:(?:public|private|protected|readonly)\s+)*(\w+)\??(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/); if (pm) params[pm[1]] = pm[2] ?? null; }
|
|
153
|
+
const cOpen = body.indexOf('{', ctor.index + ctor[0].length - 1);
|
|
154
|
+
const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
|
|
155
|
+
for (const a of cBody.matchAll(/this\.(\w+)\s*=\s*([^;\n]+)/g)) {
|
|
156
|
+
if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words(a[1]), kind: null, start: startValue(a[2], params), line: null });
|
|
157
|
+
else { const k = thing.knows.find((x) => x.name === a[1]); if (!k.start) k.start = startValue(a[2], params); }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
out.push(thing);
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── Flow: steps as a graph a person can follow ─────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* What kind of step this is, in a kid's words: find, keep-only, check, calculate, save, send, ask, repeat, answer,
|
|
170
|
+
* stop, or code (Thunder could not explain it). Shapes and colors key off this.
|
|
171
|
+
*/
|
|
172
|
+
export function stepDoes(step) {
|
|
173
|
+
const s = step.says || '', c = step.callee || '';
|
|
174
|
+
if (step.restates || step.kind === 'other') return 'code';
|
|
175
|
+
if (step.kind === 'fail') return 'stop';
|
|
176
|
+
if (step.kind === 'loop') return 'repeat';
|
|
177
|
+
if (step.kind === 'return') return 'answer';
|
|
178
|
+
if (step.kind === 'check') return 'check';
|
|
179
|
+
if (step.kind === 'branch') return 'decide';
|
|
180
|
+
if (/^Writes to the database|^(Records|Adds to|Removes)/.test(s)) return 'save';
|
|
181
|
+
if (/^(Sends an email|Announces an event|Writes a log)/.test(s)) return 'send';
|
|
182
|
+
if (/^(Calls another service|Calls Stripe)/.test(s)) return 'ask';
|
|
183
|
+
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';
|
|
184
|
+
if (step.kind === 'set') return 'calculate';
|
|
185
|
+
return 'do';
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** "the book's status" for book.status; plain words for everything else. */
|
|
189
|
+
const possessive = (text) => String(text)
|
|
190
|
+
.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)}`))
|
|
191
|
+
.replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
|
|
192
|
+
/** An answer as words: NoFee -> "No fee", true -> "Yes". */
|
|
193
|
+
const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : cap(words(r)));
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* A branch as a question a kid can answer with yes or no, asked the positive way round. "If book.status is not on
|
|
197
|
+
* shelf" becomes "Is the book's status on shelf?" with the Stop on the No side (flip). A call to a known rule is
|
|
198
|
+
* asked by the rule's own name: "Can borrow?".
|
|
199
|
+
*/
|
|
200
|
+
export function askAsQuestion(step, ruleLabel) {
|
|
201
|
+
let c = String(step.says).replace(/^If /, '').replace(/ \(\d+ steps? inside\)$/, '').trim();
|
|
202
|
+
let flip = false;
|
|
203
|
+
if (/^not: /.test(c)) { c = c.slice(5); flip = true; }
|
|
204
|
+
if (ruleLabel) {
|
|
205
|
+
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 || '');
|
|
206
|
+
// The negation is read from the code alone; the step's wording may already say "not" for the same reason.
|
|
207
|
+
return { text: `${ruleLabel.replace(/\?$/, '')}?`, flip: negated };
|
|
208
|
+
}
|
|
209
|
+
let m;
|
|
210
|
+
if ((m = c.match(/^not (.+)$/))) { c = m[1]; flip = !flip; }
|
|
211
|
+
if ((m = c.match(/^(.+?) is not (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip: !flip };
|
|
212
|
+
if ((m = c.match(/^(.+?) has no (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip: !flip };
|
|
213
|
+
if ((m = c.match(/^(.+?) is (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip };
|
|
214
|
+
if ((m = c.match(/^(.+?) has (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip };
|
|
215
|
+
return { text: `${cap(possessive(c))}?`, flip };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** A rule's own picture: each rule asked in order, the first Yes gives its answer, otherwise the fallback. */
|
|
219
|
+
export function ruleFlow(item, start) {
|
|
220
|
+
const nodes = [], edges = [];
|
|
221
|
+
let n = 0;
|
|
222
|
+
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, ...extra }); return id; };
|
|
223
|
+
let prev = node('start', start, { lane: 0, does: 'start' });
|
|
224
|
+
let label;
|
|
225
|
+
for (const r of item.rules || []) {
|
|
226
|
+
const d = node('decision', `${cap(possessive(r.says ?? r.when))}?`, { lane: 0, line: r.line, does: 'decide' });
|
|
227
|
+
edges.push({ from: prev, to: d, ...(label ? { label } : {}) });
|
|
228
|
+
const out = node('end', answerWords(r.result), { lane: 1, line: r.line, does: 'answer', answer: true, value: r.result });
|
|
229
|
+
edges.push({ from: d, to: out, label: 'yes' });
|
|
230
|
+
prev = d; label = 'no';
|
|
231
|
+
}
|
|
232
|
+
if (item.otherwise) {
|
|
233
|
+
const o = node('end', answerWords(item.otherwise.result), { lane: 0, line: item.otherwise.line, does: 'answer', answer: true, otherwise: true, value: item.otherwise.result });
|
|
234
|
+
edges.push({ from: prev, to: o, ...(label ? { label } : {}) });
|
|
235
|
+
}
|
|
236
|
+
// As a tree: each question's Yes gives its answer, its No asks the next question (or gives the fallback).
|
|
237
|
+
const decisions = nodes.filter((x) => x.kind === 'decision');
|
|
238
|
+
const answers = nodes.filter((x) => x.answer && !x.otherwise);
|
|
239
|
+
const fallback = nodes.find((x) => x.otherwise);
|
|
240
|
+
const chain = (i) => (i < decisions.length ? [{ id: decisions[i].id, yes: [{ id: answers[i].id }], no: chain(i + 1) }] : fallback ? [{ id: fallback.id }] : []);
|
|
241
|
+
return { nodes, edges, blocks: chain(0) };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Turn steps into nodes and edges. Deterministic; nothing is added that the steps do not say. */
|
|
245
|
+
export function flowOf(steps, { start = 'Start', memberIndex = new Map(), memberLabel = new Map() } = {}) {
|
|
246
|
+
const nodes = [], edges = [];
|
|
247
|
+
let n = 0;
|
|
248
|
+
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, ...extra }); return id; };
|
|
249
|
+
const connect = (open, to) => { for (const o of open) edges.push({ from: o.id, to, ...(o.label ? { label: o.label } : {}) }); };
|
|
250
|
+
// The first call in the step to another member of this file: self.can_borrow(...), delivery_fee(...), this.lateFee(...).
|
|
251
|
+
const usesOf = (st) => {
|
|
252
|
+
for (const c of String(st.code || '').matchAll(/(?:\b(?:self|this)\.)?\b([A-Za-z_]\w*)\s*\(/g)) {
|
|
253
|
+
const id = memberIndex.get(c[1].toLowerCase());
|
|
254
|
+
if (id) return id;
|
|
255
|
+
}
|
|
256
|
+
return null;
|
|
257
|
+
};
|
|
258
|
+
// walk returns { open, blocks }: open = edges still waiting for the next node; blocks = the same nodes as a tree
|
|
259
|
+
// (each question with its yes and no sides, loops with their body, try with its handlers and always), which is
|
|
260
|
+
// what the picture and Thunder Text are drawn from. The edges are the same flow as a graph, for other tools.
|
|
261
|
+
const walk = (list, open, lane) => {
|
|
262
|
+
const blocks = [];
|
|
263
|
+
for (const st of list) {
|
|
264
|
+
const does = stepDoes(st);
|
|
265
|
+
const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}) };
|
|
266
|
+
if (st.kind === 'branch') {
|
|
267
|
+
const { text, flip } = askAsQuestion(st, base.uses && memberLabel.get(base.uses));
|
|
268
|
+
const [into, past] = flip ? ['no', 'yes'] : ['yes', 'no'];
|
|
269
|
+
const d = node('decision', text, base);
|
|
270
|
+
connect(open, d);
|
|
271
|
+
const inside = walk(st.children || [], [{ id: d, label: into }], lane + 1);
|
|
272
|
+
// The other side of the question: its else (or else-if chain) when the code has one.
|
|
273
|
+
const other = st.otherwise?.length ? walk(st.otherwise, [{ id: d, label: past }], lane + 1) : { open: [{ id: d, label: past }], blocks: [] };
|
|
274
|
+
blocks.push({ id: d, [into]: inside.blocks, [past]: other.blocks });
|
|
275
|
+
open = [...other.open, ...inside.open];
|
|
276
|
+
} else if (st.kind === 'loop') {
|
|
277
|
+
const l = node('loop', st.says, base);
|
|
278
|
+
connect(open, l);
|
|
279
|
+
const body = walk(st.children || [], [{ id: l, label: 'each' }], lane + 1);
|
|
280
|
+
for (const b of body.open) edges.push({ from: b.id, to: l, label: 'next' });
|
|
281
|
+
blocks.push({ id: l, each: body.blocks });
|
|
282
|
+
open = [{ id: l, label: 'done' }];
|
|
283
|
+
} else if (st.kind === 'fail') {
|
|
284
|
+
const sn = node('stop', st.says.replace(/^Fails with /, 'Stop: '), base);
|
|
285
|
+
connect(open, sn);
|
|
286
|
+
blocks.push({ id: sn });
|
|
287
|
+
open = [];
|
|
288
|
+
} else if (st.kind === 'return') {
|
|
289
|
+
const e = node('end', st.restates ? st.code : st.says.replace(/^Returns /, 'Gives back '), { ...base, ...(st.restates ? { code: true } : {}) });
|
|
290
|
+
connect(open, e);
|
|
291
|
+
blocks.push({ id: e });
|
|
292
|
+
open = [];
|
|
293
|
+
} else if (st.kind === 'try') {
|
|
294
|
+
// Try: the normal path; each "If X goes wrong" handler beside it; "Always, at the end" after both.
|
|
295
|
+
const t = node('step', st.says, base);
|
|
296
|
+
connect(open, t);
|
|
297
|
+
const body = walk(st.children || [], [{ id: t }], lane);
|
|
298
|
+
let after = body.open;
|
|
299
|
+
const handlers = [];
|
|
300
|
+
for (const h of st.handlers || []) {
|
|
301
|
+
const hn = node('decision', `${h.says}?`, { line: h.line, lane: lane + 1, does: 'decide', handler: true });
|
|
302
|
+
edges.push({ from: t, to: hn, label: 'error' });
|
|
303
|
+
const hw = walk(h.steps, [{ id: hn, label: 'yes' }], lane + 1);
|
|
304
|
+
handlers.push({ id: hn, blocks: hw.blocks });
|
|
305
|
+
after = [...after, ...hw.open];
|
|
306
|
+
}
|
|
307
|
+
let always = null;
|
|
308
|
+
if (st.always) {
|
|
309
|
+
const an = node('step', 'Always, at the end', { line: st.always.line, lane, does: 'do', always: true });
|
|
310
|
+
connect(after, an);
|
|
311
|
+
const aw = walk(st.always.steps, [{ id: an }], lane);
|
|
312
|
+
always = { id: an, blocks: aw.blocks };
|
|
313
|
+
after = aw.open;
|
|
314
|
+
}
|
|
315
|
+
blocks.push({ id: t, body: body.blocks, ...(handlers.length ? { handlers } : {}), ...(always ? { always } : {}) });
|
|
316
|
+
open = after;
|
|
317
|
+
} else {
|
|
318
|
+
const k = node(does === 'code' ? 'code' : 'step', does === 'code' ? st.code ?? st.says : st.says, base);
|
|
319
|
+
connect(open, k);
|
|
320
|
+
open = [{ id: k }];
|
|
321
|
+
if (st.children?.length) {
|
|
322
|
+
const inner = walk(st.children, open, lane + 1);
|
|
323
|
+
blocks.push({ id: k, body: inner.blocks });
|
|
324
|
+
open = inner.open;
|
|
325
|
+
} else blocks.push({ id: k });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return { open, blocks };
|
|
329
|
+
};
|
|
330
|
+
const s0 = node('start', start, { lane: 0, does: 'start' });
|
|
331
|
+
const { open, blocks } = walk(steps || [], [{ id: s0 }], 0);
|
|
332
|
+
if (open.length) connect(open, node('end', 'Done', { lane: 0, does: 'answer' }));
|
|
333
|
+
// Rows: order of first appearance, so the picture reads top to bottom like the code.
|
|
334
|
+
nodes.forEach((x, i) => { x.row = i; });
|
|
335
|
+
return { nodes, edges, blocks };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ── The model ──────────────────────────────────────────────────────────────────────────────────────────
|
|
339
|
+
|
|
340
|
+
const idOf = (...parts) => parts.join('#').replace(/\s+/g, '');
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Read files into the one Thunder model. Things come from classes in THING_LANGUAGES; every function in every
|
|
344
|
+
* readable language becomes a member with its flow. Unknowns list what could not be read, so no view hides a gap.
|
|
345
|
+
*/
|
|
346
|
+
export function thunderModel(files, { name = 'app' } = {}) {
|
|
347
|
+
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
348
|
+
for (const f of files) {
|
|
349
|
+
const language = readableLanguage(f.path);
|
|
350
|
+
if (!language || !f.source) continue;
|
|
351
|
+
let reading;
|
|
352
|
+
try { reading = readCode(f.source, { language, file: f.path }); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); continue; }
|
|
353
|
+
let fileThings = [];
|
|
354
|
+
try { fileThings = language === 'python' ? pythonThings(f.source, f.path) : THING_LANGUAGES.includes(language) ? tsThings(f.source, f.path) : []; }
|
|
355
|
+
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
|
|
356
|
+
if (!THING_LANGUAGES.includes(language) && /\b(class|struct|record|enum|interface|data class)\s+[A-Z]/.test(f.source)) {
|
|
357
|
+
unknowns.push({ file: f.path, line: 1, why: `Classes, records, and choices in ${language} are not drawn as Things yet; their functions are read.` });
|
|
358
|
+
}
|
|
359
|
+
for (const t of fileThings) { t.id = idOf(f.path, t.name); t.label = cap(words(t.name)); t.can = []; things.push(t); }
|
|
360
|
+
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, ' ') : '';
|
|
361
|
+
fileInfo.push({ path: f.path, language, ...(moduleDoc ? { purpose: moduleDoc } : {}) });
|
|
362
|
+
|
|
363
|
+
const fns = reading.items.filter((i) => i.kind === 'function' || i.kind === 'decision');
|
|
364
|
+
const fileMembers = fns.map((item) => {
|
|
365
|
+
const owner = fileThings.filter((t) => item.line > t.lines[0] && item.line <= t.lines[1]).sort((a, b) => b.lines[0] - a.lines[0])[0];
|
|
366
|
+
const v = visualFor(item);
|
|
367
|
+
const setup = /^(__init__|constructor|init|New)$/.test(item.name) && owner;
|
|
368
|
+
const kind = setup ? 'setup' : v.element === 'action' ? 'action' : v.element === 'decision' ? 'rule' : v.element === 'not-read' ? 'not-read' : 'steps';
|
|
369
|
+
const bodyEnd = item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
|
|
370
|
+
let rule = null;
|
|
371
|
+
if (kind === 'rule') { try { rule = plainFromReading(item); } catch { rule = null; } }
|
|
372
|
+
const m = {
|
|
373
|
+
id: idOf(f.path, owner?.name ?? '', item.name, item.line), kind, name: item.name,
|
|
374
|
+
label: setup ? `A new ${owner.label} starts with` : cap(words(item.name.replace(/^__|__$/g, ''))),
|
|
375
|
+
...(owner ? { owner: owner.id } : {}), file: f.path, language, lines: [item.line, bodyEnd],
|
|
376
|
+
...(item.doc ? { doc: item.doc } : {}), ...(item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {}),
|
|
377
|
+
youGive: (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name)).map((p) => words(p.name)),
|
|
378
|
+
...(item.returns && kind !== 'rule' ? { youGetBack: kindWords(item.returns) ?? item.returns } : {}),
|
|
379
|
+
...(rule ? { rule, question: rule.question } : {}),
|
|
380
|
+
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
381
|
+
...(kind === 'rule' ? { yesNo: [...(item.rules || []).map((r) => r.result), item.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {}),
|
|
382
|
+
_steps: item.steps || [], _item: item,
|
|
383
|
+
};
|
|
384
|
+
if (owner) owner.can.push(m.id);
|
|
385
|
+
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.' });
|
|
386
|
+
return m;
|
|
387
|
+
});
|
|
388
|
+
// Flows need every member's name in the file, so a step can link to the rule or member it uses.
|
|
389
|
+
const byName = new Map(fileMembers.map((m) => [m.name.toLowerCase(), m.id]));
|
|
390
|
+
const labels = new Map(fileMembers.map((m) => [m.id, m.label]));
|
|
391
|
+
for (const m of fileMembers) {
|
|
392
|
+
const start = m.youGive.length ? `You give it: ${m.youGive.join(', ')}` : 'Start';
|
|
393
|
+
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 });
|
|
394
|
+
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 });
|
|
395
|
+
delete m._steps; delete m._item;
|
|
396
|
+
members.push(m);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ── Thunder Text, projected from the model (the picture is projected from the same nodes) ──────────────
|
|
403
|
+
|
|
404
|
+
/** Thunder Text lines from a flow's blocks: the same tree the picture is drawn from. */
|
|
405
|
+
function flowLines(flow, depth = 1) {
|
|
406
|
+
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
407
|
+
const out = [];
|
|
408
|
+
const pad = (d) => ' '.repeat(d);
|
|
409
|
+
const at = (n) => (n.line ? ` (line ${n.line})` : '');
|
|
410
|
+
const say = (n) => (n.kind === 'code' ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' ? `Ask: ${n.text}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
|
|
411
|
+
const go = (blocks, d) => {
|
|
412
|
+
for (const b of blocks || []) {
|
|
413
|
+
const n = byId.get(b.id);
|
|
414
|
+
out.push(`${pad(d)}- ${say(n)}${at(n)}`);
|
|
415
|
+
if (n.kind === 'decision') {
|
|
416
|
+
for (const side of ['yes', 'no']) {
|
|
417
|
+
if (!(side in b)) continue;
|
|
418
|
+
if (b[side].length) { out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}:`); go(b[side], d + 2); }
|
|
419
|
+
else out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}: continue`);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (b.each) { out.push(`${pad(d + 1)}For each:`); go(b.each, d + 2); }
|
|
423
|
+
if (b.body) go(b.body, d + 1);
|
|
424
|
+
for (const h of b.handlers || []) { out.push(`${pad(d + 1)}${byId.get(h.id).text.replace(/\?$/, '')}:`); go(h.blocks, d + 2); }
|
|
425
|
+
if (b.always) { out.push(`${pad(d + 1)}Always, at the end:`); go(b.always.blocks, d + 2); }
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
go(flow.blocks, depth);
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Thunder Text for a Thing or a member, made from the same model nodes the picture is drawn from, so the two
|
|
434
|
+
* cannot disagree. Pass the model and an id.
|
|
435
|
+
*/
|
|
436
|
+
export function modelText(model, id) {
|
|
437
|
+
const t = model.things.find((x) => x.id === id);
|
|
438
|
+
if (t) {
|
|
439
|
+
const lines = [`${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
|
|
440
|
+
if (t.doc) lines.push(` Author's note: ${t.doc}`);
|
|
441
|
+
if (t.choices.length) lines.push(` One of: ${t.choices.join(', ')}`);
|
|
442
|
+
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'}`); }
|
|
443
|
+
if (t.can.length) { lines.push(' It can'); for (const c of t.can) lines.push(` ${model.members.find((m) => m.id === c)?.label}`); }
|
|
444
|
+
return `${lines.join('\n')}\n`;
|
|
445
|
+
}
|
|
446
|
+
const m = model.members.find((x) => x.id === id);
|
|
447
|
+
if (!m) throw new Error(`Nothing in the model has id ${id}.`);
|
|
448
|
+
const owner = m.owner && model.things.find((x) => x.id === m.owner);
|
|
449
|
+
const lines = [`${m.label}${owner && m.kind !== 'setup' ? ` (${owner.label})` : ''}${m.kind === 'rule' ? ': a rule' : ''}`];
|
|
450
|
+
if (m.route) lines.push(` When someone calls ${m.route}`);
|
|
451
|
+
if (m.doc) lines.push(` Author's note: ${m.doc}`);
|
|
452
|
+
if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(', ')}`);
|
|
453
|
+
if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
|
|
454
|
+
lines.push(...flowLines(m.flow));
|
|
455
|
+
return `${lines.join('\n')}\n`;
|
|
456
|
+
}
|
package/src/read.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type ReadKind = 'decision' | 'function' | 'error' | 'test';
|
|
2
|
-
export interface ReadInput { name: string; type: string | null }
|
|
2
|
+
export interface ReadInput { name: string; type: string | null; /** Framework plumbing (db, request, ctx): not something a person gives. */ plumbing?: true }
|
|
3
3
|
export interface ReadRule { when: string; result: string; line: number; says: string }
|
|
4
4
|
export interface ReadUnread { line: number; text: string; reason: string }
|
|
5
5
|
export interface ReadGuard {
|
|
@@ -13,6 +13,30 @@ export interface ReadItem {
|
|
|
13
13
|
rules?: ReadRule[]; otherwise?: { result: string; line: number } | null;
|
|
14
14
|
thunder?: string; unread?: ReadUnread[]; guards?: ReadGuard[];
|
|
15
15
|
route?: { method: string; path: string };
|
|
16
|
+
/** A display name: "Late fee". */
|
|
17
|
+
label?: string;
|
|
18
|
+
/** For functions: what it handles or takes, without notes (unlike `says`). */
|
|
19
|
+
headline?: string;
|
|
20
|
+
/** Why no rules are drawn, kept apart from `says`. */
|
|
21
|
+
note?: string;
|
|
22
|
+
/** How completely Thunder explains it, and why. */
|
|
23
|
+
completeness?: { level: 'explained' | 'partly explained' | 'found' | 'executed'; reasons: string[] };
|
|
24
|
+
/** The author's own words for what the function means (docstring or doc comment), first paragraph only. Not inferred. */
|
|
25
|
+
doc?: string;
|
|
26
|
+
steps?: ReadStep[]; stepsMore?: number;
|
|
27
|
+
/** Share of steps that explain the code: not `other` and not `restates`. */
|
|
28
|
+
stepsReadable?: number;
|
|
29
|
+
}
|
|
30
|
+
/** One plain step of a function (thunder-steps-v1). */
|
|
31
|
+
export interface ReadStep {
|
|
32
|
+
kind: 'check' | 'branch' | 'loop' | 'set' | 'call' | 'return' | 'fail' | 'try' | 'other';
|
|
33
|
+
says: string; code: string; line: number; callee?: string; children?: ReadStep[];
|
|
34
|
+
/** On a fail step: the error's name and its message, apart from `says`. */
|
|
35
|
+
error?: string; message?: string;
|
|
36
|
+
/** The other side of an If; error handlers; what always runs at the end. */
|
|
37
|
+
otherwise?: ReadStep[]; handlers?: { says: string; line: number; steps: ReadStep[] }[]; always?: { line: number; steps: ReadStep[] };
|
|
38
|
+
/** The wording only restates the code's syntax ("Works out actives"); show the code, do not count it as read. */
|
|
39
|
+
restates?: true;
|
|
16
40
|
}
|
|
17
41
|
export interface Reading {
|
|
18
42
|
schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
|