@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
@@ -168,7 +168,7 @@ export const READ_LESSONS = [
168
168
  check: ({ item }) => flatSteps(item.steps).find((s) => s.kind === 'branch' && /coupon/.test(s.says)).children[0].says },
169
169
  ],
170
170
  title: "Software, as pictures",
171
- idea: "Code is a list of instructions written for a computer. Thunder shows the same instructions as a picture written for people. The Thunder compiler reads the code exactly; it never guesses.",
171
+ idea: "Code is a list of instructions written for a computer. Thunder™ shows the same instructions as a picture written for people. The Thunder compiler reads the code exactly; it never guesses.",
172
172
  picture: "A chef's shorthand notes and the recipe card in the cookbook describe the same dish. The code is the shorthand; Thunder is the recipe card anyone can follow.",
173
173
  files: [{ language: "python", label: "Python", code: `def order_total(order):
174
174
  total = 0
@@ -456,3 +456,247 @@ def place_order(order, card):
456
456
  ],
457
457
  },
458
458
  ];
459
+
460
+ // ── Part 2: write and run ──────────────────────────────────────────────────────────────────────────────────────
461
+ // Programs you write in Thunder Core. Every answer is worked out by compiling the lesson's program and running it on
462
+ // the Thunder engine (engine-core.mjs, which needs no Python and runs in a browser too). Each lesson names the
463
+ // programming concept it teaches, and `commands` are what to type in a terminal to do it yourself.
464
+
465
+ /** The program `thunder new` writes (a test checks they stay the same). */
466
+ export const STARTER_PROGRAM = `# Your first Thunder program. Run it with: thunder run
467
+
468
+ To greet:
469
+ Receive name
470
+ Give "Hello, {name}!"
471
+
472
+ say greet with "world"
473
+ `;
474
+
475
+ const CHOOSE = `Set total to $18.50
476
+
477
+ When total is at least $20:
478
+ say "Delivery is free"
479
+ Otherwise:
480
+ say "Delivery costs $3.99"
481
+ `;
482
+
483
+ const LOOP = `Set scores to [90, 75, 100]
484
+ Set total to 0
485
+ For each score in scores:
486
+ Increase total by score
487
+
488
+ say "Total: {total}"
489
+ say "First: {scores at 1}"
490
+ `;
491
+
492
+ const RECORD = `A Book has:
493
+ Title is text
494
+ Copies is a whole number
495
+ Never allow negative copies
496
+
497
+ Set book to a Book with title "Matilda" and copies 1
498
+ Set book's copies to book's copies - 1
499
+ say "{book's title}: {book's copies} left"
500
+ Set book's copies to book's copies - 1
501
+ If this fails:
502
+ say "Not allowed: {error}"
503
+ `;
504
+
505
+ const FEE_TESTS = `To delivery fee:
506
+ Receive total
507
+ When total is at least $20:
508
+ Give $0
509
+ Otherwise:
510
+ Give $3.99
511
+
512
+ Test "orders of $20 or more are free":
513
+ Expect delivery fee with $20 to be $0
514
+
515
+ Test "small orders pay for delivery":
516
+ Expect delivery fee with $5 to be $2.99
517
+ `;
518
+
519
+ const SHOP_PY = `def delivery_fee(total):
520
+ if total >= 20:
521
+ return 0
522
+ return 3.99
523
+
524
+
525
+ def safe_divide(a, b):
526
+ try:
527
+ return a / b
528
+ except ZeroDivisionError:
529
+ return None
530
+ `;
531
+
532
+ /** A small agent run record (OpenTelemetry, GenAI conventions): a refund that could not reach the payment service. */
533
+ const AGENT_RUN = (() => {
534
+ const t = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
535
+ const ns = (ms) => String(1764064800000000000n + BigInt(ms) * 1000000n);
536
+ const kv = (o) => Object.entries(o).map(([key, v]) => ({ key, value: { stringValue: String(v) } }));
537
+ const fail = (type, message) => ({ status: { code: 2, message }, events: [{ name: 'exception', attributes: kv({ 'exception.type': type, 'exception.message': message }) }] });
538
+ const span = (id, parent, name, s, e, attrs, extra = {}) => ({ traceId: t, spanId: id, ...(parent ? { parentSpanId: parent } : {}), name, startTimeUnixNano: ns(s), endTimeUnixNano: ns(e), attributes: kv(attrs), ...extra });
539
+ const post = (id, s) => span(id, 'c8e0a2b4d6f81a3c', 'POST', s, s + 2900, { 'http.request.method': 'POST', 'url.full': 'https://pay.example.com/v1/refunds', 'error.type': 'ConnectionError' }, fail('ConnectionError', 'Connection refused'));
540
+ return JSON.stringify({ resourceSpans: [{ scopeSpans: [{ spans: [
541
+ span('7c1e4a9b2d3f5061', null, 'invoke_agent support-bot', 0, 12400, { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': 'support-bot' }, fail('RuntimeError', 'tool failed')),
542
+ span('c8e0a2b4d6f81a3c', '7c1e4a9b2d3f5061', 'execute_tool refund_payment', 3150, 12350, { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': 'refund_payment', 'gen_ai.tool.call.arguments': '{"order_id": 1042, "amount": "40.00"}' }, fail('ConnectionError', 'failed after 3 attempts')),
543
+ post('1f3b5d7f9a1c3e50', 3200), post('6a8c0e2a4c6e8a01', 6300), post('b2d4f6b8d0f2b4d6', 9350),
544
+ ] }] }] }, null, 2);
545
+ })();
546
+
547
+ export const WRITE_LESSONS = [
548
+ {
549
+ slug: "first-program",
550
+ part: "write",
551
+ concept: "A program: instructions the computer follows, in order",
552
+ title: "Your first program, in two commands",
553
+ idea: "thunder new hello makes a folder called hello with a program inside. thunder run hello runs it. thunder new does not move you into the folder, so name it when you run it (or type cd hello first, then just thunder run).",
554
+ picture: "A recipe card. Writing it changes nothing; running it is cooking it.",
555
+ commands: ["thunder new hello", "thunder run hello"],
556
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: STARTER_PROGRAM }],
557
+ show: "run",
558
+ quiz: [
559
+ { prompt: "What does this program print?", choices: ["Hello, world!", "Hello, {name}!", "greet with \"world\""], expect: "Hello, world!",
560
+ explain: "To greet makes a step you can use; the last line uses it with \"world\". {name} inside text is filled in with the value, so it says Hello, world!",
561
+ check: ({ core }) => core.stdout.trim() },
562
+ { prompt: "Change \"world\" to \"Ada\" on the last line. What does it print now?", choices: ["Hello, Ada!", "Hello, world!", "Hello, {name}!"], expect: "Hello, Ada!",
563
+ explain: "The same steps run with a different value. That is the whole point of a step with an input: write it once, use it with anything.",
564
+ check: ({ runCore }) => runCore(STARTER_PROGRAM.replace('"world"', '"Ada"')).stdout.trim() },
565
+ ],
566
+ questions: [
567
+ { q: "You typed thunder new hello, then thunder run, and Thunder said there is no project here. Why?", a: "thunder new made the hello folder but did not move you into it. Run thunder run hello, or cd hello first." },
568
+ { q: "Which lines run first?", a: "To greet only describes a step; it runs when it is used. So the first thing that happens is the last line, which uses greet." },
569
+ ],
570
+ },
571
+ {
572
+ slug: "choose",
573
+ part: "write",
574
+ concept: "Conditions: the program chooses what to do",
575
+ title: "Write a choice and run it",
576
+ idea: "Open hello/src/main.thunder, write your own lines, and run it again. Thunder checks what you wrote first and explains any mistake by its line. By default your program runs as Python (Python 3.10 or newer); add --engine thunder to run it without Python. Python is the only full target today.",
577
+ picture: "A fork in a path with a sign: one way when the total is big enough, the other way otherwise.",
578
+ commands: ["thunder run hello", "thunder run hello --engine thunder"],
579
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: CHOOSE }],
580
+ show: "run",
581
+ quiz: [
582
+ { prompt: "What does this program print?", choices: ["Delivery costs $3.99", "Delivery is free"], expect: "Delivery costs $3.99",
583
+ explain: "$18.50 is not at least $20, so the Otherwise lines run.",
584
+ check: ({ core }) => core.stdout.trim() },
585
+ { prompt: "Change the total to $20. What does it print now?", choices: ["Delivery is free", "Delivery costs $3.99"], expect: "Delivery is free",
586
+ explain: "\"At least\" includes the limit itself: $20 is at least $20. The edge of a rule is where mistakes hide, so it is worth trying.",
587
+ check: ({ runCore }) => runCore(CHOOSE.replace('$18.50', '$20')).stdout.trim() },
588
+ ],
589
+ questions: [
590
+ { q: "Why is money written $18.50 and not 18.5?", a: "Money in Thunder is exact: $0.10 + $0.20 is exactly $0.30, and it always shows cents. A plain 18.5 would be a number, not money." },
591
+ ],
592
+ },
593
+ {
594
+ slug: "repeat",
595
+ part: "write",
596
+ concept: "Loops and lists: do something for each item",
597
+ title: "Go through a list",
598
+ idea: "A list holds several values in order. For each goes through them one at a time and runs the indented lines for every one. In Thunder the first item is at position 1, the way people count.",
599
+ picture: "A teacher reading a stack of tests, adding each score to a running total.",
600
+ commands: ["thunder run hello"],
601
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: LOOP }],
602
+ show: "run",
603
+ quiz: [
604
+ { prompt: "What is the total?", choices: ["Total: 265", "Total: 100", "Total: 90"], expect: "Total: 265",
605
+ explain: "The loop runs three times, once for each score: 90 + 75 + 100 = 265.",
606
+ check: ({ core }) => core.stdout.split('\n')[0] },
607
+ { prompt: "What does scores at 1 give?", choices: ["First: 90", "First: 75"], expect: "First: 90",
608
+ explain: "Positions start at 1, so scores at 1 is the first score. (In Python and JavaScript it would be scores[0]; Thunder counts like people do.)",
609
+ check: ({ core }) => core.stdout.split('\n')[1] },
610
+ ],
611
+ questions: [
612
+ { q: "How would you count only the scores of 90 or more?", a: "Inside the loop, add a choice: When score is at least 90: Increase count by 1." },
613
+ ],
614
+ },
615
+ {
616
+ slug: "records",
617
+ part: "write",
618
+ concept: "Records: data with a shape, and rules it must keep",
619
+ title: "Give your data a shape and a rule",
620
+ idea: "A record says what a kind of thing knows (a Book has a title and a number of copies). A Never rule on it is checked every time it changes, so a mistake is caught where it happens, with the rule's own words.",
621
+ picture: "A library card with fixed boxes to fill in, and a line printed at the bottom: copies can never go below zero.",
622
+ commands: ["thunder run hello"],
623
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: RECORD }],
624
+ show: "run",
625
+ quiz: [
626
+ { prompt: "The second change would make copies -1. What happens?", choices: ["Thunder refuses the change", "Copies becomes -1"], expect: "Thunder refuses the change",
627
+ explain: "Never allow negative copies is checked on every change. The change is refused, and If this fails catches it and says why: the rule, its line, and the value it would have had.",
628
+ check: ({ core }) => (core.stdout.split('\n')[1].startsWith('Not allowed:') ? 'Thunder refuses the change' : 'Copies becomes -1') },
629
+ ],
630
+ questions: [
631
+ { q: "Why put the rule on the record instead of checking before every change?", a: "Because then it cannot be forgotten. Every change to copies, anywhere in the program, is checked by the same rule." },
632
+ ],
633
+ },
634
+ {
635
+ slug: "python-as-thunder",
636
+ part: "write",
637
+ concept: "The same meaning in two languages, and honesty about the rest",
638
+ title: "Read Python as Thunder you can run",
639
+ idea: "thunder read shop.py --as-core turns Python into Thunder Core you can edit and run. A line Thunder cannot say with exactly the same meaning is never turned into something close: it is marked \"Not translated\", with the reason, and a Stop line that explains itself if it ever runs.",
640
+ picture: "A careful interpreter who translates every sentence they are sure of, and says \"I can't translate this one, here is why\" for the rest.",
641
+ commands: ["thunder read shop.py --as-core"],
642
+ files: [{ language: "python", label: "shop.py", code: SHOP_PY }],
643
+ asCore: true,
644
+ show: "run",
645
+ quiz: [
646
+ { prompt: "Which function comes across exactly?", choices: ["delivery fee", "safe divide", "both"], expect: "delivery fee",
647
+ explain: "delivery_fee is a comparison and two answers: Thunder says it exactly. safe_divide uses a Python try with a named error kind, which Core has no step for yet.",
648
+ check: ({ asCore }) => { const exact = asCore.functions.filter((f) => f.exact).map((f) => f.coreName); return exact.length === asCore.functions.length ? 'both' : exact.join(', '); } },
649
+ { prompt: "What happens if the part that was not translated runs?", choices: ["It stops with a clear message", "It guesses what the Python meant"], expect: "It stops with a clear message",
650
+ explain: "The not-translated line becomes Stop with \"Line 8 of the Python was not translated: try:\". Thunder never quietly does something different.",
651
+ check: ({ asCore }) => (/Stop with "Line \d+ of the Python was not translated/.test(asCore.core) ? 'It stops with a clear message' : 'It guesses what the Python meant') },
652
+ ],
653
+ questions: [
654
+ { q: "Why is \"not translated\" better than a close guess?", a: "A close guess looks right and behaves differently, which is the most dangerous kind of mistake. A marked line tells you exactly where to look." },
655
+ ],
656
+ },
657
+ {
658
+ slug: "check-test-verify",
659
+ part: "write",
660
+ concept: "Evidence: checking, testing, and verifying promise different things",
661
+ title: "Check, test, and verify",
662
+ idea: "thunder check reads your program before it runs and finds mistakes like a name that does not exist. thunder test runs your examples (Test blocks) and says which ones fail. thunder verify checks a change to the code, by a person or an AI, against the rules that must stay true. Each answers a different question; none replaces the others.",
663
+ picture: "A spell-checker (check), a practice exam (test), and an inspector who signs off on a renovation (verify).",
664
+ commands: ["thunder check hello", "thunder test hello"],
665
+ files: [{ language: "thunder", label: "hello/src/fee.thunder", code: FEE_TESTS }],
666
+ show: "run",
667
+ quiz: [
668
+ { prompt: "You write say totl instead of say total. When does Thunder tell you?", choices: ["Before it runs: it doesn't know what totl is", "Only when that line runs"], expect: "Before it runs: it doesn't know what totl is",
669
+ explain: "thunder check (and run, before running) reads the whole program first. An unknown name is found by its line, before anything happens.",
670
+ check: ({ compile }) => (compile('Set total to $18.50\nsay totl\n').diagnostics.some((d) => d.code === 'TC201') ? "Before it runs: it doesn't know what totl is" : 'Only when that line runs') },
671
+ { prompt: "Which test fails?", choices: ["small orders pay for delivery", "orders of $20 or more are free", "neither"], expect: "small orders pay for delivery",
672
+ explain: "The program gives $3.99 for a $5 order, but the test expected $2.99. thunder test shows both numbers and the line. Either the test or the program is wrong: a person decides which.",
673
+ check: ({ testCore }) => { const m = testCore(FEE_TESTS).stdout.match(/^FAIL {2}(.+?) \(/m); return m ? m[1] : 'neither'; } },
674
+ ],
675
+ questions: [
676
+ { q: "All your tests pass. Is the program right?", a: "It is right for the examples you wrote. Tests only cover what they check, which is why edge cases (like exactly $20) are worth a test of their own." },
677
+ ],
678
+ },
679
+ {
680
+ slug: "agent-why",
681
+ part: "write",
682
+ concept: "Reading what an AI agent did, and why it stopped",
683
+ title: "Ask what an AI agent did",
684
+ idea: "Agents leave a record of every step (an OpenTelemetry trace). thunder why run.json reads it and tells you in plain words what the agent did, what it changed, and why it stopped. When the record doesn't say whether a tool changes anything, Thunder guesses from the tool's name and says it guessed.",
685
+ picture: "A flight recorder, read back as a short story instead of a wall of numbers.",
686
+ commands: ["thunder why run.json"],
687
+ files: [{ language: "json", label: "run.json", code: AGENT_RUN }],
688
+ why: true,
689
+ show: "run",
690
+ quiz: [
691
+ { prompt: "How many times did the agent try to reach the payment service?", choices: ["3", "1", "0"], expect: "3",
692
+ explain: "Three POST requests in a row failed the same way, so Thunder shows them as one step with 3 tries.",
693
+ check: ({ why }) => String(why.problem.tries) },
694
+ { prompt: "How did Thunder decide that refund_payment changes something?", choices: ["From the tool's name (a guess)", "The tool declared it"], expect: "From the tool's name (a guess)",
695
+ explain: "The record does not say what the tool does, so Thunder used its name, and it says so. When a tool declares what it does (its MCP annotations), Thunder uses that instead.",
696
+ check: ({ why }) => (why.changes[0]?.basis === 'name' ? "From the tool's name (a guess)" : 'The tool declared it') },
697
+ ],
698
+ questions: [
699
+ { q: "The refund did not go through. Was the customer refunded?", a: "Thunder can't know: the record shows the requests failed, not what the payment service did. It says the step may have partly happened, so a person checks." },
700
+ ],
701
+ },
702
+ ];
package/src/learn.d.mts CHANGED
@@ -9,6 +9,12 @@ export interface LearnLesson {
9
9
  /** A picture to hold in mind. */
10
10
  picture: string;
11
11
  part: 'read' | 'write';
12
+ /** Write lessons: the programming concept it teaches ("Loops and lists: do something for each item"). */
13
+ concept?: string;
14
+ /** Write lessons: what to type in a terminal to do it yourself, in order. */
15
+ commands?: string[];
16
+ /** Write lessons: what the lesson's program prints, worked out by running it on the Thunder engine. */
17
+ output?: string;
12
18
  /** The lesson's code (the first file), or null for lessons with no code. */
13
19
  snippet: { language: string; code: string } | null;
14
20
  /** Every file the lesson shows (a lesson can show the same rule in several languages). */
@@ -32,3 +38,5 @@ export const LEARN_SCHEMA: 'thunder-learn-v1';
32
38
  export function learnThunder(): LearnThunder;
33
39
  /** The lesson sources (code, wording, and the checks that work out each answer). */
34
40
  export const READ_LESSONS: any[];
41
+ /** Part 2, write and run: programs whose answers are worked out by running them (no Python needed). */
42
+ export const WRITE_LESSONS: any[];
package/src/learn.mjs CHANGED
@@ -8,10 +8,14 @@ import { thunderModel, modelText } from './model.mjs';
8
8
  import { plainFromReading, explainPlain } from './plain-contract.mjs';
9
9
  import { sameMeaning } from './same.mjs';
10
10
  import { COMPILER_VERSION } from './emit.mjs';
11
- import { READ_LESSONS } from './learn-lessons.mjs';
11
+ import { READ_LESSONS, WRITE_LESSONS } from './learn-lessons.mjs';
12
+ import { compileCore } from './core/index.mjs';
13
+ import { runInProcess, testInProcess } from './core/engine-core.mjs';
14
+ import { pythonToCore } from './core/from-python.mjs';
15
+ import { explainRun } from './why.mjs';
12
16
 
13
17
  export const LEARN_SCHEMA = 'thunder-learn-v1';
14
- export { READ_LESSONS };
18
+ export { READ_LESSONS, WRITE_LESSONS };
15
19
 
16
20
  const squash = (s) => String(s).replace(/[_\s]/g, '').toLowerCase();
17
21
  const EXT = { python: 'py', typescript: 'ts', javascript: 'js', java: 'java', go: 'go', csharp: 'cs', ruby: 'rb', php: 'php', rust: 'rs', kotlin: 'kt' };
@@ -19,6 +23,7 @@ const MODEL_SHOWS = new Set(['thing', 'flow']);
19
23
 
20
24
  /** What a lesson's quiz checks may look at: only what the compiler produced from the lesson's code. */
21
25
  function lessonContext(lesson) {
26
+ if (lesson.part === 'write') return writeContext(lesson);
22
27
  const files = lesson.files.map((f, i) => ({ path: `lesson${i ? i + 1 : ''}.${EXT[f.language] ?? 'txt'}`, source: f.code }));
23
28
  const readings = lesson.files.map((f) => readCode(f.code, { language: f.language }));
24
29
  const all = readings.flatMap((r) => r.items);
@@ -47,13 +52,40 @@ function lessonContext(lesson) {
47
52
  };
48
53
  }
49
54
 
55
+ /**
56
+ * What a write lesson's quiz may look at: its Thunder program compiled and run on the Thunder engine (no Python, so
57
+ * this works in a browser too), Python read as Core, or an agent's record read by thunder why.
58
+ */
59
+ function writeContext(lesson) {
60
+ const compile = (source, file = 'main.thunder') => compileCore(source, { file });
61
+ const runCore = (source) => {
62
+ const r = compile(source);
63
+ if (!r.ok) return { ok: false, diagnostics: r.diagnostics, stdout: '', stderr: r.diagnostics.map((d) => `${d.code} ${d.message}`).join('\n'), status: 1 };
64
+ return { ok: true, diagnostics: [], ...runInProcess({ entry: r }) };
65
+ };
66
+ const testCore = (source) => {
67
+ const r = compile(source);
68
+ if (!r.ok) throw new Error(r.diagnostics.map((d) => `${d.code} line ${d.line}: ${d.message}`).join('; '));
69
+ return testInProcess({ results: [{ ...r, kind: 'src' }] });
70
+ };
71
+ const file = lesson.files[0];
72
+ const ctx = { compile, runCore, testCore };
73
+ if (file?.language === 'thunder' && !/^\s*Test "/m.test(file.code)) {
74
+ ctx.core = runCore(file.code);
75
+ if (!ctx.core.ok || ctx.core.status !== 0) throw new Error(`the lesson's program does not run cleanly: ${ctx.core.stderr}`);
76
+ }
77
+ if (lesson.asCore) ctx.asCore = pythonToCore(file.code);
78
+ if (lesson.why) ctx.why = explainRun(file.code);
79
+ return ctx;
80
+ }
81
+
50
82
  /**
51
83
  * The tutorial: { schema, languageVersion, lessons }. Each lesson has its idea, a picture to hold in mind, its code
52
84
  * (snippet), the Thunder Text the compiler gives for it, quiz questions whose answers the compiler worked out, and
53
85
  * open questions to think about (reflect).
54
86
  */
