@skillstech/thunderlang 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
@@ -0,0 +1,192 @@
1
+ // thunder read --level: the five reading levels in the terminal (big-picture, flow, details, text, original).
2
+ // Every level comes from readLevel() in model.mjs, the same compiler model OpenThunder's "Read in Thunder" shows, so
3
+ // the terminal never says something the picture doesn't. This file only lays it out as text. A step Thunder could
4
+ // not explain is marked, never smoothed over.
5
+ import { LEVELS } from './visual.mjs';
6
+ import { readLevel } from './model.mjs';
7
+
8
+ const squash = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
9
+ const at = (file, lines) => (file ? `${file}${lines?.[0] ? `:${lines[0]}` : ''}` : '');
10
+ const lineNote = (n) => (n?.line ? ` (line ${n.line})` : '');
11
+ const list = (xs) => xs.filter(Boolean).join(', ');
12
+
13
+ /** Find an action, rule, or Thing by its label (forgiving: case, spaces, and _ do not matter) or by its id. */
14
+ /** The level closest to a mistyped one, or null. */
15
+ export function nearestLevel(word) {
16
+ const d = (a, b) => { const m = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) m[0][j] = j; for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); return m[a.length][b.length]; };
17
+ const best = LEVELS.map((l) => [l.id, d(String(word).toLowerCase(), l.id)]).sort((x, y) => x[1] - y[1])[0];
18
+ return best && best[1] <= 2 ? best[0] : null;
19
+ }
20
+
21
+ export function findFocus(model, name) {
22
+ if (!name) return { id: null };
23
+ const want = squash(name);
24
+ // A screen and the function or class behind it share a name: the screen is what a person means.
25
+ const screens = model.screens ?? [];
26
+ const pool = [...screens, ...model.members.filter((m) => m.kind !== 'setup' && !m.screen), ...model.things.filter((t) => !t.screen)];
27
+ const exact = pool.filter((x) => x.id === name || squash(x.label) === want || squash(x.name) === want);
28
+ if (exact.length === 1) return { id: exact[0].id };
29
+ if (exact.length > 1) return { error: `"${name}" names ${exact.length} things: ${exact.map((x) => `${x.label} (${at(x.file, x.lines)})`).join(', ')}. Use one of their ids with --focus: ${exact.map((x) => x.id).join(', ')}.` };
30
+ const near = pool.filter((x) => squash(x.label).includes(want)).slice(0, 5);
31
+ return { error: `Nothing here is called "${name}".${near.length ? ` Did you mean: ${near.map((x) => `"${x.label}"`).join(', ')}?` : ''}` };
32
+ }
33
+
34
+ const MARK = { start: '▶', decision: '◆', stop: '✗', end: '■', loop: '↻', step: '•' };
35
+
36
+ /** A flow as an indented tree: questions with their yes and no branches, repeats, error handlers, and "always". */
37
+ function flowLines(flow) {
38
+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));
39
+ const L = [];
40
+ const text = (n) => {
41
+ const unexplained = n.explained === false || n.does === 'code';
42
+ return `${MARK[n.kind] ?? '•'} ${n.text}${unexplained ? ' [not read: shown as code]' : ''}`;
43
+ };
44
+ const start = flow.nodes.find((n) => n.kind === 'start');
45
+ if (start) L.push(` ${text(start)}`);
46
+ const walk = (blocks, pad) => {
47
+ for (const b of blocks || []) {
48
+ const n = byId.get(b.id);
49
+ if (!n) continue;
50
+ L.push(`${pad}${text(n)}${lineNote(n)}`);
51
+ const branch = (label, xs) => {
52
+ if (!xs) return;
53
+ if (!xs.length) { L.push(`${pad} ${label} → carry on`); return; }
54
+ L.push(`${pad} ${label} →`);
55
+ walk(xs, `${pad} `);
56
+ };
57
+ if (b.yes || b.no) { branch('yes', b.yes); branch('no', b.no); }
58
+ if (b.each) walk(b.each, `${pad} `);
59
+ if (b.body) walk(b.body, `${pad} `);
60
+ for (const h of b.handlers || []) { const hn = byId.get(h.id); L.push(`${pad} ${hn ? hn.text.replace(/\?$/, '') : 'if something goes wrong'} →`); walk(h.blocks, `${pad} `); }
61
+ if (b.always) { L.push(`${pad} always, at the end →`); walk(b.always.blocks, `${pad} `); }
62
+ }
63
+ };
64
+ walk(flow.blocks, ' ');
65
+ // The end, when the tree does not already show it.
66
+ const shown = new Set(L.join('\n').match(/■ [^\n]*/g) ?? []);
67
+ for (const n of flow.nodes.filter((x) => x.kind === 'end' && !(flow.blocks || []).some((b) => b.id === x.id))) if (!shown.has(`■ ${n.text}`) && !L.some((l) => l.includes(`■ ${n.text}`))) L.push(` ${text(n)}`);
68
+ return L;
69
+ }
70
+
71
+ const whenText = (when) => (when?.length ? ` when ${when.map((w) => w.says ?? (/^if /i.test(w.question) && /^yes$/i.test(w.answer) ? w.question.replace(/^if /i, '').replace(/\?$/, '') : `${w.question.replace(/\?$/, '')}: ${w.answer}`)).join(' and ')}` : '');
72
+
73
+ /** One level as terminal text. `sources` maps a file path to its text (for the original level). */
74
+ /** A screen's outline: what it shows, as nested lines (otherwise branches included). */
75
+ function outline(items, pad, L) {
76
+ for (const it of items) {
77
+ L.push(`${pad}${it.notRead ? '?' : '•'} ${it.says}${it.line ? ` (line ${it.line})` : ''}`);
78
+ if (it.kids) outline(it.kids, `${pad} `, L);
79
+ if (it.otherwise) { L.push(`${pad} ${it.otherwise.says}`); outline(it.otherwise.kids, `${pad} `, L); }
80
+ }
81
+ return L;
82
+ }
83
+
84
+ function renderScreen(r, next) {
85
+ const L = [`${r.name} · ${r.title} (${r.framework === 'react' ? 'React' : 'Angular'} screen${r.selector ? ` <${r.selector}>` : ''}, ${r.file}:${r.lines[0]})`, r.question, ''];
86
+ const inputs = (r.inputs ?? []).map((i) => `${i.label}${i.kind ? ` (${i.kind})` : ''}`).join(', ');
87
+ const state = (r.state ?? []).map((x) => `${x.label}${x.start ? ` (${/^(from|worked out)/.test(x.start) ? x.start : `starts as ${x.start}`})` : ''}`).join(', ');
88
+ if (r.level === 'big-picture') {
89
+ L.push(`It receives: ${inputs || 'nothing'}`, `It remembers: ${state || 'nothing'}`);
90
+ if (r.outputs?.length) L.push(`It sends: ${r.outputs.map((o) => o.label).join(', ')}`);
91
+ if (r.services?.length) L.push(`It uses: ${r.services.join(', ')}`);
92
+ if (r.uses?.length) L.push(`It shows: ${r.uses.map((u) => u.label).join(', ')}`);
93
+ if (r.usedBy?.length) L.push(`Shown by: ${r.usedBy.map((u) => u.label).join(', ')}`);
94
+ L.push(`Events: ${r.events}${r.notRead ? ` Not read: ${r.notRead}` : ''}`, '', `Next: ${next('flow')}`);
95
+ return L.join('\n');
96
+ }
97
+ if (r.level === 'flow') {
98
+ for (const e of r.early ?? []) { L.push(` When ${e.when}, it shows only:`); outline(e.shows.length ? e.shows : [{ says: 'nothing' }], ' ', L); }
99
+ if (r.shows.length) { L.push(' It shows:'); outline(r.shows, ' ', L); } else L.push(' It shows nothing Thunder could read.');
100
+ L.push('', `Next: ${next('details')}`);
101
+ return L.join('\n');
102
+ }
103
+ if (r.level === 'details') {
104
+ L.push(`It receives: ${inputs || 'nothing'}`, `It remembers: ${state || 'nothing'}`);
105
+ if (r.events.length) { L.push('When someone acts:'); for (const e of r.events) L.push(` • ${e.when}: ${e.runs}${e.line ? ` (line ${e.line})` : ''}`); }
106
+ if (r.effects.length) { L.push('By itself:'); for (const e of r.effects) L.push(` • ${e.when}: ${e.runs}${e.line ? ` (line ${e.line})` : ''}`); }
107
+ if (r.outputs.length) L.push(`It sends: ${r.outputs.map((o) => o.label).join(', ')}`);
108
+ if (r.notRead.length) { L.push("Can't tell from the code:"); for (const n of r.notRead) L.push(` ? ${n.line ? `line ${n.line}: ` : ''}\`${n.code}\`: ${n.why}`); }
109
+ L.push('', r.source);
110
+ return L.join('\n');
111
+ }
112
+ if (r.level === 'text') return [...L, r.text.trimEnd()].join('\n');
113
+ return null;
114
+ }
115
+
116
+ export function renderLevel(r, { sources = {}, file = 'file' } = {}) {
117
+ if (r.scope === 'screen' && r.level !== 'original') return renderScreen(r, (lv) => `thunder read ${file} --level ${lv} --focus "${r.title}"`);
118
+ const L = [`${r.name} · ${r.title}${r.file && r.scope !== 'app' ? ` (${at(r.file, r.lines)})` : ''}`, r.question, ''];
119
+ const next = (lv, focus) => `thunder read ${file} --level ${lv}${focus ? ` --focus "${focus}"` : ''}`;
120
+
121
+ if (r.needsFocus) {
122
+ L.push(r.says, '');
123
+ for (const c of r.choose.slice(0, 20)) L.push(` ${next(r.level, c.label.replace(/\?$/, ''))}`);
124
+ if (r.choose.length > 20) L.push(` …and ${r.choose.length - 20} more`);
125
+ return L.join('\n');
126
+ }
127
+
128
+ if (r.level === 'big-picture' && r.scope !== 'member') {
129
+ if (r.purpose) L.push(r.purpose, '');
130
+ for (const t of r.things) {
131
+ L.push(`${t.label}${t.doc ? `: ${t.doc}` : ''}`);
132
+ if (t.knows.length) L.push(` Knows: ${list(t.knows.map((k) => `${k.label}${k.start ? ` (${k.start})` : ''}`))}`);
133
+ if (t.can.length) L.push(` Can do: ${list(t.can.map((c) => `${c.label}${c.symbol === 'rule' ? ' (rule)' : ''}`))}`);
134
+ }
135
+ for (const x of r.resources) L.push(`${x.label} (${x.resourceType})${x.address ? `: ${x.address}` : ''}`);
136
+ const loose = [...r.actions.filter((a) => !r.things.some((t) => t.can.some((c) => c.id === a.id))), ...r.rules.filter((a) => !r.things.some((t) => t.can.some((c) => c.id === a.id))), ...r.loose];
137
+ if (loose.length) L.push(`Actions and rules: ${list(loose.map((c) => `${c.label}${c.symbol === 'rule' ? ' (rule)' : ''}`))}`);
138
+ if (r.data.length) { L.push('Data'); for (const d of r.data) L.push(` ${d.label}: ${d.choices ? d.choices.join(' | ') : list(d.knows) || '(nothing it knows)'}`); }
139
+ if (r.permissions?.length) L.push(`Permissions: ${r.permissions.length}`);
140
+ if (r.screens?.length) { L.push('Screens'); for (const x of r.screens) L.push(` ${x.label} (${x.role === 'page' ? 'page, ' : x.role === 'part' ? 'part, ' : ''}${x.framework === 'react' ? 'React' : 'Angular'}${x.selector ? ` <${x.selector}>` : ''})${x.uses.length ? `: shows ${x.uses.join(', ')}` : ''}`); }
141
+ if (r.unknowns?.length) L.push(`Not read: ${r.unknowns.length} part${r.unknowns.length === 1 ? '' : 's'} Thunder could not explain (see --level details)`);
142
+ const first = r.screens?.[0] ? { label: r.screens[0].label } : r.things[0]?.can[0] ?? loose[0];
143
+ if (first) L.push('', `Next: ${next('flow', first.label.replace(/\?$/, ''))}`);
144
+ return L.join('\n').trimEnd();
145
+ }
146
+
147
+ if (r.level === 'big-picture') {
148
+ if (r.doc) L.push(r.doc, '');
149
+ if (r.owner) L.push(`Part of: ${r.owner.label}`);
150
+ if (r.route) L.push(`Reached at: ${r.route.method ?? ''} ${r.route.path ?? ''}`.trimEnd());
151
+ L.push(`You give it: ${list((r.youGive || []).map((g) => g.label ?? g)) || 'nothing'}`);
152
+ if (r.youGetBack) L.push(`You get back: ${typeof r.youGetBack === 'string' ? r.youGetBack : r.youGetBack.label ?? JSON.stringify(r.youGetBack)}`);
153
+ if (r.uses?.length) L.push(`Uses: ${list(r.uses.map((u) => u.label))}`);
154
+ if (r.usedBy?.length) L.push(`Used by: ${list(r.usedBy.map((u) => u.label))}`);
155
+ L.push('', `Next: ${next('flow', r.title.replace(/\?$/, ''))}`);
156
+ return L.join('\n');
157
+ }
158
+
159
+ if (r.level === 'flow') {
160
+ L.push(...flowLines(r.flow));
161
+ L.push('', `Next: ${next('details', r.title.replace(/\?$/, ''))}`);
162
+ return L.join('\n');
163
+ }
164
+
165
+ if (r.level === 'details') {
166
+ L.push(`You give it: ${list((r.inputs || []).map((i) => `${i.label}${i.kind ? ` (${i.kind})` : ''}`)) || 'nothing'}`);
167
+ // A rule's answers say it best ("Small fee when the days late is at most 7"); otherwise what it gives back.
168
+ if (r.answers?.length) { L.push('Answers:'); for (const x of r.answers) L.push(` ■ ${x.answer ?? x.value ?? x.text}${x.when && x.when !== 'otherwise' ? ` when ${x.when}` : x.when === 'otherwise' ? ' otherwise' : ''}`); }
169
+ else if (r.givesBack?.length) { L.push('Gives back:'); for (const g of r.givesBack) L.push(` ■ ${g.text ?? g.value ?? g.label}${whenText(g.when)}${lineNote(g)}`); }
170
+ if (r.stops?.length) { L.push('Stops:'); for (const s of r.stops) L.push(` ✗ ${s.error}${s.message ? ` "${s.message}"` : ''}${whenText(s.when)}${lineNote(s)}`); }
171
+ if (r.changes?.length) { L.push('Changes:'); for (const c of r.changes) L.push(` • ${c.text}${whenText(c.when)}${lineNote(c)}`); }
172
+ if (r.reliesOn?.length) L.push(`Relies on: ${list(r.reliesOn.map((x) => x.label ?? x.text ?? x))}`);
173
+ const open = [...(r.openQuestions || []).map((q) => q.text ?? q.says ?? q), ...(r.notLinked || []).map((x) => `${x.call ?? x.import ?? 'a call'}: ${x.why}`)];
174
+ if (r.notExplained) open.unshift(`${r.notExplained} step${r.notExplained === 1 ? '' : 's'} not read (shown as code; see --level original)`);
175
+ if (open.length) { L.push("Can't tell from the code:"); for (const q of open) L.push(` ? ${q}`); }
176
+ L.push('', r.source);
177
+ return L.join('\n');
178
+ }
179
+
180
+ if (r.level === 'text') return [...L, r.text.trimEnd()].join('\n');
181
+
182
+ // original: the exact lines Thunder read.
183
+ const src = sources[r.file];
184
+ if (!src) return [...L, `(The text of ${r.file ?? 'this file'} is not available.)`].join('\n');
185
+ const all = src.split('\n');
186
+ const [a, b] = r.lines ?? [1, all.length];
187
+ const width = String(b).length;
188
+ for (let i = a; i <= Math.min(b, all.length); i++) L.push(`${String(i).padStart(width)} │ ${all[i - 1]}`);
189
+ return L.join('\n');
190
+ }
191
+
192
+ export { LEVELS, readLevel };
@@ -22,7 +22,8 @@ const MANIFEST = /^(go\.mod|package\.json|tsconfig\.json|jsconfig\.json)$/;
22
22
  * go.mod, package.json, and tsconfig/jsconfig files that say which imports are this repo's own (for thunderModel's
