@skillstech/thunderlang 1.7.0 → 2.0.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 (73) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +15 -3
  3. package/dist/core.cjs +303 -41
  4. package/dist/index.cjs +9906 -1387
  5. package/dist/learn.cjs +1420 -93
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +381 -149
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +320 -6
  10. package/src/core/cli.mjs +60 -8
  11. package/src/core/csharp-run.mjs +2 -2
  12. package/src/core/diagnostics.mjs +9 -0
  13. package/src/core/engine-core.mjs +148 -19
  14. package/src/core/engine-values.mjs +3 -0
  15. package/src/core/engine.mjs +131 -7
  16. package/src/core/from-python.mjs +1 -1
  17. package/src/core/go-run.mjs +5 -3
  18. package/src/core/index.mjs +12 -3
  19. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  20. package/src/core/java-run.mjs +2 -2
  21. package/src/core/kind.mjs +6 -0
  22. package/src/core/lexer.mjs +16 -2
  23. package/src/core/parser.mjs +215 -29
  24. package/src/core/project-root.mjs +18 -0
  25. package/src/core/project.mjs +34 -16
  26. package/src/core/react-run.mjs +2 -2
  27. package/src/core/runtime-go/thunder_runtime.go +310 -2
  28. package/src/core/runtime-python.mjs +365 -3
  29. package/src/core/runtime-typescript.mjs +150 -5
  30. package/src/core/rust/thunder_runtime.rs +1 -0
  31. package/src/core/rust-run.mjs +2 -2
  32. package/src/core/serving.mjs +12 -0
  33. package/src/core/store-format.mjs +110 -0
  34. package/src/core/target-csharp.mjs +14 -0
  35. package/src/core/target-go.mjs +24 -3
  36. package/src/core/target-java.mjs +14 -0
  37. package/src/core/target-python.mjs +46 -5
  38. package/src/core/target-rust.mjs +14 -0
  39. package/src/core/target-typescript.mjs +76 -6
  40. package/src/core/typescript-run.mjs +6 -4
  41. package/src/core-changes-fs.mjs +28 -0
  42. package/src/core-changes.d.mts +67 -0
  43. package/src/core-changes.mjs +603 -0
  44. package/src/core-rules.mjs +146 -0
  45. package/src/core-services.d.mts +4 -0
  46. package/src/core-services.mjs +49 -0
  47. package/src/emit.mjs +3 -3
  48. package/src/evidence-words.d.mts +6 -0
  49. package/src/evidence-words.mjs +47 -0
  50. package/src/evidence.mjs +36 -1
  51. package/src/examples.d.mts +21 -0
  52. package/src/examples.mjs +175 -0
  53. package/src/index.d.ts +19 -0
  54. package/src/index.mjs +8 -1
  55. package/src/learn-lessons.mjs +1 -1
  56. package/src/lsp.mjs +110 -0
  57. package/src/mcp.mjs +47 -12
  58. package/src/obligations.d.mts +5 -0
  59. package/src/obligations.mjs +30 -2
  60. package/src/program.d.mts +7 -0
  61. package/src/program.mjs +7 -0
  62. package/src/read-repo-fs.mjs +2 -1
  63. package/src/review.mjs +75 -6
  64. package/src/same.mjs +16 -6
  65. package/src/scan-queries.mjs +2 -1
  66. package/src/symbols.d.mts +23 -0
  67. package/src/symbols.mjs +351 -0
  68. package/src/system.mjs +1 -1
  69. package/src/template.d.mts +31 -0
  70. package/src/template.mjs +189 -0
  71. package/src/trace-cli.mjs +8 -3
  72. package/src/trace-fs.mjs +29 -3
  73. package/src/trace.mjs +23 -7