55
87
  export function learnThunder() {
56
- const lessons = READ_LESSONS.map((lesson) => {
88
+ const lessons = [...READ_LESSONS, ...WRITE_LESSONS].map((lesson) => {
57
89
  const ctx = lessonContext(lesson);
58
90
  const questions = (lesson.quiz || []).map((q, i) => {
59
91
  const where = `Lesson "${lesson.slug}", question ${i + 1}`;
@@ -66,9 +98,13 @@ export function learnThunder() {
66
98
  const snippets = lesson.files.map((f) => ({ language: f.language, label: f.label, code: f.code }));
67
99
  return {
68
100
  slug: lesson.slug, title: lesson.title, idea: lesson.idea, picture: lesson.picture, part: lesson.part ?? 'read',
101
+ ...(lesson.concept ? { concept: lesson.concept } : {}),
102
+ ...(lesson.commands ? { commands: [...lesson.commands] } : {}),
69
103
  snippet: snippets[0] ? { language: snippets[0].language, code: snippets[0].code } : null,
70
104
  snippets,
71
- thunderText: ctx.text ?? (ctx.texts[0] || null),
105
+ thunderText: ctx.text ?? (ctx.texts?.[0] || null),
106
+ // What the lesson's program prints, worked out by running it (write lessons).
107
+ ...(ctx.core ? { output: ctx.core.stdout } : {}),
72
108
  questions,
73
109
  reflect: lesson.questions.map((q) => ({ prompt: q.q, answer: q.a })),
74
110
  };
package/src/libraries.mjs CHANGED
@@ -75,6 +75,13 @@ const URL_WORDS = (u) => {
75
75
  return /^[A-Za-z_][\w.]*$/.test(t) ? `the ${words(t.split('.').pop()).replace(/\burl\b/, 'URL')}` : 'an address worked out by the code';
76
76
  };
77
77
 
78
+ /** A file path in words: a quoted path as written, a name as "at <name>" ("Reads the file at config path"). */
79
+ const FILE_WORDS = (u) => {
80
+ const t = String(u || '').trim();
81
+ if (/^["'`]/.test(t)) return t.slice(1, -1).replace(/\$\{[^}]*\}/g, '…');
82
+ return /^[A-Za-z_][\w.]*$/.test(t) ? `at ${t.includes('.') ? `the ${words(t.split('.').pop())}` : words(t)}` : 'at a path worked out by the code';
83
+ };
84
+
78
85
  // Spring Data / Rails-style derived query names: findByEmailAndActive -> "whose email is … and active is …".
79
86
  function derivedWhose(name, args) {
80
87
  const m = name.match(/^(?:find|get|read|query|search|stream|count|exists|delete|remove)(?:All|First|Top\d*|One)?By(\w+)$/);
@@ -175,9 +182,9 @@ const CATALOG = [
175
182
  { re: /^json\s*\.\s*Marshal\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON`, does: 'calculate' }) },
176
183
  { re: /^json\s*\.\s*Unmarshal\s*\(\s*[^,]+,\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads the JSON into ${words(m[1])}`, does: 'calculate' }) },
177
184
  { re: /^json\s*\.\s*NewDecoder\s*\(\s*r\.Body\s*\)\s*\.\s*Decode\s*\(\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads what it was sent into ${words(m[1])}`, does: 'calculate' }) },
178
- { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${URL_WORDS(m[2])}`, does: 'find' }) },
179
- { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${URL_WORDS(m[2])}`, does: 'save' }) },
180
- { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${URL_WORDS(m[2])}`, does: 'save' }) },
185
+ { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${FILE_WORDS(m[2])}`, does: 'find' }) },
186
+ { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
187
+ { re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
181
188
  { re: /^(?:Date\.now|datetime\.now|datetime\.utcnow|time\.Now|DateTime\.Now|DateTime\.UtcNow|Instant\.now|LocalDateTime\.now|Time\.now)\s*\(?\s*\)?$/, say: () => ({ says: 'the current time', does: 'calculate', value: true }) },
182
189
  ];
183
190
 
package/src/model.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
3
3
  // and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
4
4
  // them may say more than the model does. Browser-safe: takes [{ path, source }].
5
+ import { readScreens, screenText } from './screens.mjs';
5
6
  import { readCode, INFRA_LANGUAGES } from './read.mjs';
6
7
  import { readableLanguage, readingOf } from './read-repo.mjs';
7
8
  import { plainFromReading, explainPlain } from './plain-contract.mjs';
@@ -59,10 +60,17 @@ function kindWords(type) {
59
60
  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)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
60
61
  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'); }
61
62
  const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
62
- if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ?? `a ${inner}`}, or nothing`; }
63
+ if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ?? withArticle(inner)}, or nothing`; }
63
64
  const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
64
65
  if (map) return 'a lookup table';
65
- return /^[A-Z]/.test(t) ? `a ${t}` : null;
66
+ return /^[A-Z]/.test(t) ? withArticle(t) : null;
67
+ }
68
+
69
+ /** "a" or "an" by the sound of the word: an AgentCheckResult, an Order, a User, an Unknown, a Euro. */
70
+ export function withArticle(w) {
71
+ const t = String(w);
72
+ const an = /^(?:[AEIOaeio]|U(?:n|m|nd|tt|pp)|u(?:n|m)|[FHLMNRSX][A-Z0-9]|[fhlmnrsx](?=[A-Z0-9]))/.test(t) && !/^(?:Eu|eu|Uni|uni|Use|use|Usu|One|one|Ur)/.test(t);
73
+ return `${an ? 'an' : 'a'} ${t}`;
66
74
  }
67
75
 
68
76
  /** C: a function belongs to a struct it takes first (`library_late_fee(const Library *lib, …)`) or is named after. */
@@ -808,6 +816,20 @@ export function thunderModel(files, { name = 'app' } = {}) {
808
816
  const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
809
817
  // The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
810
818
  try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
819
+ // Screens: React and Angular components read as what a person sees and does (src/screens.mjs). Listed only when
820
+ // there are some; the function or class behind each one points to it.
821
+ try {
822
+ const screens = readScreens(files, { members });
823
+ if (screens.length) {
824
+ model.screens = screens;
825
+ for (const sc of screens) {
826
+ const m = members.find((x) => x.file === sc.file && x.name === sc.name);
827
+ if (m) { m.screen = sc.id; sc.member = m.id; }
828
+ const t = things.find((x) => x.file === sc.file && x.name === sc.name);
829
+ if (t) { t.screen = sc.id; sc.thing = t.id; }
830
+ }
831
+ }
832
+ } catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` }); }
811
833
  return model;
812
834
  }
813
835
 
@@ -853,6 +875,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
853
875
  * cannot disagree. Pass the model and an id.
854
876
  */
855
877
  export function modelText(model, id, { note = null, full = false } = {}) {
878
+ const sc = (model.screens ?? []).find((x) => x.id === id);
879
+ if (sc) return screenText(sc);
856
880
  const t = model.things.find((x) => x.id === id);
857
881
  if (t) {
858
882
  const lines = [t.kind === 'resource' ? `Resource ${t.label} (${t.resourceType})` : `${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
@@ -878,7 +902,7 @@ export function modelText(model, id, { note = null, full = false } = {}) {
878
902
 
879
903
  // ── The five reading levels: what each one shows, decided here so every product shows the same thing ─────────
880
904
 
881
- const SYMBOL_OF = { action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
905
+ const SYMBOL_OF = { screen: 'screen', action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
882
906
 
883
907
  const SETTING_WORDS = { parameter: 'given when it starts or is built', variable: 'a variable kept outside the file', secret: 'a secret (only its name is shown)', literal: 'written in the file', computed: 'worked out when it runs' };
884
908
  const APPLIED_WORDS = { parameter: 'given when it is applied', computed: 'worked out when it is applied' };
@@ -1036,6 +1060,17 @@ function detailsFacts(model, member) {
1036
1060
  return { inputs, changes, stops, givesBack, reliesOn, ...(answers ? { answers } : {}), ...(limits ? { limits } : {}), openQuestions };
1037
1061
  }
1038
1062
 
1063
+ /** One reading level of a screen (a React or Angular component): the same five levels as any member. */
1064
+ function screenLevel(lv, sc, model) {
1065
+ const base = { level: lv.id, name: lv.name, question: lv.question };
1066
+ const about = { scope: 'screen', id: sc.id, title: sc.label, symbol: 'screen', file: sc.file, lines: sc.lines, framework: sc.framework, ...(sc.selector ? { selector: sc.selector } : {}) };
1067
+ if (lv.id === 'big-picture') return { ...base, ...about, inputs: sc.inputs, state: sc.state, outputs: sc.outputs, ...(sc.services ? { services: sc.services } : {}), uses: sc.uses, usedBy: sc.usedBy ?? [], events: sc.events.length, notRead: sc.notRead.length };
1068
+ if (lv.id === 'flow') return { ...base, ...about, shows: sc.shows, ...(sc.early ? { early: sc.early } : {}) };
1069
+ if (lv.id === 'details') return { ...base, ...about, inputs: sc.inputs, state: sc.state, events: sc.events, effects: sc.effects, outputs: sc.outputs, notRead: sc.notRead, source: 'Read from code by the Thunder compiler, with no AI.' };
1070
+ if (lv.id === 'text') return { ...base, ...about, text: screenText(sc) };
1071
+ return { ...base, ...about, language: model.files.find((f) => f.path === sc.file)?.language ?? null, ...(sc.template ? { template: sc.template } : {}) };
1072
+ }
1073
+
1039
1074
  /**
1040
1075
  * What one reading level shows: `level` is a LEVELS id (big-picture, flow, details, text, original); `focus` is a
1041
1076
  * Thing or member id, or nothing for the whole model. Flow and Details need an action or rule; without one they
@@ -1044,6 +1079,8 @@ function detailsFacts(model, member) {
1044
1079
  export function readLevel(model, level, focus, { full = false } = {}) {
1045
1080
  const lv = LEVELS.find((l) => l.id === level);
1046
1081
  if (!lv) throw new Error(`Unknown reading level "${level}". Use one of: ${LEVELS.map((l) => l.id).join(', ')}.`);
1082
+ const screen = focus ? (model.screens ?? []).find((x) => x.id === focus) : undefined;
1083
+ if (screen) return screenLevel(lv, screen, model);
1047
1084
  const member = focus ? model.members.find((m) => m.id === focus) : undefined;
1048
1085
  const thing = focus && !member ? model.things.find((t) => t.id === focus) : undefined;
1049
1086
  if (focus && !member && !thing) throw new Error(`Nothing in this model has the id "${focus}".`);
@@ -1062,14 +1099,16 @@ export function readLevel(model, level, focus, { full = false } = {}) {
1062
1099
 
1063
1100
  if (!member && (lv.id === 'flow' || lv.id === 'details')) {
1064
1101
  const inScope = model.members.filter((m) => m.kind !== 'setup' && (!thing || m.owner === thing.id));
1065
- return { ...base, ...about, needsFocus: true, says: `${lv.name} shows one action or rule. Choose one.`, choose: inScope.map(short) };
1102
+ const screens = thing ? [] : (model.screens ?? []).map((x) => ({ id: x.id, label: x.label, symbol: 'screen' }));
1103
+ return { ...base, ...about, needsFocus: true, says: `${lv.name} shows one ${screens.length ? 'screen, action, or rule' : 'action or rule'}. Choose one.`, choose: [...screens, ...inScope.filter((m) => !m.screen).map(short)] };
1066
1104
  }
1067
1105
  if (lv.id === 'big-picture') {
1068
1106
  if (member) {
1069
1107
  return { ...base, ...about, ...(member.route ? { route: member.route } : {}), ...(member.doc ? { doc: member.doc } : {}),
1070
1108
  ...(owner ? { owner: { id: owner.id, label: owner.label } } : {}), youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), uses, usedBy };
1071
1109
  }
1072
- const inScope = (m) => m.kind !== 'setup' && (thing ? m.owner === thing.id : true);
1110
+ // (A screen's function or class is listed once, as the screen.)
1111
+ const inScope = (m) => m.kind !== 'setup' && (thing ? m.owner === thing.id : !m.screen);
1073
1112
  const resourceCard = (t) => ({ id: t.id, label: t.label, symbol: 'resource', resourceType: t.resourceType, address: t.address, file: t.file,
1074
1113
  knows: t.knows.map((k) => ({ label: k.label, value: k.kind, ...(k.computed ? { computed: true } : {}), ...(k.secret ? { secret: true } : {}), line: k.line })),
1075
1114
  links: (model.links || []).filter((l) => l.from === t.id || l.to === t.id).map((l) => ({ from: l.from, to: l.to, kind: l.kind, ...(l.line ? { line: l.line } : {}) })) });
@@ -1077,15 +1116,17 @@ export function readLevel(model, level, focus, { full = false } = {}) {
1077
1116
  const thingCard = (t) => ({ id: t.id, label: t.label, ...(t.doc ? { doc: t.doc } : {}), knows: t.knows.map((k) => ({ label: k.label, ...(k.start ? { start: k.start } : {}) })), can: model.members.filter((m) => m.owner === t.id && m.kind !== 'setup' && !m.callback).map(short) });
1078
1117
  return { ...base, ...about,
1079
1118
  ...(thing?.doc ?? model.files[0]?.purpose ? { purpose: thing?.doc ?? model.files[0]?.purpose } : {}),
1080
- things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing')).map(thingCard),
1119
+ things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing' && !t.screen)).map(thingCard),
1081
1120
  resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === 'resource')).map(resourceCard),
1082
1121
  ...(thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] }),
1083
1122
  data: thing ? [] : model.things.filter((t) => t.kind !== 'thing' && t.kind !== 'resource').map((t) => ({ id: t.id, label: t.label, symbol: SYMBOL_OF[t.kind], ...(t.choices.length ? { choices: t.choices } : {}), knows: t.knows.map((k) => k.label) })),
1084
1123
  actions: model.members.filter((m) => inScope(m) && m.kind === 'action').map(short),
1085
1124
  rules: model.members.filter((m) => inScope(m) && m.kind === 'rule').map(short),
1086
1125
  // (A callback is reached from the step that passes it, not listed on its own.)
1087
- loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
1126
+ loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && !m.screen && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
1088
1127
  unknowns: thing ? [] : model.unknowns,
1128
+ // The app's screens (React and Angular components), and the screens and components each one shows.
1129
+ ...(!thing && model.screens?.length ? { screens: [...model.screens].sort((x, y) => ['page', 'top', 'part'].indexOf(x.role) - ['page', 'top', 'part'].indexOf(y.role)).map((x) => ({ id: x.id, label: x.label, framework: x.framework, file: x.file, ...(x.selector ? { selector: x.selector } : {}), ...(x.role ? { role: x.role } : {}), uses: x.uses.map((u) => u.label) })) } : {}),
1089
1130
  // The app's map: which areas (folders) call which, and send requests or events to which.
1090
1131
  ...(thing ? {} : { calls: callsSummary(model), notLinked: model.notLinked ?? [] }) };
1091
1132
  }
@@ -1103,7 +1144,8 @@ export function readLevel(model, level, focus, { full = false } = {}) {
1103
1144
  const extra = [];
1104
1145
  if (!focus && model.permissions?.length) extra.push(`Permissions\n${model.permissions.map((p) => ` ${p.says ?? `${p.who} can ${p.can} ${p.on}`}${p.wide && !/\(wide\)/.test(p.says ?? '') ? ' (wide)' : ''} (line ${p.line})`).join('\n')}\n`);
1105
1146
  if (!focus && model.settings?.length) extra.push(`Settings\n${model.settings.map((x) => ` Setting ${x.name}: ${settingWords(x, model)} (line ${x.line})`).join('\n')}\n`);
1106
- const text = focus ? modelText(model, focus, { full }) : [...model.things.map((t) => modelText(model, t.id)), ...model.members.filter((m) => !m.owner && m.kind !== 'setup').map((m) => modelText(model, m.id, { full })), ...extra].join('\n');
1147
+ // The whole app: its screens first (as screens, not as the classes behind them), then everything else.
1148
+ const text = focus ? modelText(model, focus, { full }) : [...(model.screens ?? []).map((sc) => screenText(sc)), ...model.things.filter((t) => !t.screen).map((t) => modelText(model, t.id)), ...model.members.filter((m) => !m.owner && m.kind !== 'setup' && !m.screen).map((m) => modelText(model, m.id, { full })), ...extra].join('\n');
1107
1149
  return { ...base, ...about, text };
1108
1150
  }
1109
1151
  return { ...base, ...about, language: (member ?? thing) ? (member?.language ?? model.files.find((f) => f.path === thing.file)?.language ?? null) : (model.files[0]?.language ?? null) };