23
23
  * calls across files); they are not code and are not read as code.
24
24
  */
25
- export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false } = {}) {
25
+ // templates: also bring Angular component templates (*.component.html), which screens read with their component.
26
+ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, templates = false } = {}) {
26
27
  const out = [];
27
28
  const walk = (dir) => {
28
29
  let names;
@@ -36,6 +37,7 @@ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400
36
37
  const path = relative(root, full).split('\\').join('/');
37
38
  if (st.isDirectory()) walk(full);
38
39
  else if (manifests && MANIFEST.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), manifest: true });
40
+ else if (templates && /\.component\.html$/i.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), template: true });
39
41
  else if (readableLanguage(path) || (!name.includes('.') && shebangShell(full, st.size))) {
40
42
  // Oversized files are not loaded; readRepo lists them as skipped from their size.
41
43
  out.push(st.size > maxFileBytes ? { path, source: '', size: st.size } : { path, source: readFileSync(full, 'utf8') });
package/src/read.mjs CHANGED
@@ -244,7 +244,8 @@ function balancedReturnHead(after) {
244
244
  if (c === '=' && after[i + 1] === '>') { if (depth === 0) break; i++; continue; } // => ends the type, or is a function type's arrow
245
245
  if (c === '<' || c === '(' || c === '[') depth++;
246
246
  else if (c === '>' || c === ')' || c === ']') depth--;
247
- else if (c === '{') { if (depth === 0) break; depth++; }
247
+ // (At the top, a "{" with no type before it, or after | or &, starts an object type: `): { ok: boolean } {`.)
248
+ else if (c === '{') { if (depth === 0 && !/^$|[|&]$/.test(after.slice(lead[0].length, i).trim())) break; depth++; }
248
249
  else if (c === '}') depth--;
249
250
  else if (c === ';' && depth === 0) break;
250
251
  else if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < after.length && after[i] !== q) i++; }
