@skillstech/thunderlang 0.5.7 → 0.5.8
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 +19 -0
- package/dist/core.cjs +128 -5
- package/dist/index.cjs +21 -4
- package/dist/learn.cjs +42 -4
- package/package.json +1 -1
- package/src/emit.mjs +1 -1
- package/src/model.d.mts +18 -0
- package/src/model.mjs +113 -3
- package/src/read.mjs +3 -1
- package/src/steps.mjs +26 -1
- package/src/visual.mjs +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
# 0.5.8
|
|
2
|
+
|
|
3
|
+
**Language: Details is a fact sheet.** `readLevel(model, 'details', id)` now gives what you need to check before you
|
|
4
|
+
trust or change an action or rule, computed by the compiler: `stops` (every way it can stop, the error, the message
|
|
5
|
+
people see, and the answers that lead there), `givesBack`, `changes` (data it changes, saves, or sends), `inputs`
|
|
6
|
+
(and the lines where each is used), `reliesOn` (each rule or action it uses, summarized), for rules `answers` (in
|
|
7
|
+
words) and `limits` (exact ranges found by running the rule, e.g. 0 or less: No fee, 1 to 7: Small fee, 8 or more:
|
|
8
|
+
Big fee), and `openQuestions` (what the code cannot tell you). The step list stays as `steps`.
|
|
9
|
+
|
|
10
|
+
**Language: web handlers read the way people think about them.**
|
|
11
|
+
- An HTTP error response is a **Stop** with its status and message: Fastify `reply.code(400).send({ error })`,
|
|
12
|
+
Express `res.status(404).json({ message })`, `new Response(..., { status })`, FastAPI `JSONResponse(...,
|
|
13
|
+
status_code=...)`, Flask `return ..., 400` ("Fails with 400 Bad Request: \"slug is required.\"").
|
|
14
|
+
- Facts a handler unpacks from the request (`const { slug, name } = request.body`, `req.params`, `request.json()`)
|
|
15
|
+
are what goes in; framework plumbing (`request`, `reply`, a database session) is not.
|
|
16
|
+
- A one-line `if (x) return reply.code(400).send({ ... })` keeps its return; the object's braces are not a block
|
|
17
|
+
(found by OpenThunder).
|
|
18
|
+
- `if (!slug)` reads "If slug is not set" (asked as "Is slug set?") instead of "If not slug".
|
|
19
|
+
|
|
1
20
|
# 0.5.7
|
|
2
21
|
|
|
3
22
|
**Language: the five reading levels.** Every Thunder view now offers the same five levels, in this order, with
|
package/dist/core.cjs
CHANGED
|
@@ -2188,6 +2188,16 @@ function sayChain(value) {
|
|
|
2188
2188
|
}
|
|
2189
2189
|
return hit ? hit.c.say(words2(src.split(".").pop().replace(/^#/, ""))) : null;
|
|
2190
2190
|
}
|
|
2191
|
+
var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
|
|
2192
|
+
function httpErrorOf(head) {
|
|
2193
|
+
const expr = head.replace(/^return\s+/, "").replace(/^await\s+/, "").replace(/;\s*$/, "").trim();
|
|
2194
|
+
let m = expr.match(/^(?:reply|res|response|resp|ctx\.response)\s*\.\s*(?:code|status|statusCode)\s*\(\s*([45]\d\d)\s*\)/) || expr.match(/^(?:new\s+)?(?:Response|NextResponse(?:\.json)?|HttpResponse|JSONResponse|PlainTextResponse|Response\.json)\s*\(.*\bstatus(?:_code)?\s*[:=]\s*([45]\d\d)\b/) || (/^return\b/.test(head) ? expr.match(/^.+,\s*([45]\d\d)\s*$/) : null);
|
|
2195
|
+
if (!m) return null;
|
|
2196
|
+
const status = Number(m[1]);
|
|
2197
|
+
const name = HTTP_STATUS[status] ?? (status >= 500 ? "Server Error" : "Client Error");
|
|
2198
|
+
const msg = (expr.match(/\b(?:error|message|detail|msg)\s*[:=]\s*["'`]([^"'`]{1,80})["'`]/) || expr.match(/\.(?:send|json|end)\(\s*["'`]([^"'`]{1,80})["'`]/) || [])[1];
|
|
2199
|
+
return { kind: "fail", says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ""}`, error: `${status} ${name}`, ...msg ? { message: msg } : {}, status };
|
|
2200
|
+
}
|
|
2191
2201
|
function classifyStatement(raw, { inner = 0 } = {}) {
|
|
2192
2202
|
const text = String(raw).trim();
|
|
2193
2203
|
const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
|
|
@@ -2212,6 +2222,8 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2212
2222
|
const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
|
|
2213
2223
|
return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
|
|
2214
2224
|
}
|
|
2225
|
+
const httpFail = httpErrorOf(head);
|
|
2226
|
+
if (httpFail) return { ...httpFail, code };
|
|
2215
2227
|
if (m = head.match(/^return\b\s*(.*)$/)) {
|
|
2216
2228
|
const expr = stripTail(m[1]);
|
|
2217
2229
|
if (!expr) return { kind: "return", says: "Stops here", code };
|
|
@@ -2438,7 +2450,11 @@ function stepsFrom(statements) {
|
|
|
2438
2450
|
continue;
|
|
2439
2451
|
}
|
|
2440
2452
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
2441
|
-
if (
|
|
2453
|
+
if (step.inline && !/^\{/.test(step.inline.trim())) {
|
|
2454
|
+
const kid = classifyStatement(step.inline);
|
|
2455
|
+
step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
|
|
2456
|
+
delete step.inline;
|
|
2457
|
+
} else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
|
|
2442
2458
|
const kids2 = stepsFrom(s.children).steps;
|
|
2443
2459
|
if (kids2.length) {
|
|
2444
2460
|
step.children = kids2;
|
|
@@ -3470,7 +3486,7 @@ function notesSummary(ast) {
|
|
|
3470
3486
|
byLens
|
|
3471
3487
|
};
|
|
3472
3488
|
}
|
|
3473
|
-
var COMPILER_VERSION = "0.5.
|
|
3489
|
+
var COMPILER_VERSION = "0.5.8";
|
|
3474
3490
|
var PROOF_SCHEMA_VERSION = "0.1.0";
|
|
3475
3491
|
var SOURCE_PRODUCT = "skillstech-compiler";
|
|
3476
3492
|
function buildContractGraph(ast, generatedAt) {
|
|
@@ -6782,7 +6798,8 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
6782
6798
|
for (const st of r.steps) {
|
|
6783
6799
|
if (st.kind !== "branch" || !st.cond) continue;
|
|
6784
6800
|
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ""));
|
|
6785
|
-
const
|
|
6801
|
+
const bareName = /^(not\s+|!)?(?:self\.|this\.)?\w+$/.test(st.cond.trim()) && /\bis (not )?set\b/.test(st.says);
|
|
6802
|
+
const cond = bareProperty || bareName ? null : toThunderCondition(st.cond, names);
|
|
6786
6803
|
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? "not: " : ""}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, " is not empty").replace(/ is ""/g, " is empty")}${inner || ""}`);
|
|
6787
6804
|
delete st.cond;
|
|
6788
6805
|
delete st.negate;
|
|
@@ -7783,7 +7800,7 @@ var FORMS = [
|
|
|
7783
7800
|
var LEVELS = [
|
|
7784
7801
|
{ id: "big-picture", name: "Big Picture", question: "What is it, and what can it do?", shows: "The Things, what each knows and can do, its doors (actions), its rules, and its data. For one action or rule: what you give it, what you get back, and what it uses.", form: "picture" },
|
|
7785
7802
|
{ id: "flow", name: "Flow", question: "How does it go?", shows: "One action or rule as a path: questions with Yes and No, repeats, the Stops, what happens if something goes wrong, and what always happens at the end.", form: "picture" },
|
|
7786
|
-
{ id: "details", name: "Details", question: "Exactly what happens, and how sure is Thunder?", shows: "
|
|
7803
|
+
{ id: "details", name: "Details", question: "Exactly what happens, and how sure is Thunder?", shows: "A fact sheet: every way it can end (each Stop with its message, and what it gives back), the answers that lead there, what it changes, what goes in, what it relies on, a rule's answers and exact limits, and what the code cannot tell you.", form: "picture" },
|
|
7787
7804
|
{ id: "text", name: "Text", question: "What does it say, in words?", shows: "Thunder Text: the same meaning in structured words, for reading closely, reviewing a change, and keeping a copy.", form: "words" },
|
|
7788
7805
|
{ id: "original", name: "Original", question: "Which code says so?", shows: "The exact lines in the original language that Thunder read. The evidence, one click away.", form: "evidence" }
|
|
7789
7806
|
];
|
|
@@ -8495,6 +8512,27 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
|
|
|
8495
8512
|
return { nodes: nodes2, edges, blocks: blocks2 };
|
|
8496
8513
|
}
|
|
8497
8514
|
var idOf = (...parts) => parts.join("#").replace(/\s+/g, "");
|
|
8515
|
+
function youGiveOf(item2) {
|
|
8516
|
+
const given = (item2.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words5(p.name));
|
|
8517
|
+
const codes = [];
|
|
8518
|
+
const walk = (steps) => {
|
|
8519
|
+
for (const s of steps || []) {
|
|
8520
|
+
if (s.code) codes.push(s.code);
|
|
8521
|
+
walk(s.children);
|
|
8522
|
+
walk(s.otherwise);
|
|
8523
|
+
}
|
|
8524
|
+
};
|
|
8525
|
+
walk(item2.steps);
|
|
8526
|
+
for (const c of codes) {
|
|
8527
|
+
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\(\))/);
|
|
8528
|
+
if (!m) continue;
|
|
8529
|
+
for (const part of m[1].split(",")) {
|
|
8530
|
+
const name = part.split(/[:=]/)[0].replace(/^\.\.\./, "").trim();
|
|
8531
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words5(name))) given.push(words5(name));
|
|
8532
|
+
}
|
|
8533
|
+
}
|
|
8534
|
+
return given;
|
|
8535
|
+
}
|
|
8498
8536
|
function thunderModel(files, { name = "app" } = {}) {
|
|
8499
8537
|
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
8500
8538
|
for (const f of files) {
|
|
@@ -8550,7 +8588,7 @@ function thunderModel(files, { name = "app" } = {}) {
|
|
|
8550
8588
|
lines: [item2.line, bodyEnd2],
|
|
8551
8589
|
...item2.doc ? { doc: item2.doc } : {},
|
|
8552
8590
|
...item2.route ? { route: `${item2.route.method} ${item2.route.path}`.trim() } : {},
|
|
8553
|
-
youGive: (item2
|
|
8591
|
+
youGive: youGiveOf(item2),
|
|
8554
8592
|
...item2.returns && kind !== "rule" ? { youGetBack: kindWords(item2.returns) ?? item2.returns } : {},
|
|
8555
8593
|
...rule ? { rule, question: rule.question } : {},
|
|
8556
8594
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
@@ -8672,6 +8710,89 @@ function detailSteps(flow) {
|
|
|
8672
8710
|
walk(flow.blocks, 0, null);
|
|
8673
8711
|
return out;
|
|
8674
8712
|
}
|
|
8713
|
+
var CHANGES = /^(Sets|Adds|Removes|Subtracts|Clears|Marks|Saves|Deletes|Updates|Appends|Increases|Decreases|Sends|Records|Stores|Writes)\b/;
|
|
8714
|
+
function pathsOf(flow) {
|
|
8715
|
+
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
8716
|
+
const out = [];
|
|
8717
|
+
const walk = (blocks2, when) => {
|
|
8718
|
+
for (const b of blocks2 || []) {
|
|
8719
|
+
const n = byId.get(b.id);
|
|
8720
|
+
if (n && n.kind !== "start") out.push({ node: n, when });
|
|
8721
|
+
const q = n?.text ?? "";
|
|
8722
|
+
walk(b.yes, [...when, { question: q, answer: "Yes" }]);
|
|
8723
|
+
walk(b.no, [...when, { question: q, answer: "No" }]);
|
|
8724
|
+
walk(b.each, [...when, { question: q, answer: "For each" }]);
|
|
8725
|
+
walk(b.body, when);
|
|
8726
|
+
for (const h of b.handlers || []) {
|
|
8727
|
+
const hn = byId.get(h.id);
|
|
8728
|
+
walk(h.blocks, [...when, { question: (hn?.text ?? "").replace(/\?$/, ""), answer: "Yes" }]);
|
|
8729
|
+
}
|
|
8730
|
+
if (b.always) walk(b.always.blocks, when);
|
|
8731
|
+
}
|
|
8732
|
+
};
|
|
8733
|
+
walk(flow.blocks, []);
|
|
8734
|
+
return out;
|
|
8735
|
+
}
|
|
8736
|
+
function ruleAnswers(rule) {
|
|
8737
|
+
const zero = Object.fromEntries(rule.inputs.map((i) => [i.id, i.kind === "yesno" ? true : 0]));
|
|
8738
|
+
let explained;
|
|
8739
|
+
try {
|
|
8740
|
+
explained = explainPlain(rule, zero);
|
|
8741
|
+
} catch {
|
|
8742
|
+
return null;
|
|
8743
|
+
}
|
|
8744
|
+
const answers = explained.rules.map((r) => ({ answer: answerWords(r.outcome), when: r.checks.map((c) => c.text).join(r.join === "any" ? " or " : " and ") }));
|
|
8745
|
+
if (rule.otherwise) answers.push({ answer: answerWords(rule.otherwise), when: "otherwise" });
|
|
8746
|
+
return answers;
|
|
8747
|
+
}
|
|
8748
|
+
function ruleRanges(rule) {
|
|
8749
|
+
if (rule.inputs.length !== 1 || rule.inputs[0].kind === "yesno") return null;
|
|
8750
|
+
const id2 = rule.inputs[0].id;
|
|
8751
|
+
const limits = rule.rules.flatMap((r) => r.conditions).filter((c) => c.input === id2 && typeof c.value === "number").map((c) => c.value);
|
|
8752
|
+
if (!limits.length || !limits.every(Number.isInteger)) return null;
|
|
8753
|
+
const lo = Math.min(...limits) - 1, hi = Math.max(...limits) + 1;
|
|
8754
|
+
const ranges = [];
|
|
8755
|
+
for (let v = lo; v <= hi; v++) {
|
|
8756
|
+
let outcome;
|
|
8757
|
+
try {
|
|
8758
|
+
outcome = answerWords(explainPlain(rule, { [id2]: v }).outcome);
|
|
8759
|
+
} catch {
|
|
8760
|
+
return null;
|
|
8761
|
+
}
|
|
8762
|
+
const last = ranges.at(-1);
|
|
8763
|
+
if (last && last.answer === outcome) last.to = v;
|
|
8764
|
+
else ranges.push({ from: v, to: v, answer: outcome });
|
|
8765
|
+
}
|
|
8766
|
+
ranges[0].from = null;
|
|
8767
|
+
ranges.at(-1).to = null;
|
|
8768
|
+
return { fact: rule.inputs[0].label.replace(/^the /, ""), ranges };
|
|
8769
|
+
}
|
|
8770
|
+
function detailsFacts(model, member) {
|
|
8771
|
+
const paths = pathsOf(member.flow);
|
|
8772
|
+
const memberOf = (id2) => model.members.find((m) => m.id === id2);
|
|
8773
|
+
const inputs = member.youGive.map((label) => {
|
|
8774
|
+
const re = new RegExp(`\\b${label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
|
|
8775
|
+
const lines = [...new Set(paths.filter((p) => re.test(p.node.text) && p.node.line).map((p) => p.node.line))];
|
|
8776
|
+
return { label, lines };
|
|
8777
|
+
});
|
|
8778
|
+
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))).map((p) => ({ text: p.node.text, line: p.node.line ?? null, does: p.node.does, when: p.when }));
|
|
8779
|
+
const stops = paths.filter((p) => p.node.kind === "stop").map((p) => {
|
|
8780
|
+
const m = p.node.text.match(/^Stop:\s*([^:]+?)(?::\s*"(.*)")?$/);
|
|
8781
|
+
return { error: m ? m[1].trim() : p.node.text, ...m?.[2] ? { message: m[2] } : {}, line: p.node.line ?? null, when: p.when };
|
|
8782
|
+
});
|
|
8783
|
+
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 }));
|
|
8784
|
+
const reliesOn = model.links.filter((l) => l.from === member.id).map((l) => memberOf(l.to)).filter(Boolean).map((t) => {
|
|
8785
|
+
const answers2 = t.rule ? ruleAnswers(t.rule) : null;
|
|
8786
|
+
const flowAnswers = [...new Set(t.flow.nodes.filter((n) => n.answer).map((n) => n.text))];
|
|
8787
|
+
const list = answers2 ? answers2.map((a) => a.answer) : flowAnswers;
|
|
8788
|
+
const says = list.length ? `Answers ${list.join(", ").replace(/, ([^,]*)$/, list.length > 2 ? ", or $1" : " or $1")}.` : 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.`;
|
|
8789
|
+
return { id: t.id, label: t.label + (t.yesNo ? "?" : ""), symbol: SYMBOL_OF[t.kind], says };
|
|
8790
|
+
});
|
|
8791
|
+
const answers = member.rule ? ruleAnswers(member.rule) : null;
|
|
8792
|
+
const limits = member.rule ? ruleRanges(member.rule) : null;
|
|
8793
|
+
const openQuestions = (member.rule?.needsReview ?? []).filter((q) => !/^No examples yet/.test(q));
|
|
8794
|
+
return { inputs, changes, stops, givesBack, reliesOn, ...answers ? { answers } : {}, ...limits ? { limits } : {}, openQuestions };
|
|
8795
|
+
}
|
|
8675
8796
|
function readLevel(model, level, focus) {
|
|
8676
8797
|
const lv = LEVELS.find((l) => l.id === level);
|
|
8677
8798
|
if (!lv) throw new Error(`Unknown reading level "${level}". Use one of: ${LEVELS.map((l) => l.id).join(", ")}.`);
|
|
@@ -8725,6 +8846,8 @@ function readLevel(model, level, focus) {
|
|
|
8725
8846
|
...about,
|
|
8726
8847
|
youGive: member.youGive,
|
|
8727
8848
|
...member.youGetBack ? { youGetBack: member.youGetBack } : {},
|
|
8849
|
+
...member.doc ? { doc: member.doc } : {},
|
|
8850
|
+
...detailsFacts(model, member),
|
|
8728
8851
|
steps,
|
|
8729
8852
|
notExplained: steps.filter((s) => s.notExplained).length,
|
|
8730
8853
|
uses,
|
package/dist/index.cjs
CHANGED
|
@@ -2423,7 +2423,7 @@ function notesSummary(ast) {
|
|
|
2423
2423
|
byLens
|
|
2424
2424
|
};
|
|
2425
2425
|
}
|
|
2426
|
-
var COMPILER_VERSION = "0.5.
|
|
2426
|
+
var COMPILER_VERSION = "0.5.8";
|
|
2427
2427
|
var PROOF_SCHEMA_VERSION = "0.1.0";
|
|
2428
2428
|
var SOURCE_PRODUCT = "skillstech-compiler";
|
|
2429
2429
|
function buildContractGraph(ast, generatedAt) {
|
|
@@ -9399,6 +9399,16 @@ function sayChain(value) {
|
|
|
9399
9399
|
}
|
|
9400
9400
|
return hit ? hit.c.say(words2(src.split(".").pop().replace(/^#/, ""))) : null;
|
|
9401
9401
|
}
|
|
9402
|
+
var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
|
|
9403
|
+
function httpErrorOf(head) {
|
|
9404
|
+
const expr = head.replace(/^return\s+/, "").replace(/^await\s+/, "").replace(/;\s*$/, "").trim();
|
|
9405
|
+
let m = expr.match(/^(?:reply|res|response|resp|ctx\.response)\s*\.\s*(?:code|status|statusCode)\s*\(\s*([45]\d\d)\s*\)/) || expr.match(/^(?:new\s+)?(?:Response|NextResponse(?:\.json)?|HttpResponse|JSONResponse|PlainTextResponse|Response\.json)\s*\(.*\bstatus(?:_code)?\s*[:=]\s*([45]\d\d)\b/) || (/^return\b/.test(head) ? expr.match(/^.+,\s*([45]\d\d)\s*$/) : null);
|
|
9406
|
+
if (!m) return null;
|
|
9407
|
+
const status = Number(m[1]);
|
|
9408
|
+
const name = HTTP_STATUS[status] ?? (status >= 500 ? "Server Error" : "Client Error");
|
|
9409
|
+
const msg = (expr.match(/\b(?:error|message|detail|msg)\s*[:=]\s*["'`]([^"'`]{1,80})["'`]/) || expr.match(/\.(?:send|json|end)\(\s*["'`]([^"'`]{1,80})["'`]/) || [])[1];
|
|
9410
|
+
return { kind: "fail", says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ""}`, error: `${status} ${name}`, ...msg ? { message: msg } : {}, status };
|
|
9411
|
+
}
|
|
9402
9412
|
function classifyStatement(raw, { inner = 0 } = {}) {
|
|
9403
9413
|
const text = String(raw).trim();
|
|
9404
9414
|
const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
|
|
@@ -9423,6 +9433,8 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
9423
9433
|
const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
|
|
9424
9434
|
return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
|
|
9425
9435
|
}
|
|
9436
|
+
const httpFail = httpErrorOf(head);
|
|
9437
|
+
if (httpFail) return { ...httpFail, code };
|
|
9426
9438
|
if (m = head.match(/^return\b\s*(.*)$/)) {
|
|
9427
9439
|
const expr = stripTail(m[1]);
|
|
9428
9440
|
if (!expr) return { kind: "return", says: "Stops here", code };
|
|
@@ -9649,7 +9661,11 @@ function stepsFrom(statements) {
|
|
|
9649
9661
|
continue;
|
|
9650
9662
|
}
|
|
9651
9663
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
9652
|
-
if (
|
|
9664
|
+
if (step.inline && !/^\{/.test(step.inline.trim())) {
|
|
9665
|
+
const kid = classifyStatement(step.inline);
|
|
9666
|
+
step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
|
|
9667
|
+
delete step.inline;
|
|
9668
|
+
} else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
|
|
9653
9669
|
const kids2 = stepsFrom(s.children).steps;
|
|
9654
9670
|
if (kids2.length) {
|
|
9655
9671
|
step.children = kids2;
|
|
@@ -11668,7 +11684,8 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
11668
11684
|
for (const st of r.steps) {
|
|
11669
11685
|
if (st.kind !== "branch" || !st.cond) continue;
|
|
11670
11686
|
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ""));
|
|
11671
|
-
const
|
|
11687
|
+
const bareName = /^(not\s+|!)?(?:self\.|this\.)?\w+$/.test(st.cond.trim()) && /\bis (not )?set\b/.test(st.says);
|
|
11688
|
+
const cond = bareProperty || bareName ? null : toThunderCondition(st.cond, names);
|
|
11672
11689
|
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? "not: " : ""}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, " is not empty").replace(/ is ""/g, " is empty")}${inner || ""}`);
|
|
11673
11690
|
delete st.cond;
|
|
11674
11691
|
delete st.negate;
|
|
@@ -13433,7 +13450,7 @@ var FORMS = [
|
|
|
13433
13450
|
var LEVELS2 = [
|
|
13434
13451
|
{ id: "big-picture", name: "Big Picture", question: "What is it, and what can it do?", shows: "The Things, what each knows and can do, its doors (actions), its rules, and its data. For one action or rule: what you give it, what you get back, and what it uses.", form: "picture" },
|
|
13435
13452
|
{ id: "flow", name: "Flow", question: "How does it go?", shows: "One action or rule as a path: questions with Yes and No, repeats, the Stops, what happens if something goes wrong, and what always happens at the end.", form: "picture" },
|
|
13436
|
-
{ id: "details", name: "Details", question: "Exactly what happens, and how sure is Thunder?", shows: "
|
|
13453
|
+
{ id: "details", name: "Details", question: "Exactly what happens, and how sure is Thunder?", shows: "A fact sheet: every way it can end (each Stop with its message, and what it gives back), the answers that lead there, what it changes, what goes in, what it relies on, a rule's answers and exact limits, and what the code cannot tell you.", form: "picture" },
|
|
13437
13454
|
{ id: "text", name: "Text", question: "What does it say, in words?", shows: "Thunder Text: the same meaning in structured words, for reading closely, reviewing a change, and keeping a copy.", form: "words" },
|
|
13438
13455
|
{ id: "original", name: "Original", question: "Which code says so?", shows: "The exact lines in the original language that Thunder read. The evidence, one click away.", form: "evidence" }
|
|
13439
13456
|
];
|
package/dist/learn.cjs
CHANGED
|
@@ -217,6 +217,16 @@ function sayChain(value) {
|
|
|
217
217
|
}
|
|
218
218
|
return hit ? hit.c.say(words(src.split(".").pop().replace(/^#/, ""))) : null;
|
|
219
219
|
}
|
|
220
|
+
var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
|
|
221
|
+
function httpErrorOf(head) {
|
|
222
|
+
const expr = head.replace(/^return\s+/, "").replace(/^await\s+/, "").replace(/;\s*$/, "").trim();
|
|
223
|
+
let m = expr.match(/^(?:reply|res|response|resp|ctx\.response)\s*\.\s*(?:code|status|statusCode)\s*\(\s*([45]\d\d)\s*\)/) || expr.match(/^(?:new\s+)?(?:Response|NextResponse(?:\.json)?|HttpResponse|JSONResponse|PlainTextResponse|Response\.json)\s*\(.*\bstatus(?:_code)?\s*[:=]\s*([45]\d\d)\b/) || (/^return\b/.test(head) ? expr.match(/^.+,\s*([45]\d\d)\s*$/) : null);
|
|
224
|
+
if (!m) return null;
|
|
225
|
+
const status = Number(m[1]);
|
|
226
|
+
const name = HTTP_STATUS[status] ?? (status >= 500 ? "Server Error" : "Client Error");
|
|
227
|
+
const msg = (expr.match(/\b(?:error|message|detail|msg)\s*[:=]\s*["'`]([^"'`]{1,80})["'`]/) || expr.match(/\.(?:send|json|end)\(\s*["'`]([^"'`]{1,80})["'`]/) || [])[1];
|
|
228
|
+
return { kind: "fail", says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ""}`, error: `${status} ${name}`, ...msg ? { message: msg } : {}, status };
|
|
229
|
+
}
|
|
220
230
|
function classifyStatement(raw, { inner = 0 } = {}) {
|
|
221
231
|
const text = String(raw).trim();
|
|
222
232
|
const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
|
|
@@ -241,6 +251,8 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
241
251
|
const said = name && /^[a-z]/.test(name) ? `the error made by ${words(name)}` : name;
|
|
242
252
|
return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
|
|
243
253
|
}
|
|
254
|
+
const httpFail = httpErrorOf(head);
|
|
255
|
+
if (httpFail) return { ...httpFail, code };
|
|
244
256
|
if (m = head.match(/^return\b\s*(.*)$/)) {
|
|
245
257
|
const expr = stripTail(m[1]);
|
|
246
258
|
if (!expr) return { kind: "return", says: "Stops here", code };
|
|
@@ -467,7 +479,11 @@ function stepsFrom(statements) {
|
|
|
467
479
|
continue;
|
|
468
480
|
}
|
|
469
481
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
470
|
-
if (
|
|
482
|
+
if (step.inline && !/^\{/.test(step.inline.trim())) {
|
|
483
|
+
const kid = classifyStatement(step.inline);
|
|
484
|
+
step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
|
|
485
|
+
delete step.inline;
|
|
486
|
+
} else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
|
|
471
487
|
const kids2 = stepsFrom(s.children).steps;
|
|
472
488
|
if (kids2.length) {
|
|
473
489
|
step.children = kids2;
|
|
@@ -1921,7 +1937,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
|
|
|
1921
1937
|
var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
|
|
1922
1938
|
|
|
1923
1939
|
// src/emit.mjs
|
|
1924
|
-
var COMPILER_VERSION = "0.5.
|
|
1940
|
+
var COMPILER_VERSION = "0.5.8";
|
|
1925
1941
|
|
|
1926
1942
|
// src/lift.mjs
|
|
1927
1943
|
var IR_SCHEMA_VERSION = "0.1.0";
|
|
@@ -4401,7 +4417,8 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
4401
4417
|
for (const st of r.steps) {
|
|
4402
4418
|
if (st.kind !== "branch" || !st.cond) continue;
|
|
4403
4419
|
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ""));
|
|
4404
|
-
const
|
|
4420
|
+
const bareName = /^(not\s+|!)?(?:self\.|this\.)?\w+$/.test(st.cond.trim()) && /\bis (not )?set\b/.test(st.says);
|
|
4421
|
+
const cond = bareProperty || bareName ? null : toThunderCondition(st.cond, names);
|
|
4405
4422
|
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? "not: " : ""}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, " is not empty").replace(/ is ""/g, " is empty")}${inner || ""}`);
|
|
4406
4423
|
delete st.cond;
|
|
4407
4424
|
delete st.negate;
|
|
@@ -5195,6 +5212,27 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
|
|
|
5195
5212
|
return { nodes, edges, blocks };
|
|
5196
5213
|
}
|
|
5197
5214
|
var idOf = (...parts) => parts.join("#").replace(/\s+/g, "");
|
|
5215
|
+
function youGiveOf(item) {
|
|
5216
|
+
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words3(p.name));
|
|
5217
|
+
const codes = [];
|
|
5218
|
+
const walk = (steps) => {
|
|
5219
|
+
for (const s of steps || []) {
|
|
5220
|
+
if (s.code) codes.push(s.code);
|
|
5221
|
+
walk(s.children);
|
|
5222
|
+
walk(s.otherwise);
|
|
5223
|
+
}
|
|
5224
|
+
};
|
|
5225
|
+
walk(item.steps);
|
|
5226
|
+
for (const c of codes) {
|
|
5227
|
+
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\(\))/);
|
|
5228
|
+
if (!m) continue;
|
|
5229
|
+
for (const part of m[1].split(",")) {
|
|
5230
|
+
const name = part.split(/[:=]/)[0].replace(/^\.\.\./, "").trim();
|
|
5231
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words3(name))) given.push(words3(name));
|
|
5232
|
+
}
|
|
5233
|
+
}
|
|
5234
|
+
return given;
|
|
5235
|
+
}
|
|
5198
5236
|
function thunderModel(files, { name = "app" } = {}) {
|
|
5199
5237
|
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
5200
5238
|
for (const f of files) {
|
|
@@ -5250,7 +5288,7 @@ function thunderModel(files, { name = "app" } = {}) {
|
|
|
5250
5288
|
lines: [item.line, bodyEnd],
|
|
5251
5289
|
...item.doc ? { doc: item.doc } : {},
|
|
5252
5290
|
...item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {},
|
|
5253
|
-
youGive: (item
|
|
5291
|
+
youGive: youGiveOf(item),
|
|
5254
5292
|
...item.returns && kind !== "rule" ? { youGetBack: kindWords(item.returns) ?? item.returns } : {},
|
|
5255
5293
|
...rule ? { rule, question: rule.question } : {},
|
|
5256
5294
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstech/thunderlang",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.8",
|
|
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/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.8';
|
|
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/model.d.mts
CHANGED
|
@@ -16,6 +16,8 @@ export function ruleFlow(item: unknown, start: string): Flow;
|
|
|
16
16
|
export function askAsQuestion(step: { says: string; code?: string }, ruleLabel?: string): { text: string; flip: boolean };
|
|
17
17
|
export function stepDoes(step: unknown): Does;
|
|
18
18
|
export function modelText(model: ThunderModel, id: string): string;
|
|
19
|
+
/** One answer on the way to a step: the question, and Yes, No, For each, or Otherwise. */
|
|
20
|
+
export interface When { question: string; answer: string }
|
|
19
21
|
export type LevelId = 'big-picture' | 'flow' | 'details' | 'text' | 'original';
|
|
20
22
|
export interface LevelItem { id: string; label: string; symbol: string; route?: string }
|
|
21
23
|
export interface LevelView {
|
|
@@ -34,6 +36,22 @@ export interface LevelView {
|
|
|
34
36
|
// Details
|
|
35
37
|
steps?: { id: string; text: string; does: Does; mark: string; line: number | null; depth: number; via?: string; notExplained?: true }[];
|
|
36
38
|
notExplained?: number; tryable?: boolean; rule?: unknown; source?: string;
|
|
39
|
+
/** Details: what goes in, and the lines where each fact is used. */
|
|
40
|
+
inputs?: { label: string; lines: number[] }[];
|
|
41
|
+
/** Details: the data it changes, what it saves or sends, and the answers that lead there. */
|
|
42
|
+
changes?: { text: string; line: number | null; does: Does; when: When[] }[];
|
|
43
|
+
/** Details: every way it can stop, with the error, the message people see, and the answers that lead there. */
|
|
44
|
+
stops?: { error: string; message?: string; line: number | null; when: When[] }[];
|
|
45
|
+
/** Details: what it gives back, and when. */
|
|
46
|
+
givesBack?: { text: string; line: number | null; when: When[] }[];
|
|
47
|
+
/** Details: each action or rule it relies on, summarized. */
|
|
48
|
+
reliesOn?: { id: string; label: string; symbol: string; says: string }[];
|
|
49
|
+
/** Details, for a rule: its answers in words, in order (the last may be "otherwise"). */
|
|
50
|
+
answers?: { answer: string; when: string }[];
|
|
51
|
+
/** Details, for a rule with one whole-number fact: its exact limits, found by running it. from/to null = "or less"/"or more". */
|
|
52
|
+
limits?: { fact: string; ranges: { from: number | null; to: number | null; answer: string }[] };
|
|
53
|
+
/** Details: questions the code can't answer (what a number means, why the rule exists). */
|
|
54
|
+
openQuestions?: string[];
|
|
37
55
|
// Text
|
|
38
56
|
text?: string;
|
|
39
57
|
// Original
|
package/src/model.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// them may say more than the model does. Browser-safe: takes [{ path, source }].
|
|
5
5
|
import { readCode } from './read.mjs';
|
|
6
6
|
import { readableLanguage } from './read-repo.mjs';
|
|
7
|
-
import { plainFromReading } from './plain-contract.mjs';
|
|
7
|
+
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
8
8
|
import { visualFor, LEVELS, DOES } from './visual.mjs';
|
|
9
9
|
|
|
10
10
|
export const MODEL_SCHEMA = 'thunder-model-v1';
|
|
@@ -343,6 +343,27 @@ const idOf = (...parts) => parts.join('#').replace(/\s+/g, '');
|
|
|
343
343
|
* Read files into the one Thunder model. Things come from classes in THING_LANGUAGES; every function in every
|
|
344
344
|
* readable language becomes a member with its flow. Unknowns list what could not be read, so no view hides a gap.
|
|
345
345
|
*/
|
|
346
|
+
/**
|
|
347
|
+
* What a person gives an action or function: its inputs, without framework plumbing (self, the request, a database
|
|
348
|
+
* session), plus the facts a handler unpacks from the request: `const { slug, name } = request.body`,
|
|
349
|
+
* `const { id } = req.params`, `{ email } = await request.json()`.
|
|
350
|
+
*/
|
|
351
|
+
function youGiveOf(item) {
|
|
352
|
+
const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words(p.name));
|
|
353
|
+
const codes = [];
|
|
354
|
+
const walk = (steps) => { for (const s of steps || []) { if (s.code) codes.push(s.code); walk(s.children); walk(s.otherwise); } };
|
|
355
|
+
walk(item.steps);
|
|
356
|
+
for (const c of codes) {
|
|
357
|
+
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\(\))/);
|
|
358
|
+
if (!m) continue;
|
|
359
|
+
for (const part of m[1].split(',')) {
|
|
360
|
+
const name = part.split(/[:=]/)[0].replace(/^\.\.\./, '').trim();
|
|
361
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words(name))) given.push(words(name));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return given;
|
|
365
|
+
}
|
|
366
|
+
|
|
346
367
|
export function thunderModel(files, { name = 'app' } = {}) {
|
|
347
368
|
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
348
369
|
for (const f of files) {
|
|
@@ -374,7 +395,7 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
374
395
|
label: setup ? `A new ${owner.label} starts with` : cap(words(item.name.replace(/^__|__$/g, ''))),
|
|
375
396
|
...(owner ? { owner: owner.id } : {}), file: f.path, language, lines: [item.line, bodyEnd],
|
|
376
397
|
...(item.doc ? { doc: item.doc } : {}), ...(item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {}),
|
|
377
|
-
youGive: (item
|
|
398
|
+
youGive: youGiveOf(item),
|
|
378
399
|
...(item.returns && kind !== 'rule' ? { youGetBack: kindWords(item.returns) ?? item.returns } : {}),
|
|
379
400
|
...(rule ? { rule, question: rule.question } : {}),
|
|
380
401
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
@@ -481,6 +502,94 @@ function detailSteps(flow) {
|
|
|
481
502
|
return out;
|
|
482
503
|
}
|
|
483
504
|
|
|
505
|
+
|
|
506
|
+
// ── Details: what you need to check before you trust or change an action or rule ─────────────────────────
|
|
507
|
+
|
|
508
|
+
const CHANGES = /^(Sets|Adds|Removes|Subtracts|Clears|Marks|Saves|Deletes|Updates|Appends|Increases|Decreases|Sends|Records|Stores|Writes)\b/;
|
|
509
|
+
|
|
510
|
+
/** Each step with the answers that lead to it: [{ question, answer }] from the top of the flow. */
|
|
511
|
+
function pathsOf(flow) {
|
|
512
|
+
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
513
|
+
const out = [];
|
|
514
|
+
const walk = (blocks, when) => {
|
|
515
|
+
for (const b of blocks || []) {
|
|
516
|
+
const n = byId.get(b.id);
|
|
517
|
+
if (n && n.kind !== 'start') out.push({ node: n, when });
|
|
518
|
+
const q = n?.text ?? '';
|
|
519
|
+
walk(b.yes, [...when, { question: q, answer: 'Yes' }]);
|
|
520
|
+
walk(b.no, [...when, { question: q, answer: 'No' }]);
|
|
521
|
+
walk(b.each, [...when, { question: q, answer: 'For each' }]);
|
|
522
|
+
walk(b.body, when);
|
|
523
|
+
for (const h of b.handlers || []) { const hn = byId.get(h.id); walk(h.blocks, [...when, { question: (hn?.text ?? '').replace(/\?$/, ''), answer: 'Yes' }]); }
|
|
524
|
+
if (b.always) walk(b.always.blocks, when);
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
walk(flow.blocks, []);
|
|
528
|
+
return out;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** A rule's answers in words: [{ answer, when }] in order, then the otherwise answer. */
|
|
532
|
+
function ruleAnswers(rule) {
|
|
533
|
+
const zero = Object.fromEntries(rule.inputs.map((i) => [i.id, i.kind === 'yesno' ? true : 0]));
|
|
534
|
+
let explained;
|
|
535
|
+
try { explained = explainPlain(rule, zero); } catch { return null; }
|
|
536
|
+
const answers = explained.rules.map((r) => ({ answer: answerWords(r.outcome), when: r.checks.map((c) => c.text).join(r.join === 'any' ? ' or ' : ' and ') }));
|
|
537
|
+
if (rule.otherwise) answers.push({ answer: answerWords(rule.otherwise), when: 'otherwise' });
|
|
538
|
+
return answers;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* The exact limits of a rule with one number fact, found by running it on every whole number around each limit:
|
|
543
|
+
* [{ from, to, answer }] where from/to are null for "or less" / "or more". Only when every limit is a whole number,
|
|
544
|
+
* so the ranges are exact rather than approximate.
|
|
545
|
+
*/
|
|
546
|
+
function ruleRanges(rule) {
|
|
547
|
+
if (rule.inputs.length !== 1 || rule.inputs[0].kind === 'yesno') return null;
|
|
548
|
+
const id = rule.inputs[0].id;
|
|
549
|
+
const limits = rule.rules.flatMap((r) => r.conditions).filter((c) => c.input === id && typeof c.value === 'number').map((c) => c.value);
|
|
550
|
+
if (!limits.length || !limits.every(Number.isInteger)) return null;
|
|
551
|
+
const lo = Math.min(...limits) - 1, hi = Math.max(...limits) + 1;
|
|
552
|
+
const ranges = [];
|
|
553
|
+
for (let v = lo; v <= hi; v++) {
|
|
554
|
+
let outcome;
|
|
555
|
+
try { outcome = answerWords(explainPlain(rule, { [id]: v }).outcome); } catch { return null; }
|
|
556
|
+
const last = ranges.at(-1);
|
|
557
|
+
if (last && last.answer === outcome) last.to = v; else ranges.push({ from: v, to: v, answer: outcome });
|
|
558
|
+
}
|
|
559
|
+
ranges[0].from = null;
|
|
560
|
+
ranges.at(-1).to = null;
|
|
561
|
+
return { fact: rule.inputs[0].label.replace(/^the /, ''), ranges };
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function detailsFacts(model, member) {
|
|
565
|
+
const paths = pathsOf(member.flow);
|
|
566
|
+
const memberOf = (id) => model.members.find((m) => m.id === id);
|
|
567
|
+
const inputs = member.youGive.map((label) => {
|
|
568
|
+
const re = new RegExp(`\\b${label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
|
|
569
|
+
const lines = [...new Set(paths.filter((p) => re.test(p.node.text) && p.node.line).map((p) => p.node.line))];
|
|
570
|
+
return { label, lines };
|
|
571
|
+
});
|
|
572
|
+
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))))
|
|
573
|
+
.map((p) => ({ text: p.node.text, line: p.node.line ?? null, does: p.node.does, when: p.when }));
|
|
574
|
+
const stops = paths.filter((p) => p.node.kind === 'stop').map((p) => {
|
|
575
|
+
const m = p.node.text.match(/^Stop:\s*([^:]+?)(?::\s*"(.*)")?$/);
|
|
576
|
+
return { error: m ? m[1].trim() : p.node.text, ...(m?.[2] ? { message: m[2] } : {}), line: p.node.line ?? null, when: p.when };
|
|
577
|
+
});
|
|
578
|
+
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 }));
|
|
579
|
+
const reliesOn = model.links.filter((l) => l.from === member.id).map((l) => memberOf(l.to)).filter(Boolean).map((t) => {
|
|
580
|
+
const answers = t.rule ? ruleAnswers(t.rule) : null;
|
|
581
|
+
const flowAnswers = [...new Set(t.flow.nodes.filter((n) => n.answer).map((n) => n.text))];
|
|
582
|
+
const list = answers ? answers.map((a) => a.answer) : flowAnswers;
|
|
583
|
+
const says = list.length ? `Answers ${list.join(', ').replace(/, ([^,]*)$/, list.length > 2 ? ', or $1' : ' or $1')}.`
|
|
584
|
+
: 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.`;
|
|
585
|
+
return { id: t.id, label: t.label + (t.yesNo ? '?' : ''), symbol: SYMBOL_OF[t.kind], says };
|
|
586
|
+
});
|
|
587
|
+
const answers = member.rule ? ruleAnswers(member.rule) : null;
|
|
588
|
+
const limits = member.rule ? ruleRanges(member.rule) : null;
|
|
589
|
+
const openQuestions = (member.rule?.needsReview ?? []).filter((q) => !/^No examples yet/.test(q));
|
|
590
|
+
return { inputs, changes, stops, givesBack, reliesOn, ...(answers ? { answers } : {}), ...(limits ? { limits } : {}), openQuestions };
|
|
591
|
+
}
|
|
592
|
+
|
|
484
593
|
/**
|
|
485
594
|
* What one reading level shows: `level` is a LEVELS id (big-picture, flow, details, text, original); `focus` is a
|
|
486
595
|
* Thing or member id, or nothing for the whole model. Flow and Details need an action or rule; without one they
|
|
@@ -526,7 +635,8 @@ export function readLevel(model, level, focus) {
|
|
|
526
635
|
if (lv.id === 'flow') return { ...base, ...about, flow: member.flow };
|
|
527
636
|
if (lv.id === 'details') {
|
|
528
637
|
const steps = detailSteps(member.flow);
|
|
529
|
-
return { ...base, ...about, youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}),
|
|
638
|
+
return { ...base, ...about, youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), ...(member.doc ? { doc: member.doc } : {}),
|
|
639
|
+
...detailsFacts(model, member), steps,
|
|
530
640
|
notExplained: steps.filter((s) => s.notExplained).length, uses, usedBy, tryable: !!member.rule, ...(member.rule ? { rule: member.rule } : {}),
|
|
531
641
|
source: 'Read from code by the Thunder compiler, with no AI.' };
|
|
532
642
|
}
|
package/src/read.mjs
CHANGED
|
@@ -1773,7 +1773,9 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
1773
1773
|
if (st.kind !== 'branch' || !st.cond) continue;
|
|
1774
1774
|
// A bare yes/no property (`order.refunded`) already reads as a sentence from the step itself; keep it.
|
|
1775
1775
|
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ''));
|
|
1776
|
-
|
|
1776
|
+
// A plain name used as a yes/no (`if (!slug)`) already reads as "slug is not set"; keep it rather than "not slug".
|
|
1777
|
+
const bareName = /^(not\s+|!)?(?:self\.|this\.)?\w+$/.test(st.cond.trim()) && /\bis (not )?set\b/.test(st.says);
|
|
1778
|
+
const cond = bareProperty || bareName ? null : toThunderCondition(st.cond, names);
|
|
1777
1779
|
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? 'not: ' : ''}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, ' is not empty').replace(/ is ""/g, ' is empty')}${inner || ''}`);
|
|
1778
1780
|
delete st.cond; delete st.negate;
|
|
1779
1781
|
}
|
package/src/steps.mjs
CHANGED
|
@@ -223,6 +223,25 @@ function sayChain(value) {
|
|
|
223
223
|
return hit ? hit.c.say(words(src.split('.').pop().replace(/^#/, ''))) : null;
|
|
224
224
|
}
|
|
225
225
|
|
|
226
|
+
const HTTP_STATUS = { 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 409: 'Conflict', 410: 'Gone', 413: 'Payload Too Large', 415: 'Unsupported Media Type', 422: 'Unprocessable Content', 429: 'Too Many Requests', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout' };
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* An HTTP error response, returned or sent: Fastify `reply.code(400).send(...)`, Express `res.status(404).json(...)`,
|
|
230
|
+
* `new Response(..., { status: 403 })`, FastAPI `JSONResponse(..., status_code=422)`, Flask `return jsonify(...), 400`.
|
|
231
|
+
* Gives a fail step: { kind: 'fail', says, error: '400 Bad Request', message, status } or null.
|
|
232
|
+
*/
|
|
233
|
+
function httpErrorOf(head) {
|
|
234
|
+
const expr = head.replace(/^return\s+/, '').replace(/^await\s+/, '').replace(/;\s*$/, '').trim();
|
|
235
|
+
let m = expr.match(/^(?:reply|res|response|resp|ctx\.response)\s*\.\s*(?:code|status|statusCode)\s*\(\s*([45]\d\d)\s*\)/)
|
|
236
|
+
|| expr.match(/^(?:new\s+)?(?:Response|NextResponse(?:\.json)?|HttpResponse|JSONResponse|PlainTextResponse|Response\.json)\s*\(.*\bstatus(?:_code)?\s*[:=]\s*([45]\d\d)\b/)
|
|
237
|
+
|| (/^return\b/.test(head) ? expr.match(/^.+,\s*([45]\d\d)\s*$/) : null);
|
|
238
|
+
if (!m) return null;
|
|
239
|
+
const status = Number(m[1]);
|
|
240
|
+
const name = HTTP_STATUS[status] ?? (status >= 500 ? 'Server Error' : 'Client Error');
|
|
241
|
+
const msg = (expr.match(/\b(?:error|message|detail|msg)\s*[:=]\s*["'`]([^"'`]{1,80})["'`]/) || expr.match(/\.(?:send|json|end)\(\s*["'`]([^"'`]{1,80})["'`]/) || [])[1];
|
|
242
|
+
return { kind: 'fail', says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ''}`, error: `${status} ${name}`, ...(msg ? { message: msg } : {}), status };
|
|
243
|
+
}
|
|
244
|
+
|
|
226
245
|
export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
227
246
|
const text = String(raw).trim();
|
|
228
247
|
// TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
|
|
@@ -256,6 +275,9 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
256
275
|
const said = name && /^[a-z]/.test(name) ? `the error made by ${words(name)}` : name;
|
|
257
276
|
return { kind: 'fail', says: `Fails${said ? ` with ${said}` : ''}${msg ? `: "${msg}"` : ''}`, code, ...(name ? { error: name } : {}), ...(msg ? { message: msg } : {}) };
|
|
258
277
|
}
|
|
278
|
+
// An HTTP error response (4xx/5xx) is a Stop: the request is refused, with a status and a message.
|
|
279
|
+
const httpFail = httpErrorOf(head);
|
|
280
|
+
if (httpFail) return { ...httpFail, code };
|
|
259
281
|
// Returns (Go/Rust error returns read as failures)
|
|
260
282
|
if ((m = head.match(/^return\b\s*(.*)$/))) {
|
|
261
283
|
const expr = stripTail(m[1]);
|
|
@@ -479,7 +501,10 @@ export function stepsFrom(statements) {
|
|
|
479
501
|
if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
|
|
480
502
|
if (/^[)\]}]+[):;,]*$/.test(t0) || /^\.\.\.$/.test(t0) || /^\.[A-Za-z_]/.test(t0) || /^@\w+(?:\(.*\))?$/.test(t0) || /^#?\[[\w:]+(?:\(.*\))?\]$/.test(t0) || /^:(?:param|rtype|return|raises|type)\b/.test(t0)) { skipped.push(spanOf(s)); continue; }
|
|
481
503
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
482
|
-
if (
|
|
504
|
+
// A one-line `if (x) return reply.code(400).send({ error: 'bad' })` is one statement: its braces belong to the
|
|
505
|
+
// object being sent, not to a block, so read the statement after the condition instead of the braces' inside.
|
|
506
|
+
if (step.inline && !/^\{/.test(step.inline.trim())) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
|
|
507
|
+
else if (s.children?.length && ['branch', 'loop', 'try'].includes(step.kind)) {
|
|
483
508
|
const kids = stepsFrom(s.children).steps;
|
|
484
509
|
if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); }
|
|
485
510
|
}
|
package/src/visual.mjs
CHANGED
|
@@ -28,7 +28,7 @@ export const FORMS = [
|
|
|
28
28
|
export const LEVELS = [
|
|
29
29
|
{ id: 'big-picture', name: 'Big Picture', question: 'What is it, and what can it do?', shows: 'The Things, what each knows and can do, its doors (actions), its rules, and its data. For one action or rule: what you give it, what you get back, and what it uses.', form: 'picture' },
|
|
30
30
|
{ id: 'flow', name: 'Flow', question: 'How does it go?', shows: 'One action or rule as a path: questions with Yes and No, repeats, the Stops, what happens if something goes wrong, and what always happens at the end.', form: 'picture' },
|
|
31
|
-
{ id: 'details', name: 'Details', question: 'Exactly what happens, and how sure is Thunder?', shows: '
|
|
31
|
+
{ id: 'details', name: 'Details', question: 'Exactly what happens, and how sure is Thunder?', shows: 'A fact sheet: every way it can end (each Stop with its message, and what it gives back), the answers that lead there, what it changes, what goes in, what it relies on, a rule\'s answers and exact limits, and what the code cannot tell you.', form: 'picture' },
|
|
32
32
|
{ id: 'text', name: 'Text', question: 'What does it say, in words?', shows: 'Thunder Text: the same meaning in structured words, for reading closely, reviewing a change, and keeping a copy.', form: 'words' },
|
|
33
33
|
{ id: 'original', name: 'Original', question: 'Which code says so?', shows: 'The exact lines in the original language that Thunder read. The evidence, one click away.', form: 'evidence' },
|
|
34
34
|
];
|