@skillstech/thunderlang 0.5.9 → 0.5.11
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 +68 -0
- package/dist/core.cjs +1597 -156
- package/dist/index.cjs +1079 -113
- package/dist/learn.cjs +1549 -133
- package/package.json +1 -1
- package/src/core.d.ts +1 -1
- package/src/core.mjs +1 -1
- package/src/emit.mjs +1 -1
- package/src/lift.mjs +1 -0
- package/src/model.d.mts +7 -3
- package/src/model.mjs +82 -24
- package/src/read-repo.d.mts +7 -0
- package/src/read-repo.mjs +21 -0
- package/src/read.mjs +31 -8
- package/src/same.mjs +2 -2
- package/src/sql.mjs +387 -0
- package/src/steps.mjs +500 -22
- package/src/things-langs.mjs +352 -0
- package/src/thunderize.mjs +3 -4
- package/src/visual.mjs +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstech/thunderlang",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.11",
|
|
4
4
|
"description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
package/src/core.d.ts
CHANGED
|
@@ -126,7 +126,7 @@ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES }
|
|
|
126
126
|
export type { Reading, ReadItem, ReadKind } from './read.mjs';
|
|
127
127
|
export function completenessOf(item: unknown): { level: 'explained' | 'partly explained' | 'found' | 'executed'; reasons: string[] };
|
|
128
128
|
export function displayLabel(name: string): string;
|
|
129
|
-
export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
|
|
129
|
+
export { readRepo, searchRepo, groupByFile, readableLanguage, readFiles, readingOf, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
|
|
130
130
|
export type { RepoItem, RepoFacet, RepoReading, RepoFilter } from './read-repo.mjs';
|
|
131
131
|
export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
|
|
132
132
|
export type { Promotion } from './promote.mjs';
|
package/src/core.mjs
CHANGED
|
@@ -111,5 +111,5 @@ export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
|
|
|
111
111
|
// Read code you don't know: decisions recovered from six languages as ThunderLang + plain English.
|
|
112
112
|
export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES, completenessOf, displayLabel } from './read.mjs';
|
|
113
113
|
// Read a whole repository (pure: the caller passes file contents) and turn a recovered decision into a contract.
|
|
114
|
-
export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
|
|
114
|
+
export { readRepo, searchRepo, groupByFile, readableLanguage, readFiles, readingOf, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
|
|
115
115
|
export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
|
package/src/emit.mjs
CHANGED
|
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
export const COMPILER_VERSION = '0.5.
|
|
33
|
+
export const COMPILER_VERSION = '0.5.11';
|
|
34
34
|
export const PROOF_SCHEMA_VERSION = '0.1.0';
|
|
35
35
|
// Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
|
|
36
36
|
// Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
|
package/src/lift.mjs
CHANGED
|
@@ -628,6 +628,7 @@ function liftDiagnostics(lift, facts) {
|
|
|
628
628
|
* repo-level summary matching the `thunder lift --from repo --json` contract.
|
|
629
629
|
*/
|
|
630
630
|
export function languageForFile(file) {
|
|
631
|
+
if (/\.sql$/i.test(file)) return 'sql';
|
|
631
632
|
if (/\.rs$/i.test(file)) return 'rust';
|
|
632
633
|
if (/\.(pl|pm|t)$/i.test(file)) return 'perl';
|
|
633
634
|
if (/\.pyi?$/i.test(file)) return 'python';
|
package/src/model.d.mts
CHANGED
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
import type { Does } from './visual.mjs';
|
|
3
3
|
export const MODEL_SCHEMA: 'thunder-model-v1';
|
|
4
4
|
export const THING_LANGUAGES: string[];
|
|
5
|
-
export interface FlowNode { id: string; kind: 'start' | 'decision' | 'step' | 'loop' | 'stop' | 'end' | 'code'; text: string; line?: number; lane: number; row: number; does: Does; uses?: string; answer?: boolean; otherwise?: boolean; value?: string; code?: boolean }
|
|
6
|
-
export interface FlowEdge { from: string; to: string; label?: 'yes' | 'no' | 'each' | 'next' | 'done' | 'error' }
|
|
7
|
-
export interface FlowBlock { id: string; yes?: FlowBlock[]; no?: FlowBlock[]; each?: FlowBlock[]; body?: FlowBlock[];
|
|
5
|
+
export interface FlowNode { id: string; kind: 'start' | 'decision' | 'step' | 'loop' | 'stop' | 'end' | 'code'; text: string; line?: number; lane: number; row: number; does: Does; uses?: string; answer?: boolean; otherwise?: boolean; value?: string; code?: boolean; /** A decision with several cases (see FlowBlock.cases). */ cases?: true }
|
|
6
|
+
export interface FlowEdge { from: string; to: string; label?: 'yes' | 'no' | 'each' | 'next' | 'done' | 'error' | 'case' | 'nested'; /** On a 'case' edge: the case it takes ("When it is from 90 to 100", "Otherwise", "None of these"). */ text?: string }
|
|
7
|
+
export interface FlowBlock { id: string; yes?: FlowBlock[]; no?: FlowBlock[]; each?: FlowBlock[]; body?: FlowBlock[];
|
|
8
|
+
/** A choice among several cases (switch, when, match, select): one side per case, in order. The decision node has `cases: true`. */
|
|
9
|
+
cases?: { label: string; line?: number; blocks: FlowBlock[] }[];
|
|
10
|
+
/** The body is an inner function (a hook, a callback, go/defer): its own sub-flow; the outer flow continues from this step. */
|
|
11
|
+
nested?: true; handlers?: { id: string; blocks: FlowBlock[] }[]; always?: { id: string; blocks: FlowBlock[] } }
|
|
8
12
|
/** nodes/edges: the flow as a graph. blocks: the same nodes as a tree, which views draw from. */
|
|
9
13
|
export interface Flow { nodes: FlowNode[]; edges: FlowEdge[]; blocks: FlowBlock[] }
|
|
10
14
|
export interface Thing { id: string; kind: 'thing' | 'record' | 'choices'; name: string; label: string; doc?: string; file: string; lines: [number, number]; knows: { name: string; label: string; kind: string | null; start: string | null; line: number | null }[]; choices: string[]; can: string[] }
|
package/src/model.mjs
CHANGED
|
@@ -3,13 +3,15 @@
|
|
|
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
5
|
import { readCode } from './read.mjs';
|
|
6
|
-
import { readableLanguage } from './read-repo.mjs';
|
|
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
|
+
import { makeThingReaders } from './things-langs.mjs';
|
|
10
|
+
import { sqlThings } from './sql.mjs';
|
|
9
11
|
|
|
10
12
|
export const MODEL_SCHEMA = 'thunder-model-v1';
|
|
11
13
|
/** Languages whose classes, records, and choices are read today. Others still get every function. */
|
|
12
|
-
export const THING_LANGUAGES = ['python', 'typescript', 'javascript'];
|
|
14
|
+
export const THING_LANGUAGES = ['python', 'typescript', 'javascript', 'java', 'csharp', 'kotlin', 'php', 'go', 'rust', 'ruby', 'sql'];
|
|
13
15
|
|
|
14
16
|
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
15
17
|
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
@@ -20,35 +22,39 @@ function startValue(expr, params = {}) {
|
|
|
20
22
|
const e = String(expr ?? '').trim();
|
|
21
23
|
if (!e) return null;
|
|
22
24
|
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
|
|
24
|
-
if (/^(None|null|undefined)$/.test(e)) return 'nothing at first';
|
|
25
|
+
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 (/^(None|null|undefined|nil|NULL|Option::None)$/.test(e)) return 'nothing at first';
|
|
25
27
|
if (/^(True|true)$/.test(e)) return 'yes at first';
|
|
26
28
|
if (/^(False|false)$/.test(e)) return 'no at first';
|
|
27
29
|
if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
|
|
28
30
|
if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
|
|
29
|
-
const en = e.match(/^[A-Z]\w
|
|
31
|
+
const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/);
|
|
30
32
|
if (en) return `${words(en[1])} at first`;
|
|
31
33
|
return 'worked out when it starts';
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
const KIND_WORDS = [
|
|
35
|
-
[/^(int|float|number|double|long|decimal|Decimal|bigint)
|
|
36
|
-
[/^(str|string|String|text)
|
|
37
|
-
[/^(bool|boolean)
|
|
38
|
-
[/^(date|datetime|Date|LocalDate|Instant)
|
|
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'],
|
|
38
|
+
[/^(str|string|String|text|&str|&'static str|char|Char|Character|rune)$/, 'words'],
|
|
39
|
+
[/^(bool|boolean|Boolean|Bool)$/, 'yes or no'],
|
|
40
|
+
[/^(date|datetime|Date|LocalDate|LocalDateTime|Instant|DateTime|DateTimeOffset|ZonedDateTime|time\.Time|NaiveDate|NaiveDateTime|DateTimeImmutable)$/, 'a date'],
|
|
39
41
|
];
|
|
40
42
|
function kindWords(type) {
|
|
41
43
|
const t = String(type ?? '').trim();
|
|
42
44
|
if (!t) return null;
|
|
43
45
|
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)
|
|
46
|
-
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
|
|
47
|
-
if (opt)
|
|
46
|
+
const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^(?:Array|List|ArrayList|LinkedList|Vec|VecDeque|IList|IEnumerable|ICollection|IReadOnlyList|Collection|Set|HashSet|MutableList|MutableSet|Sequence|Iterable)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
|
|
47
|
+
if (list) { const inner = (list[1] || list[2] || list[3] || list[4]).trim(); return `a list of ${kindWords(inner)?.replace(/^an? /, '') ?? inner}s`.replace(/wordss$/, 'words').replace(/ys$/, 'ies').replace(/(yes or no)s$/, '$1 answers'); }
|
|
48
|
+
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
|
|
49
|
+
if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ?? `a ${inner}`}, or nothing`; }
|
|
50
|
+
const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
|
|
51
|
+
if (map) return 'a lookup table';
|
|
48
52
|
return /^[A-Z]/.test(t) ? `a ${t}` : null;
|
|
49
53
|
}
|
|
50
54
|
|
|
51
|
-
|
|
55
|
+
const thingsFor = makeThingReaders({ words: (x) => words(x), kindWords: (x) => kindWords(x), startValue: (x, p) => startValue(x, p) });
|
|
56
|
+
|
|
57
|
+
// ── Things: classes, records, and choices ───────────────────────────────────────────────────────────
|
|
52
58
|
|
|
53
59
|
function pythonThings(src, file) {
|
|
54
60
|
const lines = src.split('\n');
|
|
@@ -247,7 +253,7 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
247
253
|
const nodes = [], edges = [];
|
|
248
254
|
let n = 0;
|
|
249
255
|
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, ...extra }); return id; };
|
|
250
|
-
const connect = (open, to) => { for (const o of open) edges.push({ from: o.id, to, ...(o.label ? { label: o.label } : {}) }); };
|
|
256
|
+
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 } : {}) }); };
|
|
251
257
|
// The first call in the step to another member of this file: self.can_borrow(...), delivery_fee(...), this.lateFee(...).
|
|
252
258
|
const usesOf = (st) => {
|
|
253
259
|
for (const c of String(st.code || '').matchAll(/(?:\b(?:self|this)\.)?\b([A-Za-z_]\w*)\s*\(/g)) {
|
|
@@ -264,6 +270,25 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
264
270
|
for (const st of list) {
|
|
265
271
|
const does = stepDoes(st);
|
|
266
272
|
const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}) };
|
|
273
|
+
// A choice among several cases (switch, when, match, select): one question with one side per case.
|
|
274
|
+
const arms = st.kind === 'branch' && st.children?.length && st.children.every((c) => c.kind === 'check') ? st.children : null;
|
|
275
|
+
if (arms) {
|
|
276
|
+
const d = node('decision', st.says.replace(/\?$/, ''), { ...base, cases: true });
|
|
277
|
+
connect(open, d);
|
|
278
|
+
const cases = [];
|
|
279
|
+
let after = [];
|
|
280
|
+
for (const arm of arms) {
|
|
281
|
+
const label = arm.says;
|
|
282
|
+
const w = walk(arm.children || [], [{ id: d, label: 'case', text: label }], lane + 1);
|
|
283
|
+
cases.push({ label, line: arm.line, blocks: w.blocks });
|
|
284
|
+
after = [...after, ...w.open];
|
|
285
|
+
}
|
|
286
|
+
// With no "Otherwise", a value that matches no case carries straight on.
|
|
287
|
+
if (!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' });
|
|
288
|
+
blocks.push({ id: d, cases });
|
|
289
|
+
open = after;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
267
292
|
if (st.kind === 'branch') {
|
|
268
293
|
const { text, flip } = askAsQuestion(st, base.uses && memberLabel.get(base.uses));
|
|
269
294
|
const [into, past] = flip ? ['no', 'yes'] : ['yes', 'no'];
|
|
@@ -319,7 +344,12 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
319
344
|
const k = node(does === 'code' ? 'code' : 'step', does === 'code' ? st.code ?? st.says : st.says, base);
|
|
320
345
|
connect(open, k);
|
|
321
346
|
open = [{ id: k }];
|
|
322
|
-
if (st.children?.length) {
|
|
347
|
+
if (st.children?.length && st.nested) {
|
|
348
|
+
// An inner function (a hook, a callback, go/defer, a closure) runs on its own: its steps are its own
|
|
349
|
+
// sub-flow, and a return or stop inside it ends only that function. The outer flow carries on from here.
|
|
350
|
+
const inner = walk(st.children, [{ id: k, label: 'nested' }], lane + 1);
|
|
351
|
+
blocks.push({ id: k, body: inner.blocks, nested: true });
|
|
352
|
+
} else if (st.children?.length) {
|
|
323
353
|
const inner = walk(st.children, open, lane + 1);
|
|
324
354
|
blocks.push({ id: k, body: inner.blocks });
|
|
325
355
|
open = inner.open;
|
|
@@ -350,7 +380,10 @@ const idOf = (...parts) => parts.join('#').replace(/\s+/g, '');
|
|
|
350
380
|
* `const { id } = req.params`, `{ email } = await request.json()`.
|
|
351
381
|
*/
|
|
352
382
|
function youGiveOf(item) {
|
|
353
|
-
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing)
|
|
383
|
+
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing)
|
|
384
|
+
// Destructured parameters (React props `{ userId, name }`) give each name.
|
|
385
|
+
.flatMap((p) => (/^\{.*\}$/.test(String(p.name).trim()) ? String(p.name).trim().slice(1, -1).split(',').map((x) => x.split(/[:=]/)[0].trim().replace(/^\.\.\./, '')).filter((x) => /^[A-Za-z_$][\w$]*$/.test(x)) : [p.name]))
|
|
386
|
+
.map((n) => words(n));
|
|
354
387
|
const codes = [];
|
|
355
388
|
const walk = (steps) => { for (const s of steps || []) { if (s.code) codes.push(s.code); walk(s.children); walk(s.otherwise); } };
|
|
356
389
|
walk(item.steps);
|
|
@@ -371,9 +404,9 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
371
404
|
const language = readableLanguage(f.path);
|
|
372
405
|
if (!language || !f.source) continue;
|
|
373
406
|
let reading;
|
|
374
|
-
try { reading =
|
|
407
|
+
try { reading = readingOf(f, language); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); continue; }
|
|
375
408
|
let fileThings = [];
|
|
376
|
-
try { fileThings = language === 'python' ? pythonThings(f.source, f.path) :
|
|
409
|
+
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); }
|
|
377
410
|
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
|
|
378
411
|
if (!THING_LANGUAGES.includes(language) && /\b(class|struct|record|enum|interface|data class)\s+[A-Z]/.test(f.source)) {
|
|
379
412
|
unknowns.push({ file: f.path, line: 1, why: `Classes, records, and choices in ${language} are not drawn as Things yet; their functions are read.` });
|
|
@@ -383,10 +416,11 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
383
416
|
fileInfo.push({ path: f.path, language, ...(moduleDoc ? { purpose: moduleDoc } : {}) });
|
|
384
417
|
|
|
385
418
|
const fns = reading.items.filter((i) => i.kind === 'function' || i.kind === 'decision');
|
|
386
|
-
const
|
|
387
|
-
|
|
419
|
+
const declaredThing = (item) => fileThings.some((t) => t.name === item.name && t.lines[0] === item.line);
|
|
420
|
+
const fileMembers = fns.filter((item) => !declaredThing(item)).map((item) => {
|
|
421
|
+
const owner = fileThings.filter((t) => (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];
|
|
388
422
|
const v = visualFor(item);
|
|
389
|
-
const setup = /^(__init__|constructor|init|New)$/.test(item.name) && owner;
|
|
423
|
+
const setup = (/^(__init__|constructor|init|New|__construct|initialize|new)$/.test(item.name) || (owner && item.name === owner.name)) && owner;
|
|
390
424
|
const kind = setup ? 'setup' : v.element === 'action' ? 'action' : v.element === 'decision' ? 'rule' : v.element === 'not-read' ? 'not-read' : 'steps';
|
|
391
425
|
const bodyEnd = item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
|
|
392
426
|
let rule = null;
|
|
@@ -418,6 +452,15 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
418
452
|
members.push(m);
|
|
419
453
|
}
|
|
420
454
|
}
|
|
455
|
+
for (const t of things) delete t.memberRanges; // only used to find which Thing owns a method
|
|
456
|
+
// An empty class (no facts, nothing it can do) is not a Thing a person needs to see: an error type is already shown
|
|
457
|
+
// where it stops a path, and any other empty class is a named record with no facts.
|
|
458
|
+
const owners = new Set(members.map((x) => x.owner).filter(Boolean));
|
|
459
|
+
for (let i = things.length - 1; i >= 0; i--) {
|
|
460
|
+
const t = things[i];
|
|
461
|
+
if (t.kind !== 'thing' || t.knows.length || owners.has(t.id)) continue;
|
|
462
|
+
if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1); else t.kind = 'record';
|
|
463
|
+
}
|
|
421
464
|
return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
|
|
422
465
|
}
|
|
423
466
|
|
|
@@ -429,7 +472,7 @@ function flowLines(flow, depth = 1) {
|
|
|
429
472
|
const out = [];
|
|
430
473
|
const pad = (d) => ' '.repeat(d);
|
|
431
474
|
const at = (n) => (n.line ? ` (line ${n.line})` : '');
|
|
432
|
-
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);
|
|
475
|
+
const say = (n) => (n.kind === 'code' ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' && n.cases ? n.text : n.kind === 'decision' ? `Ask: ${n.text}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
|
|
433
476
|
const go = (blocks, d) => {
|
|
434
477
|
for (const b of blocks || []) {
|
|
435
478
|
const n = byId.get(b.id);
|
|
@@ -441,6 +484,10 @@ function flowLines(flow, depth = 1) {
|
|
|
441
484
|
else out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}: continue`);
|
|
442
485
|
}
|
|
443
486
|
}
|
|
487
|
+
for (const c of b.cases || []) {
|
|
488
|
+
if (c.blocks.length) { out.push(`${pad(d + 1)}${c.label}:`); go(c.blocks, d + 2); }
|
|
489
|
+
else out.push(`${pad(d + 1)}${c.label}: nothing`);
|
|
490
|
+
}
|
|
444
491
|
if (b.each) { out.push(`${pad(d + 1)}For each:`); go(b.each, d + 2); }
|
|
445
492
|
if (b.body) go(b.body, d + 1);
|
|
446
493
|
for (const h of b.handlers || []) { out.push(`${pad(d + 1)}${byId.get(h.id).text.replace(/\?$/, '')}:`); go(h.blocks, d + 2); }
|
|
@@ -494,6 +541,7 @@ function detailSteps(flow) {
|
|
|
494
541
|
walk(b.yes, depth + 1, 'Yes');
|
|
495
542
|
walk(b.no, depth + 1, 'No');
|
|
496
543
|
walk(b.each, depth + 1, 'For each');
|
|
544
|
+
for (const c of b.cases || []) walk(c.blocks, depth + 1, c.label);
|
|
497
545
|
walk(b.body, depth + 1, null);
|
|
498
546
|
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); }
|
|
499
547
|
if (b.always) { const an = byId.get(b.always.id); if (an) push(an, depth, null); walk(b.always.blocks, depth + 1, null); }
|
|
@@ -512,6 +560,7 @@ const CHANGES = /^(Sets|Adds|Removes|Subtracts|Clears|Marks|Saves|Deletes|Update
|
|
|
512
560
|
function pathsOf(flow) {
|
|
513
561
|
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
514
562
|
const out = [];
|
|
563
|
+
const ends = (blocks) => { const last = byId.get((blocks || []).at(-1)?.id); return !!last && (last.kind === 'stop' || last.kind === 'end'); };
|
|
515
564
|
const walk = (blocks, when) => {
|
|
516
565
|
for (const b of blocks || []) {
|
|
517
566
|
const n = byId.get(b.id);
|
|
@@ -520,9 +569,18 @@ function pathsOf(flow) {
|
|
|
520
569
|
walk(b.yes, [...when, { question: q, answer: 'Yes' }]);
|
|
521
570
|
walk(b.no, [...when, { question: q, answer: 'No' }]);
|
|
522
571
|
walk(b.each, [...when, { question: q, answer: 'For each' }]);
|
|
523
|
-
|
|
572
|
+
for (const c of b.cases || []) walk(c.blocks, [...when, { question: q, answer: c.label }]);
|
|
573
|
+
// An inner function's steps end only that function: not one of this action's endings.
|
|
574
|
+
if (!b.nested) walk(b.body, when);
|
|
524
575
|
for (const h of b.handlers || []) { const hn = byId.get(h.id); walk(h.blocks, [...when, { question: (hn?.text ?? '').replace(/\?$/, ''), answer: 'Yes' }]); }
|
|
525
576
|
if (b.always) walk(b.always.blocks, when);
|
|
577
|
+
// A question whose one side ends the path (a Stop or an answer) guards everything after it: what follows only
|
|
578
|
+
// happens on the other side. "Gives back org" happens when "Is org set?" is Yes, not always.
|
|
579
|
+
if (n?.kind === 'decision' && (b.yes || b.no)) {
|
|
580
|
+
const yesEnds = ends(b.yes), noEnds = ends(b.no);
|
|
581
|
+
if (yesEnds && !noEnds) when = [...when, { question: q, answer: 'No' }];
|
|
582
|
+
else if (noEnds && !yesEnds) when = [...when, { question: q, answer: 'Yes' }];
|
|
583
|
+
}
|
|
526
584
|
}
|
|
527
585
|
};
|
|
528
586
|
walk(flow.blocks, []);
|
package/src/read-repo.d.mts
CHANGED
|
@@ -19,3 +19,10 @@ export function readableLanguage(path: string): string | null;
|
|
|
19
19
|
export function readRepo(files: Array<{ path: string; source: string; size?: number }>, options?: { maxFileBytes?: number; maxFiles?: number }): RepoReading;
|
|
20
20
|
export function searchRepo(index: RepoReading, filter?: RepoFilter): RepoItem[];
|
|
21
21
|
export function groupByFile(items: RepoItem[]): Array<{ file: string; language: string; items: RepoItem[] }>;
|
|
22
|
+
|
|
23
|
+
/** A file, optionally carrying the reading readFiles attached (or the error reading it gave). */
|
|
24
|
+
export interface ReadableFile { path: string; source?: string; size?: number; reading?: import('./read.d.mts').Reading; readError?: string }
|
|
25
|
+
/** Read every file once; thunderModel, thunderizeFiles, and sameMeaning reuse each file's `reading`. */
|
|
26
|
+
export function readFiles<T extends ReadableFile>(files: T[]): (T & { reading?: import('./read.d.mts').Reading; readError?: string })[];
|
|
27
|
+
/** A file's reading: the attached one, or a fresh one. */
|
|
28
|
+
export function readingOf(file: ReadableFile, language?: string): import('./read.d.mts').Reading;
|
package/src/read-repo.mjs
CHANGED
|
@@ -21,6 +21,7 @@ const EXT_LANG = [
|
|
|
21
21
|
[/\.kts?$/i, 'kotlin'],
|
|
22
22
|
[/\.php$/i, 'php'],
|
|
23
23
|
[/\.rb$/i, 'ruby'],
|
|
24
|
+
[/\.sql$/i, 'sql'],
|
|
24
25
|
];
|
|
25
26
|
|
|
26
27
|
/** Folders that hold dependencies, build output, or tooling state rather than the application. */
|
|
@@ -137,3 +138,23 @@ export function groupByFile(items) {
|
|
|
137
138
|
}
|
|
138
139
|
return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
|
|
139
140
|
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Read every file once. Whole-app stages (thunderModel, thunderizeFiles, sameMeaning) reuse `reading` when a file
|
|
144
|
+
* carries one, so a caller running several stages pays for reading only once: `const app = readFiles(files)`, then
|
|
145
|
+
* pass `app` to each. Files Thunder does not read are passed through unchanged.
|
|
146
|
+
*/
|
|
147
|
+
export function readFiles(files) {
|
|
148
|
+
return files.map((f) => {
|
|
149
|
+
const language = readableLanguage(f.path);
|
|
150
|
+
if (!language || !f.source || f.reading) return f;
|
|
151
|
+
try { return { ...f, reading: readCode(f.source, { language, file: f.path }) }; }
|
|
152
|
+
catch (e) { return { ...f, readError: e.message }; }
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A file's reading: the one readFiles attached, or a fresh one. Throws the same error the reader would. */
|
|
157
|
+
export function readingOf(f, language = readableLanguage(f.path)) {
|
|
158
|
+
if (f.readError) throw new Error(f.readError);
|
|
159
|
+
return f.reading ?? readCode(f.source, { language, file: f.path });
|
|
160
|
+
}
|
package/src/read.mjs
CHANGED
|
@@ -9,19 +9,22 @@
|
|
|
9
9
|
// return cond ? X : Y (nested ternaries) Python: return X if cond else Y
|
|
10
10
|
// Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
|
|
11
11
|
// Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
|
|
12
|
+
import { sqlItems } from './sql.mjs';
|
|
12
13
|
import { stepsFrom, braceStatements, indentStatements, plainEnums } from './steps.mjs';
|
|
13
14
|
import { compileExpr, simplifyExpr } from './expr.mjs';
|
|
14
15
|
import { extractFacts, languageForFile } from './lift.mjs';
|
|
15
16
|
|
|
16
17
|
export const READ_SCHEMA = 'thunder-reading-v1';
|
|
17
|
-
export const READ_LANGUAGES = ['typescript', 'javascript', 'python', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php', 'ruby'];
|
|
18
|
+
export const READ_LANGUAGES = ['typescript', 'javascript', 'python', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php', 'ruby', 'sql'];
|
|
18
19
|
const BRACE_LANGS = new Set(['typescript', 'javascript', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php']);
|
|
19
|
-
const KEYWORDS_NOT_FN = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'else', 'using', 'lock', 'foreach', 'match', 'loop', 'sizeof', 'typeof', 'nameof']);
|
|
20
|
+
const KEYWORDS_NOT_FN = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'else', 'using', 'lock', 'synchronized', 'foreach', 'match', 'loop', 'sizeof', 'typeof', 'nameof']);
|
|
20
21
|
|
|
21
22
|
/** Best-effort language guess for pasted code (a file name, when known, is more reliable). */
|
|
22
23
|
export function detectLanguage(source, file = '') {
|
|
23
24
|
if (file) return languageForFile(file);
|
|
24
25
|
const s = String(source);
|
|
26
|
+
// SQL: a file that starts with (or is mostly) schema statements.
|
|
27
|
+
if (/^\s*(?:--[^\n]*\n\s*)*(?:CREATE|ALTER|INSERT\s+INTO|SELECT|WITH)\b/i.test(s) && /\b(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:TABLE|VIEW|FUNCTION|PROCEDURE|TRIGGER|TYPE|INDEX)|SELECT\b[\s\S]*\bFROM)\b/i.test(s)) return 'sql';
|
|
25
28
|
if (/^\s*<\?php\b/.test(s) || /\bfunction\s+\w+\s*\([^)]*\$\w+/.test(s)) return 'php';
|
|
26
29
|
if (/\bfun\s+(<[^>]*>\s*)?[\w.]*\w+\s*\(/.test(s)) return 'kotlin';
|
|
27
30
|
if (/^\s*def\s+[\w.?!]+(\s*\(.*\))?\s*$/m.test(s) && /^\s*end\s*$/m.test(s)) return 'ruby';
|
|
@@ -552,7 +555,7 @@ function kotlinTerminate(body) {
|
|
|
552
555
|
else if (')]}'.includes(c)) depth--;
|
|
553
556
|
else if (c === '\n' && depth === 0) {
|
|
554
557
|
const line = src.slice(src.lastIndexOf('\n', i - 1) + 1, i);
|
|
555
|
-
const next = src.slice(i + 1);
|
|
558
|
+
const next = src.slice(i + 1, i + 400); // only the start of the next line matters
|
|
556
559
|
if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
|
|
557
560
|
out += src.slice(last, i) + ';';
|
|
558
561
|
last = i;
|
|
@@ -1126,9 +1129,11 @@ function splitStatements(body, baseLine) {
|
|
|
1126
1129
|
if (depth === 0 && !blockHeader) { i = close; continue; }
|
|
1127
1130
|
i = close;
|
|
1128
1131
|
if (depth === 0) {
|
|
1129
|
-
// An if/else chain continues past a closing brace
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
+
// An if/else chain continues past a closing brace, and so do `do { … } while (…)` and a Go function
|
|
1133
|
+
// called where it is written (`go func() { … }()`). Only the next few characters matter.
|
|
1134
|
+
const next = src.slice(i + 1, i + 40);
|
|
1135
|
+
const goes = /^\s*else\b/.test(next) || (/^do\b/.test(prefix) && /^\s*while\b/.test(next)) || (/^\(/.test(next) && /^(?:go\s+|defer\s+)?func\s*\(/.test(prefix));
|
|
1136
|
+
if (!goes) { i++; break; }
|
|
1132
1137
|
}
|
|
1133
1138
|
} else if (c === ';' && depth === 0) {
|
|
1134
1139
|
// Go: `if err := open(); err != nil {` and `for i := 0; i < n; i++ {` keep their header together.
|
|
@@ -1143,7 +1148,9 @@ function splitStatements(body, baseLine) {
|
|
|
1143
1148
|
let j = i + 1;
|
|
1144
1149
|
while (j < src.length && (src[j] === ' ' || src[j] === '\t' || src[j] === '\n' || src[j] === '\r')) j++;
|
|
1145
1150
|
const after = src.slice(j, j + 24);
|
|
1146
|
-
|
|
1151
|
+
// A switch label (`case 'a':`, `default:`) is a statement of its own: what follows it is the case's first step.
|
|
1152
|
+
if (/^(?:case\b[^\n]*|default\s*):$/.test(before)) { i++; break; }
|
|
1153
|
+
if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) &&!/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) { i++; break; }
|
|
1147
1154
|
}
|
|
1148
1155
|
}
|
|
1149
1156
|
const raw = src.slice(start, i);
|
|
@@ -1785,9 +1792,11 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
1785
1792
|
export function readCode(source, { language, file = '' } = {}) {
|
|
1786
1793
|
const src = String(source ?? '');
|
|
1787
1794
|
if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
|
|
1788
|
-
const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, 'typescript').replace(/^js$/, 'javascript').replace(/^py$/, 'python').replace(/^(cs|c#)$/, 'csharp').replace(/^rs$/, 'rust').replace(/^golang$/, 'go').replace(/^kts?$/, 'kotlin').replace(/^rb$/, 'ruby');
|
|
1795
|
+
const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, 'typescript').replace(/^js$/, 'javascript').replace(/^py$/, 'python').replace(/^(cs|c#)$/, 'csharp').replace(/^rs$/, 'rust').replace(/^golang$/, 'go').replace(/^kts?$/, 'kotlin').replace(/^rb$/, 'ruby').replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, 'sql');
|
|
1789
1796
|
if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(', ')}. Got "${lang}".`);
|
|
1790
1797
|
READING_RUST = lang === 'rust';
|
|
1798
|
+
// SQL is read by its own reader: tables, rules (CHECK, UNIQUE), views, functions, procedures, triggers.
|
|
1799
|
+
if (lang === 'sql') return sqlReading(src);
|
|
1791
1800
|
// PHP is read after `$name` -> `name` and `->` -> `.`; every line stays on its line.
|
|
1792
1801
|
const code = lang === 'php' ? normalizePhp(src) : src;
|
|
1793
1802
|
const items = [];
|
|
@@ -1877,3 +1886,17 @@ export function searchReading(reading, { query = '', kinds = [], status = [] } =
|
|
|
1877
1886
|
return terms.every((t) => hay.includes(t));
|
|
1878
1887
|
});
|
|
1879
1888
|
}
|
|
1889
|
+
|
|
1890
|
+
/** A reading of a SQL file in the same shape as every other language's. */
|
|
1891
|
+
function sqlReading(src) {
|
|
1892
|
+
const items = sqlItems(src);
|
|
1893
|
+
for (const it of items) it.completeness = completenessOf(it);
|
|
1894
|
+
const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
1895
|
+
return {
|
|
1896
|
+
schema: READ_SCHEMA, language: 'sql', detected: false, items, counts,
|
|
1897
|
+
limitations: [
|
|
1898
|
+
'Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.',
|
|
1899
|
+
'Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps.',
|
|
1900
|
+
],
|
|
1901
|
+
};
|
|
1902
|
+
}
|
package/src/same.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// value either rule mentions), not by comparing text, so a rewritten condition that gives the same answers counts as
|
|
4
4
|
// the same, and a changed limit is caught with a counterexample. Browser-safe: takes [{ path, source }].
|
|
5
5
|
import { readCode } from './read.mjs';
|
|
6
|
-
import { readableLanguage } from './read-repo.mjs';
|
|
6
|
+
import { readableLanguage, readingOf } from './read-repo.mjs';
|
|
7
7
|
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
8
8
|
import { visualFor } from './visual.mjs';
|
|
9
9
|
|
|
@@ -31,7 +31,7 @@ function readAll(files) {
|
|
|
31
31
|
const language = readableLanguage(f.path);
|
|
32
32
|
if (!language || !f.source) continue;
|
|
33
33
|
let reading;
|
|
34
|
-
try { reading =
|
|
34
|
+
try { reading = readingOf(f, language); } catch (e) { unreadable.push({ path: f.path, reason: e.message }); continue; }
|
|
35
35
|
const seen = new Map();
|
|
36
36
|
for (const it of reading.items) {
|
|
37
37
|
if (it.kind !== 'decision' && it.kind !== 'function') continue;
|