@@ -324,7 +325,8 @@ function findFunctions(src, language) {
324
325
  const patterns = {
325
326
  typescript: [
326
327
  /(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
327
- /(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
328
+ // The type annotation stops at the end of its statement (";"), or `let a: T;` would name the next line's function.
329
+ /(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
328
330
  /^\s*(?:public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/gm,
329
331
  ],
330
332
  go: [/func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\s*\(/g],
@@ -418,7 +420,8 @@ function findFunctions(src, language) {
418
420
  : language === 'go'
419
421
  ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
420
422
  : (language === 'typescript' || language === 'javascript')
421
- ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
423
+ // (The handler may be wrapped: `fastify.get('/x', handle(async (request) => …))`, `asyncHandler(…)`.)
424
+ ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
422
425
  : [];
423
426
  for (const re of routeRes) {
424
427
  let m;
@@ -426,11 +429,31 @@ function findFunctions(src, language) {
426
429
  const open = src.indexOf('(', m.index + m[0].length - 1);
427
430
  const close = matchClose(src, open);
428
431
  if (close < 0) continue;
432
+ const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
429
433
  const brace = src.indexOf('{', close);
430
- if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) continue;
434
+ if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) {
435
+ // An arrow whose body is one expression: `async (request) => practiceView(…)`. It gives back that value;
436
+ // the expression runs to the first ")" or "," that closes the call around it.
437
+ const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
438
+ if (!(language === 'typescript' || language === 'javascript') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
439
+ const from = close + 1 + arrow[0].length;
440
+ let depth = 0, end = from, q = null;
441
+ for (; end < src.length; end++) {
442
+ const c = src[end];
443
+ if (q) { if (c === q && src[end - 1] !== '\\') q = null; continue; }
444
+ if (c === "'" || c === '"' || c === '`') { q = c; continue; }
445
+ if ('([{'.includes(c)) depth++;
446
+ else if (')]}'.includes(c)) { if (depth === 0) break; depth--; }
447
+ else if ((c === ',' || c === ';') && depth === 0) break;
448
+ }
449
+ const expr = src.slice(from, end).trim();
450
+ if (!expr) continue;
451
+ // (Read as `return <expr>`: the body starts 7 characters early so every line number stays right.)
452
+ fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: from - 7, body: `return ${expr};`, route: { method, path: m[2] }, expressionBody: true });
453
+ continue;
454
+ }
431
455
  const bc = matchClose(src, brace);
432
456
  if (bc < 0) continue;
433
- const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
434
457
  fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method, path: m[2] } });
435
458
  }
436
459
  }
@@ -0,0 +1,123 @@
1
+ // thunder replay: the Thunder Time Machine. Step forward and back through a recording made with
2
+ // `thunder run --record <file>`: each statement as it ran, the values it changed, what it printed, what a function
3
+ // gave back, and where a choice or a loop went. It replays a recording: going back shows an earlier moment and never
4
+ // undoes anything the program did.
5
+ // thunder replay <file> [--step n] [--json]
6
+ import { readFileSync } from 'node:fs';
7
+ import { createInterface } from 'node:readline';
8
+ import { paint, paintThunderLine, useColor } from './term.mjs';
9
+
10
+ const SCHEMA = 'thunder-time-machine-v1';
11
+ const USAGE = `usage: thunder replay <recording.json> [--step n] [--json]
12
+ Step through a recording made with: thunder run <program> --record <recording.json>
13
+ Keys: Enter or n for the next step, b to go back, j and a number to jump (j 7), q to quit.`;
14
+
15
+ /** The text of a Thunder line from the recording's copy of the program. */
16
+ const lineText = (trace, file, line) => {
17
+ const src = trace.files?.[file] ?? Object.values(trace.files ?? {})[0];
18
+ return src ? (src.split('\n')[line - 1] ?? '').trim() : '';
19
+ };
20
+
21
+ /**
22
+ * Where a choice or a loop went, in words. For When / Otherwise when / Otherwise, the arm whose lines hold the next
23
+ * step answers it: the first arm is "yes"; a later one is "no", then that arm.
24
+ */
25
+ function branchText(trace, s) {
26
+ if (s.next == null) return s.kind === 'if' ? ' → no, so nothing inside ran' : ' → the steps inside did not run';
27
+ if (s.kind !== 'if') return ` → goes on to line ${s.next}`;
28
+ const src = (trace.files?.[s.file] ?? '').split('\n');
29
+ const indent = (l) => l.match(/^\s*/)[0].length;
30
+ const base = indent(src[s.line - 1] ?? '');
31
+ const arms = [{ line: s.line, text: (src[s.line - 1] ?? '').trim() }];
32
+ for (let k = s.line; k < src.length; k++) {
33
+ const l = src[k];
34
+ if (!l.trim()) continue;
35
+ if (indent(l) < base || (indent(l) === base && !/^\s*Otherwise\b/.test(l))) break;
36
+ if (indent(l) === base) arms.push({ line: k + 1, text: l.trim() });
37
+ }
38
+ const arm = [...arms].reverse().find((x) => x.line < s.next) ?? arms[0];
39
+ if (arm === arms[0]) return ' → yes';
40
+ if (/^Otherwise:$/.test(arm.text)) return ` → no, so the Otherwise steps (line ${arm.line})`;
41
+ return ` → no; then: ${arm.text.replace(/^Otherwise\s+(when|if)\s+/i, '').replace(/:$/, '')} → yes (line ${arm.line})`;
42
+ }
43
+
44
+ /** One step as a few lines of plain text. */
45
+ export function renderStep(trace, i) {
46
+ const steps = trace.steps;
47
+ const s = steps[i];
48
+ if (!s) return `There is no step ${i + 1}. This recording has ${steps.length} step${steps.length === 1 ? '' : 's'}.`;
49
+ const where = s.fn ? `inside "${s.fn.replace(/_/g, ' ')}"` : 'in the program';
50
+ const L = [`⏱ Step ${s.n} of ${steps.length} · ${s.file}, line ${s.line} · ${where}`, ` ${paintThunderLine(lineText(trace, s.file, s.line), useColor())}`];
51
+ // A call: the steps deeper than this one, right after it, belong to the function it called.
52
+ let j = i + 1;
53
+ while (j < steps.length && steps[j].depth > s.depth) j++;
54
+ const calls = j > i + 1 && !('next' in s) ? steps[i + 1] : null;
55
+ if (calls) L.push(` Calls "${(calls.fn ?? 'a function').replace(/_/g, ' ')}" (step${j - i - 1 === 1 ? '' : 's'} ${i + 2}${j - i - 1 > 1 ? `–${j}` : ''}), then:`);
56
+ if ('next' in s) L.push(branchText(trace, s));
57
+ for (const c of s.changes ?? []) L.push(` ${c.name}: ${c.before != null ? `${c.before} → ` : '→ '}${c.after}`);
58
+ if (s.gives != null) L.push(` gives back ${s.gives}`);
59
+ if (s.said) for (const line of s.said.replace(/\n$/, '').split('\n')) L.push(` says: ${line}`);
60
+ if (s.failed && !('next' in s)) L.push(` ✗ stopped here${trace.stderr ? `: ${trace.stderr.trim().replace(/^.*?: /, '')}` : ''}`);
61
+ if (!s.changes && s.gives == null && !s.said && !('next' in s) && !s.failed && !calls) L.push(' (nothing changed)');
62
+ return L.join('\n');
63
+ }
64
+
65
+ export function replayMain(argv, { input = process.stdin, output = process.stdout } = {}) {
66
+ const a = { _: [], step: null, json: false };
67
+ for (let i = 0; i < argv.length; i++) {
68
+ const x = argv[i];
69
+ if (x === '--step') a.step = argv[++i];
70
+ else if (x === '--json') a.json = true;
71
+ else if (x === '--help' || x === '-h') { console.log(USAGE); return Promise.resolve(0); }
72
+ else if (x.startsWith('--')) { console.error(`thunder replay: there is no option ${x}.\n${USAGE}`); return Promise.resolve(2); }
73
+ else a._.push(x);
74
+ }
75
+ if (a._.length !== 1) { console.error(`thunder replay: name one recording.\n${USAGE}`); return Promise.resolve(2); }
76
+ let trace;
77
+ try { trace = JSON.parse(readFileSync(a._[0], 'utf8')); }
78
+ catch (e) { console.error(`thunder replay: couldn't read ${a._[0]}${e.code === 'ENOENT' ? ': there is no such file' : ': it is not a recording'}. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
79
+ if (trace?.schema !== SCHEMA || !Array.isArray(trace.steps)) { console.error(`thunder replay: ${a._[0]} is not a Thunder recording. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
80
+ const total = trace.steps.length;
81
+ const say = (s = '') => output.write(`${paint(s, useColor(output))}\n`);
82
+ if (!total) { say('This recording has no steps (the program had nothing to run).'); return Promise.resolve(0); }
83
+ if (a.step != null) {
84
+ const n = Number(a.step);
85
+ if (!Number.isInteger(n) || n < 1 || n > total) { console.error(`thunder replay: --step needs a number from 1 to ${total}.`); return Promise.resolve(2); }
86
+ say(a.json ? JSON.stringify(trace.steps[n - 1], null, 2) : renderStep(trace, n - 1));
87
+ return Promise.resolve(0);
88
+ }
89
+ if (a.json) { say(JSON.stringify(trace, null, 2)); return Promise.resolve(0); }
90
+
91
+ // Step through: one step at a time, from the terminal or from piped lines.
92
+ say(`⚡ Replaying ${trace.program}: ${total} step${total === 1 ? '' : 's'}, recorded with Thunder™ ${trace.thunder}.`);
93
+ say('This replays a recording. Going back shows an earlier moment; it never undoes anything the program did.');
94
+ say('');
95
+ const rl = createInterface({ input, terminal: false });
96
+ const it = rl[Symbol.asyncIterator]();
97
+ let i = 0;
98
+ const show = () => { say(renderStep(trace, i)); };
99
+ const ask = async () => {
100
+ output.write(`\n ${i + 1 < total ? 'Enter/n next' : 'last step'} · b back · j N jump · q quit > `);
101
+ const r = await it.next();
102
+ if (r.done) return null;
103
+ if (!input.isTTY) output.write(`${r.value}\n`);
104
+ return r.value.trim();
105
+ };
106
+ return (async () => {
107
+ show();
108
+ for (;;) {
109
+ const c = await ask();
110
+ if (c == null || /^q/i.test(c)) break;
111
+ if (c === '' || /^n/i.test(c)) { if (i + 1 < total) i++; else { say('\nThat was the last step.'); continue; } }
112
+ else if (/^b/i.test(c)) { if (i > 0) i--; else { say('\nThis is the first step.'); continue; } }
113
+ else if (/^j\s*\d+$/i.test(c)) { const n = Number(c.replace(/\D/g, '')); if (n >= 1 && n <= total) i = n - 1; else { say(`\nJump to a step from 1 to ${total}.`); continue; } }
114
+ else { say('\nType Enter or n (next), b (back), j and a number (jump), or q (quit).'); continue; }
115
+ say('');
116
+ show();
117
+ }
118
+ rl.close();
119
+ say('');
120
+ if (trace.status !== 0) say(`The program stopped with a problem: ${trace.stderr.trim()}`);
121
+ return 0;
122
+ })();
123
+ }