@@ -0,0 +1,110 @@
1
+ // The file a stored list is saved in (Store habits as a list of Habit -> data/habits.json): a JSON list of objects,
2
+ // one per record, each field written by its kind so the file says exactly what the value is:
3
+ // whole number -> a JSON integer (text when too large for one) number -> text ("2.5", exact)
4
+ // money -> text ("1.50", the amount, exact) text -> text yes/no -> true/false date -> "2026-11-27"
5
+ // or nothing -> null
6
+ // The same format on every target (the Thunder engine here; runtime-python's load/save mirror it), so a program's
7
+ // data means the same whichever language runs it. Browser-safe: reading and writing the file is the caller's job.
8
+
9
+ import { Dec, Money, PyDate, RecordVal, PyDict, Tuple, ConversionFailed, KindMismatch, show } from './engine-values.mjs';
10
+
11
+ const kindWords = { whole: 'a whole number', number: 'a number', money: 'money', text: 'text', bool: 'yes or no', date: 'a date' };
12
+
13
+ function encode(v, t) {
14
+ if (t.k === 'optional') return v === null || v === undefined ? null : encode(v, t.of);
15
+ if (v === null || v === undefined) return null;
16
+ switch (t.k) {
17
+ case 'whole': return typeof v === 'bigint' && v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
18
+ case 'number': return String(v);
19
+ case 'money': return v instanceof Money ? v.toString().replace('$', '') : String(v);
20
+ case 'date': return v instanceof PyDate ? v.iso() : String(v);
21
+ default: return v;
22
+ }
23
+ }
24
+
25
+ function decode(x, t, where, has = 'the file has') {
26
+ if (t.k === 'optional') return x === null ? null : decode(x, t.of, where, has);
27
+ const bad = () => ConversionFailed(`${where} should be ${kindWords[t.k] ?? 'a value'}, but ${has} ${JSON.stringify(x)}.`);
28
+ switch (t.k) {
29
+ case 'whole': if (typeof x === 'number' && Number.isInteger(x)) return BigInt(x); if (typeof x === 'string' && /^-?\d+$/.test(x)) return BigInt(x); throw bad();
30
+ case 'number': { if (typeof x === 'number' && Number.isInteger(x)) return BigInt(x); const d = typeof x === 'string' ? Dec.parse(x) : null; if (!d) throw bad(); return /^-?\d+$/.test(x) ? BigInt(x) : d; }
31
+ case 'money': { const d = typeof x === 'string' ? Dec.parse(x) : typeof x === 'number' ? Dec.parse(String(x)) : null; if (!d) throw bad(); return new Money(d); }
32
+ case 'text': if (typeof x === 'string') return x; throw bad();
33
+ case 'bool': if (typeof x === 'boolean') return x; throw bad();
34
+ case 'date': { const d = typeof x === 'string' ? PyDate.parse(x) : null; if (!d) throw bad(); return d; }
35
+ default: return x;
36
+ }
37
+ }
38
+
39
+ /** A stored list as the text of its file. `cls` is the record kind (its fields carry their kinds). */
40
+ export function storeToText(list, cls) {
41
+ const rows = list.map((rec) => Object.fromEntries(cls.fields.map((f) => [f.py, encode(rec.f.get(f.py), f.type ?? { k: 'text' })])));
42
+ return `${JSON.stringify(rows, null, 2)}\n`;
43
+ }
44
+
45
+ /**
46
+ * The records in a store's file. `name` is the file's name as a person sees it (data/habits.json); `make(given)`
47
+ * builds a record from a Map of field values (so the record's Never rules are checked, as in the program).
48
+ */
49
+ export function storeFromText(text, cls, name, make) {
50
+ let rows;
51
+ try { rows = JSON.parse(text); } catch (e) { throw ConversionFailed(`${name} is not a list Thunder can read (${e.message}).`); }
52
+ if (!Array.isArray(rows)) throw ConversionFailed(`${name} should hold a list, written [ … ].`);
53
+ return rows.map((row, i) => recordFrom(row, cls, `${name}, item ${i + 1}`, make));
54
+ }
55
+
56
+ /** A record from a JSON object, each field read by its kind; a problem says where it is and which field. */
57
+ export function recordFrom(row, cls, where, make, has = 'the file has') {
58
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw ConversionFailed(`${where} should be a record, written { … }.`);
59
+ const given = new Map();
60
+ for (const f of cls.fields) {
61
+ const t = f.type ?? { k: 'text' };
62
+ if (!(f.py in row)) { if (t.k === 'optional') { given.set(f.py, null); continue; } throw ConversionFailed(`${where} has no "${f.py}".`); }
63
+ given.set(f.py, decode(row[f.py], t, `${where}, "${f.py}"`, has));
64
+ }
65
+ return make(given);
66
+ }
67
+
68
+ /** A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false. */
69
+ export function inputValue(raw, t, where, fromText) {
70
+ const plain = t.k === 'optional' ? t.of : t;
71
+ if (fromText && plain.k === 'bool' && typeof raw === 'string' && /^(yes|no|true|false)$/i.test(raw)) raw = /^(yes|true)$/i.test(raw);
72
+ return decode(raw, t, where, 'the request has');
73
+ }
74
+
75
+ /**
76
+ * A value as JSON data (HTTP answers and requests), written by its kind as in a stored list: whole numbers as
77
+ * numbers (text when too large), numbers and money as exact text, dates as "2026-11-28", records as objects.
78
+ */
79
+ export function dataReady(v) {
80
+ if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'string') return v ?? null;
81
+ if (typeof v === 'bigint') return v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
82
+ if (v instanceof Dec) return String(v);
83
+ if (v instanceof Money) return v.toString().replace('$', '');
84
+ if (v instanceof PyDate) return v.iso();
85
+ if (Array.isArray(v)) return v.map(dataReady);
86
+ if (v instanceof Tuple) return v.items.map(dataReady);
87
+ if (v instanceof PyDict) {
88
+ const out = {};
89
+ for (const [k, x] of v.m.values()) { if (typeof k !== 'string') throw KindMismatch(`A JSON object's keys are text, but one is ${show(k)}.`); out[k] = dataReady(x); }
90
+ return out;
91
+ }
92
+ if (v instanceof RecordVal) {
93
+ // An alternative of a data type: "which" and the fields it has, not the other alternatives' fields.
94
+ const keep = v.cls.alts ? ['which', ...(v.cls.alts[v.f.get('which')] ?? [])] : v.cls.fields.map((f) => f.py);
95
+ return Object.fromEntries(keep.map((py) => [py, dataReady(v.f.get(py))]));
96
+ }
97
+ throw KindMismatch(`${show(v)} can't be sent as JSON.`);
98
+ }
99
+ export const dataJson = (v) => JSON.stringify(dataReady(v));
100
+
101
+ /** Why a service could not be reached, in words that are the same on every target ({ error: code, name } from fetch). */
102
+ export function unreachableReason(out) {
103
+ if (out.name === 'TimeoutError' || out.name === 'AbortError') return 'no answer within 30 seconds';
104
+ if (out.error === 'ECONNREFUSED') return 'nothing is answering there';
105
+ if (out.error === 'ENOTFOUND' || out.error === 'EAI_AGAIN') return 'the address could not be found';
106
+ return out.error;
107
+ }
108
+
109
+ export const storeFile = (s) => `data/${s.py.toLowerCase()}.json`;
110
+ export { RecordVal };
@@ -336,6 +336,20 @@ class Gen {
336
336
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
337
337
  const v = this.fresh('v'), t = this.fresh('t');
338
338
  const head = `object ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
339
+ if (s.guard) {
340
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
341
+ const n = this.fresh('new');
342
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
343
+ if (isName) {
344
+ this.line(L, `{ ${head} object ${n} = T.copyList(${t}); ${op}`);
345
+ this.ind++;
346
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${cs(rule.text)}, ${rule.line}, ${n});`, L);
347
+ this.emit(`${id(py)} = ${n}; }`, L);
348
+ this.ind--;
349
+ this.rulesAfter(s, py);
350
+ } else this.line(L, `{ ${head} object ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
351
+ return;
352
+ }
339
353
  let body;
340
354
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
341
355
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -90,6 +90,13 @@ class Gen {
90
90
  this.emit('}');
91
91
  }
92
92
  for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
93
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime Run).
94
+ const stores = (this.info.stores ?? []).filter(own);
95
+ if (stores.length) {
96
+ this.blank();
97
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
98
+ for (const s of stores) this.emit(`var ${this.g(s.py)} = T.NewStore(${this.file}, ${s.line}, ${goStr(s.py.toLowerCase())}, ${this.g(s.record.py)}, []T.StoreField{${s.record.fields.map((f) => `{Py: ${goStr(f.py)}, Kind: ${goStr(kind(f.type))}}`).join(', ')}})`, s.line);
99
+ }
93
100
  const consts = this.info.consts.filter(own);
94
101
  this.blank();
95
102
  for (const k of consts) this.emit(`var ${this.g(k.py)} T.V`, k.line);
@@ -201,7 +208,7 @@ class Gen {
201
208
  }
202
209
  };
203
210
  visit(body);
204
- const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
211
+ const globals = new Set([...this.info.consts, ...(this.info.stores ?? []), ...this.info.funcs, ...this.info.records].map((x) => x.py));
205
212
  return [...names].filter((n) => !globals.has(n));
206
213
  }
207
214
 
@@ -371,6 +378,20 @@ class Gen {
371
378
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
372
379
  const v = this.fresh('v'), t = this.fresh('t');
373
380
  const head = `${v} := ${this.x(s.e)}; ${t} := ${this.x(s.target)}`;
381
+ if (s.guard) {
382
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
383
+ const n = this.fresh('new');
384
+ const op = s.k === 'add' ? `T.AppendTo(${n}, ${v})` : `T.RemoveFrom(${n}, ${v})`;
385
+ if (isName) {
386
+ this.line(L, `{ ${head}; ${n} := T.CopyList(${t}); ${op}`);
387
+ this.ind++;
388
+ for (const rule of s.rules) this.emit(`T.Never(${this.x(rule.rule.cond, { subject: n })}, ${goStr(rule.text)}, ${rule.line}, ${n})`, L);
389
+ this.emit(`${this.nameOf(py)} = ${n} }`, L);
390
+ this.ind--;
391
+ this.rulesAfter(s, py);
392
+ } else this.line(L, `{ ${head}; ${n} := T.CopyList(${t}); ${op}; ${this.storeCode(s.target, n)} }`);
393
+ return;
394
+ }
374
395
  let body;
375
396
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.AppendTo(${t}, ${v})` : `T.RemoveFrom(${t}, ${v})`;
376
397
  else if (s.targetKind === 'map') body = `T.RemoveFrom(${t}, ${v})`;
@@ -536,14 +557,14 @@ const own = (r) => (s) => !r.info.imported?.has(s);
536
557
  */
537
558
  export function goNamespaces(results) {
538
559
  const defs = new Map();
539
- for (const r of results) for (const s of [...r.info.records, ...r.info.funcs, ...r.info.consts].filter(own(r))) (defs.get(s.py) ?? defs.set(s.py, []).get(s.py)).push(r.module);
560
+ for (const r of results) for (const s of [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.stores ?? [])].filter(own(r))) (defs.get(s.py) ?? defs.set(s.py, []).get(s.py)).push(r.module);
540
561
  const goName = (module, py) => ((defs.get(py)?.length ?? 0) > 1 ? `${module}_${py}` : id(py));
541
562
  const out = new Map();
542
563
  for (const r of results) {
543
564
  const visible = new Map();
544
565
  const funcs = new Map();
545
566
  const take = (x) => {
546
- for (const s of [...x.info.records, ...x.info.funcs, ...x.info.consts].filter(own(x))) visible.set(s.py, goName(x.module, s.py));
567
+ for (const s of [...x.info.records, ...x.info.funcs, ...x.info.consts, ...(x.info.stores ?? [])].filter(own(x))) visible.set(s.py, goName(x.module, s.py));
547
568
  for (const f of x.info.funcs.filter(own(x))) funcs.set(f.py, f.params.length);
548
569
  };
549
570
  // A test file sees every src file's names (as the Python target's `from <module> import *`), later ones winning.
@@ -420,6 +420,20 @@ class Gen {
420
420
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
421
421
  const v = this.fresh('v'), t = this.fresh('t');
422
422
  const head = `Object ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
423
+ if (s.guard) {
424
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
425
+ const n = this.fresh('new');
426
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
427
+ if (isName) {
428
+ this.line(L, `{ ${head} Object ${n} = T.copyList(${t}); ${op}`);
429
+ this.ind++;
430
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${javaString(rule.text)}, ${rule.line}, ${n});`, L);
431
+ this.emit(`${this.lv(py)} = ${n}; }`, L);
432
+ this.ind--;
433
+ this.rulesAfter(s, py);
434
+ } else this.line(L, `{ ${head} Object ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
435
+ return;
436
+ }
423
437
  let body;
424
438
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
425
439
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -61,6 +61,13 @@ class Gen {
61
61
  for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
62
62
  const consts = this.info.consts.filter(own);
63
63
  if (consts.length) { this.blank(); for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line); }
64
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime run()).
65
+ const stores = (this.info.stores ?? []).filter(own);
66
+ if (stores.length) {
67
+ this.blank();
68
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
69
+ for (const s of stores) this.emit(`${s.py} = ${this.R('new_store')}(THUNDER_SOURCE, ${s.line}, ${py(s.py.toLowerCase())}, ${s.record.py}, {${s.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(', ')}})`, s.line);
70
+ }
64
71
  const tests = this.info.tests;
65
72
  for (const t of tests) {
66
73
  this.blank();
@@ -73,14 +80,27 @@ class Gen {
73
80
  for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
74
81
  this.emit(']');
75
82
  }
83
+ // Endpoints (When someone calls …): the routes the server answers, each with its inputs (name, kind, where from).
84
+ const endpoints = (this.info.endpoints ?? []).filter(own);
85
+ if (endpoints.length) {
86
+ this.blank();
87
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
88
+ this.emit('THUNDER_ROUTES = [');
89
+ for (const f of endpoints) {
90
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
91
+ const ins = f.params.map((p) => `(${py(p.text)}, ${py(p.py)}, ${py(kind(p.type))}, ${fromPath.has(p.name) ? '"path"' : '"request"'}, ${p.dflt ? 'True' : 'False'})`);
92
+ this.emit(` (${py(f.endpoint.method)}, ${py(f.endpoint.path)}, ${f.py}, [${ins.join(', ')}]),`, f.line);
93
+ }
94
+ this.emit(']');
95
+ }
76
96
  const main = this.p.main ?? [];
77
97
  this.blank();
78
- if (main.length) {
98
+ if (main.length || endpoints.length) {
79
99
  this.emit('def main():');
80
- this.ind++; this.block(main); this.ind--;
100
+ this.ind++; if (main.length) this.block(main); else this.emit('pass'); this.ind--;
81
101
  this.blank();
82
102
  this.emit('if __name__ == "__main__":');
83
- this.emit(` ${this.R('run')}(main, __file__)`);
103
+ this.emit(` ${this.R('run')}(main, __file__${endpoints.length ? ', routes=THUNDER_ROUTES' : ''})`);
84
104
  }
85
105
  body.push(...this.out);
86
106
 
@@ -115,6 +135,8 @@ class Gen {
115
135
  this.emit(`${f.py}: ${t}${dflt}`, f.line);
116
136
  }
117
137
  if (!r.fields.length) this.emit('pass');
138
+ // A data type with alternatives: each alternative's own fields, so JSON carries only the fields it has.
139
+ if (r.alts) this.emit(`__thunder_alts__ = {${r.alts.map((a) => `${py(a.name)}: (${a.fields.map((f) => `${py(f.py)}, `).join('')})`).join(', ')}}`, r.line);
118
140
  const rules = r.rulesToCheck ?? [];
119
141
  if (rules.length) {
120
142
  this.out.push('');
@@ -205,8 +227,13 @@ class Gen {
205
227
  this.store(t, v, L);
206
228
  return;
207
229
  }
208
- case 'give': this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
209
- case 'stop': this.emit(`raise ${this.R('Stop')}(${s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`})`, L); return;
230
+ case 'give':
231
+ if (s.status != null) this.emit(`${this.R('answer_status')}(${s.status})`, L);
232
+ this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
233
+ case 'stop': {
234
+ const msg = s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`;
235
+ this.emit(s.status != null ? `raise ${this.R('stop_with')}(${msg}, ${s.status})` : `raise ${this.R('Stop')}(${msg})`, L); return;
236
+ }
210
237
  case 'if':
211
238
  s.branches.forEach((b, k) => {
212
239
  this.emit(`${k === 0 ? 'if' : 'elif'} ${this.yn(b.cond).c}:`, b.line);
@@ -240,6 +267,14 @@ class Gen {
240
267
  case 'add': case 'remove': {
241
268
  const v = this.x(s.e).c;
242
269
  const target = this.lv(s.target);
270
+ if (s.guard) {
271
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
272
+ const copy = `_copy_${s.line}_`;
273
+ this.emit(`${copy} = list(${target})`, L);
274
+ this.emit(s.k === 'add' ? `${copy}.append(${v})` : `${this.R('remove_from')}(${copy}, ${v})`, L);
275
+ if (s.target.k === 'name') this.assign(s, target, copy); else this.store(s.target, copy, L);
276
+ return;
277
+ }
243
278
  if (s.targetKind === 'list') this.emit(s.k === 'add' ? `${target}.append(${v})` : `${this.R('remove_from')}(${target}, ${v})`, L);
244
279
  else if (s.targetKind === 'map') this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
245
280
  else if (s.targetKind === 'number') { if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'add' ? '+' : '-'} ${v}`); return; } this.emit(`${target} ${s.k === 'add' ? '+' : '-'}= ${v}`, L); }
@@ -357,6 +392,12 @@ class Gen {
357
392
  case 'bool': return A(e.v ? 'True' : 'False');
358
393
  case 'nothing': return A('None');
359
394
  case 'paren': return sub(e.e);
395
+ // the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
396
+ case 'httpCall': {
397
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
398
+ const as = e.record ? `(${e.record.py}, {${e.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(', ')}}, ${e.as.k === 'list' ? 'True' : 'False'})` : 'None';
399
+ return A(`${this.R('http_call')}(${py(e.method)}, ${sub(e.url).c}, ${e.body ? sub(e.body).c : 'None'}, ${as})`);
400
+ }
360
401
  case 'today': this.needDate = true; return A('date.today()');
361
402
  case 'date': this.needDate = true; return A(`date.fromisoformat(${py(e.text)})`);
362
403
  case 'str': return A(this.str(e, ctx));
@@ -375,6 +375,20 @@ class Gen {
375
375
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
376
376
  const v = this.fresh('v'), t = this.fresh('t');
377
377
  const head = `let ${v} = ${this.x(s.e)}; let ${t} = ${this.x(s.target)};`;
378
+ if (s.guard) {
379
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
380
+ const n = this.fresh('new');
381
+ const op = s.k === 'add' ? `T::append_to(${n}.clone(), ${v});` : `T::remove_from(${n}.clone(), ${v});`;
382
+ if (isName) {
383
+ this.line(L, `{ ${head} let ${n} = T::copy_list(${t}); ${op}`);
384
+ this.ind++;
385
+ for (const rule of s.rules) this.emit(`T::never(${this.x(rule.rule.cond, { subject: `${n}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${n}.clone());`, L);
386
+ this.emit(`${id(py)} = ${n}; }`, L);
387
+ this.ind--;
388
+ this.rulesAfter(s, py);
389
+ } else this.line(L, `{ ${head} let ${n} = T::copy_list(${t}); ${op} ${this.storeCode(s.target, n)} }`);
390
+ return;
391
+ }
378
392
  let body;
379
393
  if (s.targetKind === 'list') body = s.k === 'add' ? `T::append_to(${t}, ${v});` : `T::remove_from(${t}, ${v});`;
380
394
  else if (s.targetKind === 'map') body = `T::remove_from(${t}, ${v});`;
@@ -75,6 +75,24 @@ export function dotnetRefusals(info, targetName, diag) {
75
75
  'Build for C# to use .NET libraries: --target csharp, or target = "csharp" under [build] in thunder.toml. Thunder never swaps in a different library.'));
76
76
  }
77
77
 
78
+ /** TC411 for endpoints and calls to other services: HTTP runs on Python, TypeScript, and the Thunder engine for now. */
79
+ export function httpRefusals(info, targetName, diag) {
80
+ const own = (s) => !info.imported?.has(s);
81
+ const out = (info.endpoints ?? []).filter(own).map((f) => diag('TC411', f.line,
82
+ `"${f.text}" is an endpoint, and HTTP works only on Python, TypeScript, and the Thunder engine for now, not on ${targetName}.`,
83
+ 'Run it with Python (the default target), --target typescript, or --engine thunder.'));
84
+ if (info.usesHttp && !out.length) out.push(diag('TC411', 1, `This program calls another service ("the answer from …"), and HTTP works only on Python, TypeScript, and the Thunder engine for now, not on ${targetName}.`,
85
+ 'Run it with Python (the default target), --target typescript, or --engine thunder.'));
86
+ return out;
87
+ }
88
+
89
+ /** TC410 for every stored list (Store … as a list of …) when compiling for `target`: saved data runs on Python, TypeScript, Go, and the Thunder engine for now. */
90
+ export function storeRefusals(info, targetName, diag) {
91
+ return (info.stores ?? []).filter((s) => !info.imported?.has(s)).map((s) => diag('TC410', s.line,
92
+ `"${s.text}" is a stored list, and saved data works only on Python, TypeScript, Go, and the Thunder engine for now, not on ${targetName}.`,
93
+ 'Run it with Python (the default target), --target typescript, --target go, or --engine thunder. Thunder never swaps in a different way of saving.'));
94
+ }
95
+
78
96
  /** The name of an npm package's namespace import (import * as <it> from "<package>"). */
79
97
  const npmNs = (m) => `$npm_${m.py}`;
80
98
 
@@ -114,6 +132,13 @@ export class Gen {
114
132
  this.ind--;
115
133
  this.emit('});');
116
134
  }
135
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime run()).
136
+ const stores = (this.info.stores ?? []).filter(own);
137
+ if (stores.length) {
138
+ this.blank();
139
+ const kind = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${kind(t.of)} }` : `{ k: ${js(t.k)} }`);
140
+ for (const s of stores) this.emit(`export const ${id(s.py)}: any = T.newStore(FILE, ${s.line}, ${js(s.py.toLowerCase())}, ${id(s.record.py)}, [${s.record.fields.map((f) => `{ py: ${js(f.py)}, type: ${kind(f.type)} }`).join(', ')}]);`, s.line);
141
+ }
117
142
  const tests = this.info.tests;
118
143
  for (const t of tests) {
119
144
  this.blank();
@@ -127,21 +152,40 @@ export class Gen {
127
152
  this.emit('export const THUNDER_TESTS: [string, () => void, number][] = [');
128
153
  for (const t of tests) this.emit(` [${js(t.title)}, ${id(t.py)}, ${t.line}],`);
129
154
  this.emit('];');
155
+ // Endpoints (When someone calls …): the routes the server answers, each with its inputs and where they come from.
156
+ const endpoints = (this.info.endpoints ?? []).filter(own);
157
+ const tyOf = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${tyOf(t.of)} }` : `{ k: ${js(t.k)} }`);
158
+ if (endpoints.length) {
159
+ this.blank();
160
+ this.emit('export const THUNDER_ROUTES: any[] = [');
161
+ for (const f of endpoints) {
162
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
163
+ const ins = f.params.map((p) => `{ text: ${js(p.text)}, py: ${js(p.py)}, type: ${tyOf(p.type)}, path: ${fromPath.has(p.name)}, dflt: ${!!p.dflt} }`);
164
+ this.emit(` { method: ${js(f.endpoint.method)}, path: ${js(f.endpoint.path)}, handler: ${id(f.py)}, inputs: [${ins.join(', ')}] },`, f.line);
165
+ }
166
+ this.emit('];');
167
+ }
130
168
  const main = this.p.main ?? [];
131
- if (main.length) {
169
+ if (main.length || endpoints.length) {
132
170
  this.blank();
133
171
  this.emit('export function main(): void {');
134
172
  this.ind++;
135
- this.frameBody('T.enterFrame(FILE, 0)', main, [], true);
173
+ if (main.length) this.frameBody('T.enterFrame(FILE, 0)', main, [], true);
136
174
  this.ind--;
137
175
  this.emit('}');
138
176
  this.blank();
139
- this.emit('if (T.isEntry(import.meta.url)) T.run(main);');
177
+ this.emit(`if (T.isEntry(import.meta.url)) T.run(main${endpoints.length ? ', THUNDER_ROUTES' : ''});`);
140
178
  }
141
179
  return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
142
180
  }
143
181
 
144
182
  record(r) {
183
+ this.recordKind(r);
184
+ // A data type with alternatives: each alternative's own fields, so JSON carries only the fields it has.
185
+ if (r.alts) this.emit(`(${id(r.py)} as any).alts = {${r.alts.map((a) => `${js(a.name)}: [${a.fields.map((f) => js(f.py)).join(', ')}]`).join(', ')}};`, r.line);
186
+ }
187
+
188
+ recordKind(r) {
145
189
  const fields = r.fields.map((f) => `{ py: ${js(f.py)}, type: { k: ${js(f.type?.k ?? 'any')} } }`).join(', ');
146
190
  const rules = r.rulesToCheck ?? [];
147
191
  if (!rules.length) { this.emit(`export const ${id(r.py)} = T.recordKind(${js(r.py)}, [${fields}]);`, r.line); return; }
@@ -206,7 +250,7 @@ export class Gen {
206
250
  }
207
251
  };
208
252
  visit(body);
209
- const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
253
+ const globals = new Set([...this.info.consts, ...(this.info.stores ?? []), ...this.info.funcs, ...this.info.records].map((x) => x.py));
210
254
  return [...names].filter((n) => !globals.has(n));
211
255
  }
212
256
 
@@ -251,8 +295,14 @@ export class Gen {
251
295
  this.line(L, `{ const ${v} = ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
252
296
  return;
253
297
  }
254
- case 'give': this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
255
- case 'stop': { const v = this.x(s.e); this.line(L, `throw T.Stop(${s.e.type?.k === 'text' ? `T.pyStr(${v})` : `T.show(${v})`});`); return; }
298
+ case 'give':
299
+ if (s.status != null) this.line(L, `T.answerStatus(${s.status});`);
300
+ this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
301
+ case 'stop': {
302
+ const v = this.x(s.e);
303
+ const msg = s.e.type?.k === 'text' ? `T.pyStr(${v})` : `T.show(${v})`;
304
+ this.line(L, s.status != null ? `throw T.stopWith(${msg}, ${s.status});` : `throw T.Stop(${msg});`); return;
305
+ }
256
306
  case 'if': {
257
307
  this.emit(`F.line = ${L};`, L);
258
308
  s.branches.forEach((b, k) => {
@@ -349,6 +399,20 @@ export class Gen {
349
399
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
350
400
  const v = this.fresh('v'), t = this.fresh('t');
351
401
  const head = `const ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
402
+ if (s.guard) {
403
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
404
+ const n = this.fresh('new');
405
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
406
+ if (isName) {
407
+ this.line(L, `{ ${head} const ${n} = T.copyList(${t}); ${op}`);
408
+ this.ind++;
409
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${js(rule.text)}, ${rule.line}, ${n});`, L);
410
+ this.emit(`${id(py)} = ${n}; }`, L);
411
+ this.ind--;
412
+ this.rulesAfter(s, py);
413
+ } else this.line(L, `{ ${head} const ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
414
+ return;
415
+ }
352
416
  let body;
353
417
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
354
418
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -412,6 +476,12 @@ export class Gen {
412
476
  case 'bool': return e.v ? 'true' : 'false';
413
477
  case 'nothing': case 'hole': return 'null';
414
478
  case 'paren': return sub(e.e);
479
+ // the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
480
+ case 'httpCall': {
481
+ const tyOf = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${tyOf(t.of)} }` : `{ k: ${js(t.k)} }`);
482
+ const as = e.record ? `{ cls: ${id(e.record.py)}, fields: [${e.record.fields.map((f) => `{ py: ${js(f.py)}, type: ${tyOf(f.type)} }`).join(', ')}], many: ${e.as.k === 'list'} }` : 'null';
483
+ return `T.httpCall(${js(e.method)}, ${sub(e.url)}, ${e.body ? sub(e.body) : 'null'}, ${as})`;
484
+ }
415
485
  case 'today': return 'T.today()';
416
486
  case 'date': return `T.date(${js(e.text)})`;
417
487
  case 'str': return this.str(e, ctx);
@@ -6,6 +6,7 @@
6
6
  import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync } from 'node:fs';
7
7
  import { join, dirname } from 'node:path';
8
8
  import { spawnSync } from 'node:child_process';
9
+ import { spawnServing } from './serving.mjs';
9
10
  import { createRequire } from 'node:module';
10
11
  import { fileURLToPath } from 'node:url';
11
12
  import { toTypeScript, pythonOnlyUses, npmUses, dotnetRefusals } from './target-typescript.mjs';
@@ -13,7 +14,7 @@ import { TS_RUNTIME, TS_RUNTIME_DTS } from './runtime-typescript.mjs';
13
14
  import { diag } from './diagnostics.mjs';
14
15
 
15
16
  /** The names a src file gives a test file (its records, functions, and kept values). */
16
- const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.modules ?? []).filter((m) => m.ecosystem === 'npm')].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
17
+ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.stores ?? []), ...(r.info.modules ?? []).filter((m) => m.ecosystem === 'npm')].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
17
18
 
18
19
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
19
20
  export function typescriptDiagnostics(result) {
@@ -82,11 +83,12 @@ export function typescriptRunner({ nodeVersion = process.versions.node, searchFr
82
83
  * Run a compiled module (`entry`, e.g. "main.ts" or "run_tests.ts") in `outDir`, in the folder `cwd`.
83
84
  * Returns spawnSync's result ({ status, stdout, stderr }), or { status: 2, stderr } when TypeScript cannot run here.
84
85
  */
85
- export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', searchFrom = [] } = {}) {
86
+ export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', searchFrom = [], serving = false } = {}) {
87
+ const run = serving ? spawnServing : spawnSync; // a program with endpoints keeps answering until stopped
86
88
  const runner = typescriptRunner({ searchFrom: [outDir, cwd, ...searchFrom] });
87
89
  if (runner.error) return { status: 2, stdout: '', stderr: `${runner.error}\n`, error: runner.error };
88
90
  const env = { ...process.env, NODE_NO_WARNINGS: '1' };
89
- if (runner.args) return spawnSync(process.execPath, [...runner.args, join(outDir, entry)], { cwd, stdio, encoding: 'utf8', env });
91
+ if (runner.args) return run(process.execPath, [...runner.args, join(outDir, entry)], { cwd, stdio, encoding: 'utf8', env });
90
92
  // Older Node: remove the types with the typescript package, into .run/ next to the TypeScript.
91
93
  const ts = runner.ts;
92
94
  const runDir = join(outDir, '.run');
@@ -97,7 +99,7 @@ export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', sea
97
99
  writeFileSync(join(runDir, f.replace(/\.ts$/, '.mjs')), js.replace(/(from\s+['"]\.\/[^'"]+)\.ts(['"])/g, '$1.mjs$2'));
98
100
  }
99
101
  writeFileSync(join(runDir, 'thunder_runtime.mjs'), readFileSync(join(outDir, 'thunder_runtime.mjs'), 'utf8'));
100
- return spawnSync(process.execPath, [join(runDir, entry.replace(/\.ts$/, '.mjs'))], { cwd, stdio, encoding: 'utf8', env });
102
+ return run(process.execPath, [join(runDir, entry.replace(/\.ts$/, '.mjs'))], { cwd, stdio, encoding: 'utf8', env });
101
103
  }
102
104
 
103
105
  function readdirTs(dir) {
@@ -0,0 +1,28 @@
1
+ // Reading Thunder Core files from disk for core-changes.mjs (which is browser-safe and reads nothing itself).
2
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import { join, relative, sep } from 'node:path';
4
+ import { isCoreProgram } from './core/kind.mjs';
5
+
6
+ const SKIP = new Set(['node_modules', '.git', 'generated', 'data', 'dist', 'build', '.thunder']);
7
+
8
+ /** The Thunder Core programs in a file or folder (recursive), as [{ path, source }] with paths relative to `base`. */
9
+ export function coreFilesIn(target, base = target) {
10
+ const out = [];
11
+ const add = (full) => {
12
+ if (!full.endsWith('.thunder')) return;
13
+ const source = readFileSync(full, 'utf8');
14
+ const path = relative(base, full).split(sep).join('/') || full.split(sep).pop();
15
+ if (isCoreProgram(path, source)) out.push({ path, source });
16
+ };
17
+ const walk = (dir) => {
18
+ for (const name of readdirSync(dir).sort()) {
19
+ if (SKIP.has(name)) continue;
20
+ const full = join(dir, name);
21
+ const st = statSync(full);
22
+ if (st.isDirectory()) walk(full); else add(full);
23
+ if (out.length >= 500) return;
24
+ }
25
+ };
26
+ if (statSync(target).isDirectory()) walk(target); else add(target);
27
+ return out;
28
+ }
@@ -0,0 +1,67 @@
1
+ // Types for core-changes.mjs: behaviour changes in Thunder Core programs, and what to look at again.
2
+
3
+ export const CORE_CHANGES_SCHEMA: 'thunder-core-changes-v1';
4
+ export const AFFECTED_SCHEMA: 'thunder-affected-v1';
5
+
6
+ export interface CoreFile { path: string; source: string }
7
+
8
+ /** A rule another one reaches: where it is, and the rules in between (via). */
9
+ export interface CoreRef { id: string; subject: string; kind: string; file: string; line: number; via?: string[]; test?: 'passes' | 'fails' }
10
+
11
+ export interface CoreBehaviourGroup {
12
+ /** "now a review Refund instead of an approved Refund", or "still a review Refund, but its reason is now …" */
13
+ says: string;
14
+ /** The input that decides it, as the values tried: "amount is from $50.00 to $99.99". Null when no one input does. */
15
+ where: string | null;
16
+ count: number;
17
+ example: string;
18
+ }
19
+
20
+ /** Both versions run on the same inputs: tested evidence on those inputs, not a proof. */
21
+ export type CoreBehaviour = { why: string } | { tried: number; unknown: number; stopped: boolean; changed: number; groups: CoreBehaviourGroup[] };
22
+
23
+ export interface CoreChange {
24
+ /** A stable name from what the rule is: "function:decide refund", "keep:review limit", "endpoint:POST /orders". */
25
+ id: string;
26
+ kind: 'function' | 'endpoint' | 'keep' | 'record' | 'never' | 'store' | 'test' | 'main' | 'file';
27
+ subject: string;
28
+ change: 'added' | 'removed' | 'renamed' | 'changed' | 'affected' | 'not-compiled';
29
+ severity: 'risk' | 'meaning';
30
+ file: string;
31
+ line: number;
32
+ says: string;
33
+ before: string[] | null;
34
+ after: string[] | null;
35
+ behaviour?: CoreBehaviour;
36
+ /** For an affected function: the changed rule it reaches, and the rules in between. */
37
+ through?: string[];
38
+ affects: CoreRef[];
39
+ }
40
+
41
+ export interface CoreChanges {
42
+ schema: 'thunder-core-changes-v1';
43
+ files: string[];
44
+ changes: CoreChange[];
45
+ unchanged: number;
46
+ problems: Array<{ file: string; diagnostics: Array<{ line: number; code: string; message: string }> }>;
47
+ }
48
+
49
+ export interface Affected {
50
+ schema: 'thunder-affected-v1';
51
+ of: CoreRef[];
52
+ unknown: string[];
53
+ functions: CoreRef[];
54
+ endpoints: CoreRef[];
55
+ tests: CoreRef[];
56
+ examples: Array<{ file: string; line: number; test: string; says: string | null; reaches: string }>;
57
+ rules: Array<CoreRef & { usedBy: string }>;
58
+ stored: Array<CoreRef & { usedBy: string }>;
59
+ }
60
+
61
+ export function isCoreProgram(path: string, source: string): boolean;
62
+ export function coreChanges(oldFiles: CoreFile[], newFiles: CoreFile[]): CoreChanges;
63
+ export function affectedBy(files: CoreFile[], change: string | string[]): Affected;
64
+ export function renderAffected(r: Affected): string;
65
+
66
+ /** Thunder Trace impact with what changes in a changed Thunder Core endpoint's answers (`behaviour` on route findings). */
67
+ export function withCoreBehaviour<T extends { findings: unknown[]; note: string }>(impact: T, byRepo: Map<string, CoreChanges>): T;