@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
package/dist/learn.cjs CHANGED
@@ -17253,7 +17253,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
17253
17253
  var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
17254
17254
 
17255
17255
  // src/emit.mjs
17256
- var COMPILER_VERSION = "1.7.0";
17256
+ var COMPILER_VERSION = "2.0.0";
17257
17257
 
17258
17258
  // src/lift.mjs
17259
17259
  var IR_SCHEMA_VERSION = "0.1.0";
@@ -21973,16 +21973,16 @@ function powershellReading(src, file = "") {
21973
21973
  KNOWN_FNS2 = /* @__PURE__ */ new Set();
21974
21974
  return out;
21975
21975
  }
21976
- function psThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
21976
+ function psThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
21977
21977
  const { things } = powershellReading(src, file);
21978
21978
  const norm3 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
21979
21979
  const kind = (t) => {
21980
21980
  const x = String(t ?? "").toLowerCase();
21981
21981
  if (!x) return null;
21982
- if (/\[\]$/.test(x)) return kindWords3(`List<${String(t).slice(0, -2).replace(/^string$/i, "string").replace(/^int$/i, "int")}>`);
21982
+ if (/\[\]$/.test(x)) return kindWords4(`List<${String(t).slice(0, -2).replace(/^string$/i, "string").replace(/^int$/i, "int")}>`);
21983
21983
  if (/(?:arraylist|list|collection|hashset)(?:\[|$)/.test(x)) return "a list";
21984
21984
  if (/^(?:hashtable|dictionary|ordered)/.test(x)) return "a lookup table";
21985
- return kindWords3(/^(int|int32|int64|long|double|decimal|float)$/.test(x) ? "int" : /^(string|char)$/.test(x) ? "string" : /^(bool|boolean|switch)$/.test(x) ? "bool" : /^datetime$/.test(x) ? "DateTime" : String(t).split(".").pop());
21985
+ return kindWords4(/^(int|int32|int64|long|double|decimal|float)$/.test(x) ? "int" : /^(string|char)$/.test(x) ? "string" : /^(bool|boolean|switch)$/.test(x) ? "bool" : /^datetime$/.test(x) ? "DateTime" : String(t).split(".").pop());
21986
21986
  };
21987
21987
  return things.map((t) => ({
21988
21988
  kind: t.kind,
@@ -23551,7 +23551,7 @@ function rReading(src, file = "") {
23551
23551
  KNOWN_FNS3 = /* @__PURE__ */ new Set();
23552
23552
  return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
23553
23553
  }
23554
- function rThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
23554
+ function rThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
23555
23555
  const norm3 = (v) => String(v ?? "").trim().replace(/^(?:list|c|character|numeric|integer|logical|vector)\(\s*(?:0)?\s*\)$/, "[]").replace(/^NULL$/, "null").replace(/^NA$/, "null").replace(/^TRUE$/, "true").replace(/^FALSE$/, "false").replace(/^(\d+)L$/, "$1").replace(/^'(.*)'$/, '"$1"');
23556
23556
  return rReading(src, file).things.map((t) => ({
23557
23557
  kind: t.kind,
@@ -23561,7 +23561,7 @@ function rThings(src, file, { words: w, kindWords: kindWords3, startValue: start
23561
23561
  ...t.doc ? { doc: t.doc } : {},
23562
23562
  choices: t.choices,
23563
23563
  memberRanges: t.memberRanges,
23564
- knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ? kindWords3(k.type) : null, start: k.start == null || k.start === "" ? null : typeof k.start === "object" ? k.start.param == null ? "given when it starts" : `${startValue2(norm3(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm3(k.start)), line: k.line }))
23564
+ knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ? kindWords4(k.type) : null, start: k.start == null || k.start === "" ? null : typeof k.start === "object" ? k.start.param == null ? "given when it starts" : `${startValue2(norm3(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm3(k.start)), line: k.line }))
23565
23565
  }));
23566
23566
  }
23567
23567
 
@@ -28456,9 +28456,9 @@ function goDoc(src, at2, name) {
28456
28456
  const t = d.replace(new RegExp(`^${name}\\s+(?:is|holds|represents)\\s+`), "").replace(new RegExp(`^${name}\\s+`), "");
28457
28457
  return t.charAt(0).toUpperCase() + t.slice(1);
28458
28458
  }
28459
- function makeThingReaders({ words: words13, kindWords: kindWords3, startValue: startValue2 }) {
28459
+ function makeThingReaders({ words: words13, kindWords: kindWords4, startValue: startValue2 }) {
28460
28460
  const know = (name, type, start, params, line = null) => {
28461
- const kind = type ? kindWords3(type) : null;
28461
+ const kind = type ? kindWords4(type) : null;
28462
28462
  const said = start != null && start !== "" ? /^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? "") ? "worked out when it starts" : startValue2(start, params) : null;
28463
28463
  return { name, label: words13(name.replace(/^[_$]+|_$/g, "")), kind, start: said, line };
28464
28464
  };
@@ -34147,6 +34147,18 @@ ${model.settings.map((x) => ` Setting ${x.name}: ${settingWords(x, model)} (li
34147
34147
  return { ...base2, ...about, language: member ?? thing ? member?.language ?? model.files.find((f) => f.path === thing.file)?.language ?? null : model.files[0]?.language ?? null };
34148
34148
  }
34149
34149
 
34150
+ // src/evidence-words.mjs
34151
+ var EVIDENCE_LEVELS = ["proven", "tested", "partial", "unverified", "violated"];
34152
+ function combineEvidence(levels) {
34153
+ const ls = [...levels].filter((l) => EVIDENCE_LEVELS.includes(l));
34154
+ if (!ls.length) return "unverified";
34155
+ if (ls.includes("violated")) return "violated";
34156
+ if (ls.every((l) => l === "proven")) return "proven";
34157
+ if (ls.every((l) => l === "proven" || l === "tested")) return "tested";
34158
+ if (ls.every((l) => l === "unverified")) return "unverified";
34159
+ return "partial";
34160
+ }
34161
+
34150
34162
  // src/same.mjs
34151
34163
  var SAME_SCHEMA = "thunder-same-v1";
34152
34164
  var MAX_CASES = 4096;
@@ -34230,7 +34242,9 @@ function comparePlainRules(a, b) {
34230
34242
  }
34231
34243
  const bAsA = { ...b, inputs: b.inputs.map((i) => ({ ...i, id: toA.get(key(i)) })), rules: b.rules.map((r) => ({ ...r, conditions: r.conditions.map((c) => ({ ...c, input: toA.get(key(b.inputs.find((i) => i.id === c.input))) })) })) };
34232
34244
  let tried = 0;
34233
- for (const values of product(caseValues([a, bAsA]))) {
34245
+ const axes = caseValues([a, bAsA]);
34246
+ const total = axes.reduce((n, [, vs]) => n * Math.max(1, vs.length), 1);
34247
+ for (const values of product(axes)) {
34234
34248
  if (++tried > MAX_CASES) {
34235
34249
  tried--;
34236
34250
  break;
@@ -34238,7 +34252,7 @@ function comparePlainRules(a, b) {
34238
34252
  const x = explainPlain(a, values).outcome, y = explainPlain(bAsA, values).outcome;
34239
34253
  if (x !== y) return { same: false, tried, counterexample: { values: { ...values }, facts: a.inputs.map((i) => `${i.label} ${i.kind === "yesno" ? values[i.id] ? i.yes ?? "yes" : i.no ?? "no" : values[i.id]}`).join(", "), old: x, new: y } };
34240
34254
  }
34241
- return { same: true, tried };
34255
+ return { same: true, tried, total, ...total > tried ? { capped: true } : {} };
34242
34256
  }
34243
34257
  var SYNTAX = new Set("const let var val final auto def fn func function return await async new public private protected static self this my local export mut ref out in of for foreach if elif elsif while do then end each as range".split(" "));
34244
34258
  var OPS4 = { "&&": "and", "||": "or", "!": "not", "===": "==", "!==": "!=", "<>": "!=", "**": "^", and: "and", or: "or", not: "not", is: "==", None: "null", nil: "null", undefined: "null", NULL: "null", nullptr: "null", True: "true", False: "false" };
@@ -34261,7 +34275,7 @@ function compareItems(o, n) {
34261
34275
  if (o.kind === "decision") {
34262
34276
  const r = compareRules(o, n);
34263
34277
  if (!r) return { status: "cannot-check", reason: "One rule could not be drawn as a card, so its answers could not be compared.", ...where2 };
34264
- if (r.same) return { status: "same", reason: `Same answer on all ${r.tried} edge cases.`, ...where2 };
34278
+ if (r.same) return { status: "same", reason: r.capped ? `Same answer on the first ${r.tried} of ${r.total} edge cases (the rest were not tried).` : `Same answer on all ${r.tried} edge cases.`, ...where2 };
34265
34279
  if (r.counterexample) {
34266
34280
  const facts = r.counterexample.facts;
34267
34281
  return { status: "different", reason: `Different answer for ${facts}: ${r.counterexample.old} before, ${r.counterexample.new} after.`, counterexample: r.counterexample, ...where2 };
@@ -34294,9 +34308,13 @@ function sameMeaning(oldFiles, newFiles) {
34294
34308
  }
34295
34309
  for (const [key, n] of B.items) if (!used.has(key)) items.push({ name: n.name, status: "only-new", reason: "New: not in the old code.", new: { file: n.file, line: n.line, language: n.language } });
34296
34310
  const counts = { same: 0, different: 0, "only-old": 0, "only-new": 0, "cannot-check": 0 };
34297
- for (const it of items) counts[it.status]++;
34311
+ for (const it of items) {
34312
+ counts[it.status]++;
34313
+ it.evidence = it.status === "same" ? /edge cases/.test(it.reason) ? "tested" : "partial" : it.status === "cannot-check" ? "unverified" : "violated";
34314
+ }
34298
34315
  const verdict = counts.different || counts["only-old"] || counts["only-new"] ? "different" : counts["cannot-check"] ? "partly-checked" : "same";
34299
- return { schema: SAME_SCHEMA, verdict, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
34316
+ const evidence = combineEvidence(items.map((it) => it.evidence));
34317
+ return { schema: SAME_SCHEMA, verdict, evidence, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
34300
34318
  }
34301
34319
 
34302
34320
  // src/learn-lessons.mjs
@@ -35259,7 +35277,7 @@ var WRITE_LESSONS = [
35259
35277
  prompt: "Every test passed. Does the passport say the change works in production?",
35260
35278
  choices: ["No: deployment is always listed as not verified", "Yes"],
35261
35279
  expect: "No: deployment is always listed as not verified",
35262
- explain: "Tests prove what they ran, on the machine they ran on. How it is deployed, real outside services, more than one machine, and heavy load are listed as not verified unless a claim covers them.",
35280
+ explain: "Tests show what they ran, on the machine they ran on. How it is deployed, real outside services, more than one machine, and heavy load are listed as not verified unless a claim covers them.",
35263
35281
  check: ({ passport }) => passport.unknowns.notVerified.some((x) => /^Deployment/.test(x)) ? "No: deployment is always listed as not verified" : "Yes"
35264
35282
  }
35265
35283
  ],
@@ -35304,12 +35322,25 @@ function lev(a, b) {
35304
35322
  }
35305
35323
 
35306
35324
  // src/core/lexer.mjs
35307
- var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">"];
35325
+ var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">", "?"];
35308
35326
  var WORD_START = /[\p{L}_]/u;
35309
35327
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
35310
35328
  function tokenizeLine(text2, line, colOffset = 0) {
35311
35329
  const toks2 = [];
35312
35330
  let i = 0;
35331
+ const ep = text2.match(/^(when)(\s+)(someone)(\s+)(calls)(\s+)([A-Za-z]+)(\s+)(\/\S*?)(\s*)(:)(\s*(#.*)?)$/i);
35332
+ if (ep) {
35333
+ let col = colOffset + 1;
35334
+ const out = [];
35335
+ const parts = ep.slice(1, 12);
35336
+ parts.forEach((part, k) => {
35337
+ if (k === 8) out.push({ t: "path", text: part, col, line });
35338
+ else if (k === 10) out.push({ t: "sym", text: ":", col, line });
35339
+ else if (part && !/^\s*$/.test(part)) out.push({ t: "word", text: part, lower: part.toLowerCase(), col, line });
35340
+ col += part.length;
35341
+ });
35342
+ return out;
35343
+ }
35313
35344
  const at2 = (k = 0) => text2[i + k];
35314
35345
  while (i < text2.length) {
35315
35346
  const c = at2();
@@ -35614,6 +35645,9 @@ function collectNames(nodes, names) {
35614
35645
  } else if (w0 === "keep") {
35615
35646
  const k = splitTop4(ts, (t) => isWord(t, "at"));
35616
35647
  add2("const", stripArticle(ts.slice(1, k < 0 ? ts.length : k)));
35648
+ } else if (w0 === "store" && ts.some((t) => isWord(t, "as"))) {
35649
+ const k = splitTop4(ts, (t) => isWord(t, "as"));
35650
+ add2("const", stripArticle(ts.slice(1, k)));
35617
35651
  } else if (w0 === "receive") {
35618
35652
  for (const p of paramGroups(ts.slice(1))) add2("var", p.words);
35619
35653
  } else if (w0 === "for" && isWord(ts[1], "each")) {
@@ -35632,6 +35666,29 @@ function collectNames(nodes, names) {
35632
35666
  for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(" "), defaultTokens: p.defaultTokens });
35633
35667
  }
35634
35668
  names.funcInputs.set(keyOf(ts.slice(1, -1)), inputs);
35669
+ } else if ((w0 === "a" || w0 === "an") && isOneOf(ts)) {
35670
+ const words13 = ts.slice(1, -4);
35671
+ add2("record", words13);
35672
+ const own = ["which"];
35673
+ const alts = [];
35674
+ for (const c of n.children) {
35675
+ const at2 = c.tokens.findIndex((t) => isWord(t, "with"));
35676
+ const altWords = stripArticle(at2 < 0 ? c.tokens : c.tokens.slice(0, at2));
35677
+ if (altWords.length) {
35678
+ alts.push(keyOf(altWords));
35679
+ names.alts.set(keyOf(altWords), [...names.alts.get(keyOf(altWords)) ?? [], keyOf(words13)]);
35680
+ }
35681
+ if (at2 >= 0) {
35682
+ for (const g of paramGroups(c.tokens.slice(at2 + 1))) if (g.words.length) {
35683
+ names.fields.add(keyOf(g.words));
35684
+ own.push(keyOf(g.words));
35685
+ }
35686
+ }
35687
+ }
35688
+ names.fields.add("which");
35689
+ names.recordFields.set(keyOf(words13), [...new Set(own)]);
35690
+ names.recordText.set(keyOf(words13), words13.map((x) => x.text).join(" "));
35691
+ names.altsOf.set(keyOf(words13), alts);
35635
35692
  } else if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has")) {
35636
35693
  const words13 = ts.slice(1, -2);
35637
35694
  add2("record", words13);
@@ -35672,6 +35729,10 @@ function rememberName(ts) {
35672
35729
  const end2 = ts.findIndex((t) => isWord(t, "as") || isWord(t, "starting") || isSym(t, ","));
35673
35730
  return stripArticle(end2 < 0 ? ts : ts.slice(0, end2));
35674
35731
  }
35732
+ function isOneOf(ts) {
35733
+ const n = ts.length;
35734
+ return n >= 6 && isSym(ts[n - 1], ":") && isWord(ts[n - 2], "of") && isWord(ts[n - 3], "one") && isWord(ts[n - 4], "is");
35735
+ }
35675
35736
  function paramGroups(ts) {
35676
35737
  const groups3 = [];
35677
35738
  let cur = [];
@@ -35834,6 +35895,15 @@ var ExprParser = class {
35834
35895
  }
35835
35896
  if (s.word("in")) return wrap2({ k: "contains", l: this.add(s, o), r: l, line });
35836
35897
  if (s.done()) s.fail('Something is missing after "is".', "For example: is 10, is at least 18, is nothing, is empty.", "TC108");
35898
+ if (this.names.alts?.size && s.peek()?.t === "word") {
35899
+ const run = [];
35900
+ for (let j = s.i; s.ts[j]?.t === "word" && !RESERVED2.has(s.ts[j].lower); j++) run.push(s.ts[j]);
35901
+ const ak = this.longest(run, (key) => this.names.alts.has(key));
35902
+ if (ak && !this.longest(run, (key) => this.names.known.has(key))) {
35903
+ s.i += ak;
35904
+ return wrap2({ k: "isAlt", e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(" "), col: run[0].col, line });
35905
+ }
35906
+ }
35837
35907
  return { k: "cmp", op: neg2 ? "!=" : "==", l, r: this.add(s, o), line };
35838
35908
  }
35839
35909
  return l;
@@ -35884,7 +35954,7 @@ var ExprParser = class {
35884
35954
  if (!run.length) s.fail(`I expected a field name after "'s".`, null, "TC108");
35885
35955
  const k = this.longest(run, (key) => this.names.fields.has(key)) || run.length;
35886
35956
  s.i -= run.length - k;
35887
- e = { k: "field", obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(" "), line: s.line };
35957
+ e = { k: "field", obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(" "), col: run[0].col, line: s.line };
35888
35958
  } else if (isWord(t, "at") && !isWord(s.peek(1), "least") && !isWord(s.peek(1), "most")) {
35889
35959
  s.next();
35890
35960
  const key = this.unary(s, { ...o, noAnd: true });
@@ -35986,11 +36056,52 @@ var ExprParser = class {
35986
36056
  if (!k) s.fail(`I don't know the kind of value "${run.map((x) => x.text).join(" ")}".`, 'Kinds: number, whole number, text, yes/no, money, date, list of \u2026, map of \u2026 to \u2026, optional \u2026, or a record you defined with "A \u2026 has:".', "TC306");
35987
36057
  s.i -= run.length - k;
35988
36058
  const key = keyOf(run.slice(0, k));
35989
- return { k: "record", name: this.names.records.has(key) ? key : key.replace(/s$/, "") };
36059
+ return { k: "record", name: this.names.records.has(key) ? key : key.replace(/s$/, ""), col: run[0].col, line: s.line };
36060
+ }
36061
+ /** The fields a record is built with: with name "Ann" and balance $10 (none without "with"). */
36062
+ recordFields(s, line) {
36063
+ const fields = [];
36064
+ if (s.word("with")) {
36065
+ do {
36066
+ const fr = this.wordRun(s);
36067
+ if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, "TC108");
36068
+ const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
36069
+ s.i -= fr.length - fk;
36070
+ fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(" "), e: this.expr(s, { noAnd: true }), line });
36071
+ } while ((isSym(s.peek(), ",") || isWord(s.peek(), "and")) && this.fieldAhead(s, 1) && s.next());
36072
+ }
36073
+ return fields;
35990
36074
  }
35991
36075
  primary(s, o) {
35992
36076
  const t = s.peek();
35993
36077
  const line = s.line;
36078
+ const METHODS2 = ["get", "post", "put", "patch", "delete"];
36079
+ if (isWord(t, "answer") && isWord(s.peek(1), "from") && METHODS2.includes(s.peek(2)?.lower)) {
36080
+ s.i += 2;
36081
+ const method = s.next().text.toUpperCase();
36082
+ const url = this.primary(s, { ...o, noAnd: true });
36083
+ let body2 = null, as = null;
36084
+ if (s.word("with")) {
36085
+ body2 = this.expr(s, { ...o, noAnd: true });
36086
+ if (body2.k === "conv" && body2.type) {
36087
+ as = body2.type;
36088
+ body2 = body2.e;
36089
+ }
36090
+ }
36091
+ if (!as && s.word("as")) as = this.typeRef(s);
36092
+ return { k: "httpCall", method, url, body: body2, as, line };
36093
+ }
36094
+ if (isWord(t, "calling") && METHODS2.includes(s.peek(1)?.lower) && isSym(s.peek(2), "/")) {
36095
+ s.i += 2;
36096
+ const method = s.ts[s.i - 1].text.toUpperCase();
36097
+ let path = "";
36098
+ let prev = null;
36099
+ while (s.peek() && (prev === null ? isSym(s.peek(), "/") : s.peek().col === prev.col + String(prev.text).length && (isSym(s.peek(), "/") || isSym(s.peek(), "-") || s.peek().t === "word" || s.peek().t === "num"))) {
36100
+ prev = s.next();
36101
+ path += prev.text;
36102
+ }
36103
+ return { k: "callEndpoint", method, path, fields: this.recordFields(s, line), line };
36104
+ }
35994
36105
  if (!t) s.fail("A value is missing at the end of this line.", null, "TC108");
35995
36106
  if (t.t === "num") {
35996
36107
  s.next();
@@ -36010,6 +36121,13 @@ var ExprParser = class {
36010
36121
  s.next();
36011
36122
  return { k: "str", parts: t.parts.map((p) => typeof p === "string" ? p : { e: this.parse(p.tokens, line), source: p.source }), line };
36012
36123
  }
36124
+ if (isSym(t, "?")) {
36125
+ s.next();
36126
+ const next = s.peek();
36127
+ let want = null;
36128
+ if (next && next.t === "word" && t.col != null && next.col === t.col + 1) want = this.typeRef(s);
36129
+ return { k: "draftHole", want, line, col: t.col };
36130
+ }
36013
36131
  if (isSym(t, "(")) {
36014
36132
  s.next();
36015
36133
  const e = this.expr(s, {});
@@ -36095,23 +36213,32 @@ var ExprParser = class {
36095
36213
  }
36096
36214
  if (RESERVED2.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, "TC105");
36097
36215
  const run = this.wordRun(s);
36216
+ if (o.article && this.names.alts?.size) {
36217
+ for (let i = 1; i < run.length; i++) {
36218
+ const alt = keyOf(run.slice(0, i));
36219
+ const recs = this.names.alts.get(alt);
36220
+ if (!recs) continue;
36221
+ const rk = this.longest(run.slice(i), (key) => recs.includes(key));
36222
+ if (!rk || i + rk !== run.length) continue;
36223
+ s.i -= run.length - i - rk;
36224
+ const node = { k: "new", record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(" "), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
36225
+ return node;
36226
+ }
36227
+ for (let i = 1; i < run.length; i++) {
36228
+ const rk = this.longest(run.slice(i), (key) => this.names.altsOf.has(key));
36229
+ if (!rk || i + rk !== run.length) continue;
36230
+ s.i -= run.length - i - rk;
36231
+ return { k: "new", record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(" "), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
36232
+ }
36233
+ }
36098
36234
  let off = run[0]?.lower === "new" && run.length > 1 ? 1 : 0;
36099
36235
  const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
36100
36236
  const wantsRecord = o.article || off || isWord(s.peek(), "with") || !this.longest(run, (key) => this.names.known.has(key));
36101
36237
  if (recK && wantsRecord && recK + off === run.length) {
36102
36238
  s.i -= run.length - off - recK;
36103
36239
  const name = keyOf(run.slice(off, off + recK));
36104
- const fields = [];
36105
- if (s.word("with")) {
36106
- do {
36107
- const fr = this.wordRun(s);
36108
- if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, "TC108");
36109
- const fk2 = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
36110
- s.i -= fr.length - fk2;
36111
- fields.push({ name: keyOf(fr.slice(0, fk2)), text: fr.slice(0, fk2).map((x) => x.text).join(" "), e: this.expr(s, { noAnd: true }), line });
36112
- } while ((isSym(s.peek(), ",") || isWord(s.peek(), "and")) && this.fieldAhead(s, 1) && s.next());
36113
- }
36114
- const node = { k: "new", record: name, fields, line };
36240
+ const fields = this.recordFields(s, line);
36241
+ const node = { k: "new", record: name, recordCol: run[off].col, fields, line };
36115
36242
  if (!fields.length && this.open) this.open.push(node);
36116
36243
  return node;
36117
36244
  }
@@ -36126,26 +36253,27 @@ var ExprParser = class {
36126
36253
  const key = keyOf(run.slice(0, k));
36127
36254
  const text2 = run.slice(0, k).map((x) => x.text).join(" ");
36128
36255
  if (this.names.known.get(key) === "func") {
36129
- if (isSym(s.peek(), "(")) return { k: "call", name: key, text: text2, args: this.parenArgs(s), line };
36130
- if (s.word("with")) return { k: "call", name: key, text: text2, args: this.withArgs(s), line };
36131
- const node = { k: "call", name: key, text: text2, args: [], line, bare: true };
36256
+ const col = run[0].col;
36257
+ if (isSym(s.peek(), "(")) return { k: "call", name: key, text: text2, col, args: this.parenArgs(s), line };
36258
+ if (s.word("with")) return { k: "call", name: key, text: text2, col, args: this.withArgs(s), line };
36259
+ const node = { k: "call", name: key, text: text2, col, args: [], line, bare: true };
36132
36260
  if (this.open) this.open.push(node);
36133
36261
  return node;
36134
36262
  }
36135
- return { k: "name", name: key, text: text2, line };
36263
+ return { k: "name", name: key, text: text2, col: run[0].col, line };
36136
36264
  }
36137
36265
  const fk = this.longest(run, (key) => this.names.fields.has(key));
36138
36266
  if (fk) {
36139
36267
  s.i -= run.length - fk;
36140
- return { k: "name", name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(" "), line, unknown: true };
36268
+ return { k: "name", name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(" "), col: run[0].col, line, unknown: true };
36141
36269
  }
36142
- return { k: "name", name: keyOf(run), text: run.map((x) => x.text).join(" "), line, unknown: true };
36270
+ return { k: "name", name: keyOf(run), text: run.map((x) => x.text).join(" "), col: run[0]?.col, line, unknown: true };
36143
36271
  }
36144
36272
  };
36145
36273
  function parseCore(source, { seed = null } = {}) {
36146
36274
  const { lines, diagnostics } = lex3(source);
36147
36275
  const tree = buildBlocks(lines, diagnostics);
36148
- const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: /* @__PURE__ */ new Map(), screens: /* @__PURE__ */ new Map() };
36276
+ const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: /* @__PURE__ */ new Map(), screens: /* @__PURE__ */ new Map(), alts: new Map(seed?.alts ?? []), altsOf: new Map(seed?.altsOf ?? []) };
36149
36277
  collectNames(tree, names);
36150
36278
  const ep = new ExprParser(names);
36151
36279
  const body2 = parseBlock(tree, ep, names, diagnostics, { top: true });
@@ -36178,12 +36306,12 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
36178
36306
  }
36179
36307
  return out;
36180
36308
  }
36181
- var BLOCK_STATEMENTS = /* @__PURE__ */ new Set(["when", "if", "otherwise", "for", "repeat", "to", "test", "receive", "never", "use", "screen"]);
36309
+ var BLOCK_STATEMENTS = /* @__PURE__ */ new Set(["when", "if", "otherwise", "for", "repeat", "to", "test", "receive", "never", "use", "screen", "depending"]);
36182
36310
  function fieldBlock(n, diagnostics = []) {
36183
36311
  const ts = n.tokens;
36184
36312
  if (!n.children.length || !isSym(ts[ts.length - 1], ":")) return null;
36185
36313
  const w0 = ts[0]?.t === "word" ? ts[0].lower : "";
36186
- if (BLOCK_STATEMENTS.has(w0) || (w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has")) return null;
36314
+ if (BLOCK_STATEMENTS.has(w0) || (w0 === "a" || w0 === "an") && (isWord(ts[ts.length - 2], "has") || isOneOf(ts))) return null;
36187
36315
  return n.children.map((c) => {
36188
36316
  const colon = c.tokens.findIndex((t) => isSym(t, ":"));
36189
36317
  const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
@@ -36260,7 +36388,7 @@ function nameWords2(ts, line, what) {
36260
36388
  if (t.t !== "word") throw new CoreError(diag("TC105", line, `A name can only use words, but "${show(t)}" is not a word.`));
36261
36389
  if (RESERVED2.has(t.lower)) throw new CoreError(diag("TC202", line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
36262
36390
  }
36263
- return { name: keyOf(words13), text: words13.map((x) => x.text).join(" ") };
36391
+ return { name: keyOf(words13), text: words13.map((x) => x.text).join(" "), col: words13[0].col };
36264
36392
  }
36265
36393
  function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36266
36394
  const ts = n.tokens;
@@ -36276,6 +36404,26 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36276
36404
  };
36277
36405
  const w0 = ts[0].t === "word" ? ts[0].lower : "";
36278
36406
  const rest2 = ts.slice(1);
36407
+ if (w0 === "when" && isWord(ts[1], "someone") && isWord(ts[2], "calls") && ts[4]?.t === "path") {
36408
+ if (!ctx.top) fail2("TC402", 'An endpoint ("When someone calls \u2026") must be written at the left edge, not inside another block.');
36409
+ const method = ts[3].text.toUpperCase();
36410
+ const path = ts[4].text;
36411
+ const segments = path.split("/").filter(Boolean).map((seg) => {
36412
+ const m = seg.match(/^\{([^{}]+)\}$/);
36413
+ return m ? { param: m[1].trim().toLowerCase(), text: m[1].trim() } : { lit: seg };
36414
+ });
36415
+ const kids2 = n.children;
36416
+ const params = [];
36417
+ let r = 0;
36418
+ while (kids2[r] && isWord(kids2[r].tokens[0], "receive")) {
36419
+ const kid = kids2[r];
36420
+ params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
36421
+ r++;
36422
+ }
36423
+ const words13 = ["answer", method.toLowerCase(), ...segments.map((g) => g.param ? g.param : g.lit.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()).filter(Boolean)];
36424
+ const name = words13.join(" ");
36425
+ return { k: "func", name, text: `${method} ${path}`, params, body: parseBlock(kids2.slice(r), ep, names, diagnostics, { inFunc: true, inEndpoint: true }), line, endpoint: { method, path, segments, line } };
36426
+ }
36279
36427
  if (w0 === "say" || w0 === "print") return { k: "say", e: E(rest2), line };
36280
36428
  if (w0 === "set") {
36281
36429
  const at2 = splitTop4(rest2, (t) => isWord(t, "to"));
@@ -36286,20 +36434,37 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36286
36434
  if (!["name", "field", "at"].includes(target.k)) fail2("TC305", "Only a name, a field (customer's balance), or an entry (counts at word) can be set.");
36287
36435
  return { k: "set", target, e: E(rest2.slice(at2 + 1)), line };
36288
36436
  }
36437
+ if (w0 === "store" && rest2.some((t) => isWord(t, "as"))) {
36438
+ if (!ctx.top) fail2("TC402", 'A "Store" line must be written at the left edge of the file.');
36439
+ const as = splitTop4(rest2, (t) => isWord(t, "as"));
36440
+ const typeTokens = stripArticle(rest2.slice(as + 1));
36441
+ if (!typeTokens.length) fail2("TC108", "Write what the store holds: Store habits as a list of Habit.");
36442
+ return { k: "store", ...nameWords2(rest2.slice(0, as), line, '"Store"'), type: typeOf(ep, typeTokens, line), line };
36443
+ }
36289
36444
  if (w0 === "keep") {
36290
36445
  const at2 = splitTop4(rest2, (t) => isWord(t, "at"));
36291
36446
  if (at2 < 0) fail2("TC108", '"Keep" needs "at": Keep tax rate at 7%.');
36292
36447
  return { k: "keep", ...nameWords2(rest2.slice(0, at2), line, '"Keep"'), e: E(rest2.slice(at2 + 1)), line };
36293
36448
  }
36449
+ const statusAt = (r, joiner) => {
36450
+ const n2 = r.length;
36451
+ if (n2 >= 3 && isWord(r[n2 - 3], joiner) && isWord(r[n2 - 2], "status") && r[n2 - 1].t === "num") {
36452
+ if (joiner === "with" && !ctx.inEndpoint) fail2("TC218", `"with status" sets the HTTP status of an endpoint's answer, so it goes inside "When someone calls \u2026".`, "Outside an endpoint, Give the value; the endpoint that gives it sets the status.");
36453
+ return { status: Number(r[n2 - 1].text), r: r.slice(0, -3) };
36454
+ }
36455
+ return { status: null, r };
36456
+ };
36294
36457
  if (w0 === "give") {
36295
36458
  let r = rest2;
36296
36459
  if (isWord(r[0], "back")) r = r.slice(1);
36297
- return { k: "give", e: r.length ? E(r) : { k: "nothing", line }, line };
36460
+ const st = statusAt(r, "with");
36461
+ return { k: "give", e: st.r.length ? E(st.r) : { k: "nothing", line }, status: st.status, line };
36298
36462
  }
36299
36463
  if (w0 === "stop") {
36300
36464
  let r = rest2;
36301
36465
  if (isWord(r[0], "with") || isSym(r[0], ":")) r = r.slice(1);
36302
- return { k: "stop", e: r.length ? E(r) : { k: "str", parts: ["Stopped"], line }, line };
36466
+ const st = statusAt(r, "and");
36467
+ return { k: "stop", e: st.r.length ? E(st.r) : { k: "str", parts: ["Stopped"], line }, status: st.status, line };
36303
36468
  }
36304
36469
  if (w0 === "if" && keyOf(ts.slice(0, 3)) === "if this fails") {
36305
36470
  header();
@@ -36308,6 +36473,28 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36308
36473
  siblings.pop();
36309
36474
  return { k: "tryFail", stmt: prev, handler: children(), line };
36310
36475
  }
36476
+ if (w0 === "depending" && isWord(ts[1], "on")) {
36477
+ const subject = E(header().slice(2));
36478
+ const cases = [];
36479
+ let otherwise = null;
36480
+ for (const c of n.children) {
36481
+ try {
36482
+ const ct = c.tokens;
36483
+ if (!isSym(ct[ct.length - 1], ":") || ct.length < 2) throw new CoreError(diag("TC108", c.line, 'Under "Depending on", each case is an alternative and a colon, for example: Successful:'));
36484
+ const sub2 = parseBlock(c.children, ep, names, diagnostics, ctx);
36485
+ if (ct.length === 2 && isWord(ct[0], "otherwise")) {
36486
+ otherwise = sub2;
36487
+ continue;
36488
+ }
36489
+ const { name, text: text2, col } = nameWords2(ct.slice(0, -1), c.line, "A case");
36490
+ cases.push({ alt: name, text: text2, col, body: sub2, line: c.line });
36491
+ } catch (e2) {
36492
+ if (e2 instanceof CoreError) diagnostics.push(e2.diagnostic);
36493
+ else throw e2;
36494
+ }
36495
+ }
36496
+ return { k: "depending", subject, cases, otherwise, line };
36497
+ }
36311
36498
  if (w0 === "when" || w0 === "if") {
36312
36499
  const cond = E(header().slice(1));
36313
36500
  return { k: "if", branches: [{ cond, body: children(), line }], otherwise: null, line };
@@ -36350,7 +36537,7 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36350
36537
  }
36351
36538
  if (w0 === "to" && isSym(ts[ts.length - 1], ":")) {
36352
36539
  if (!ctx.top) fail2("TC402", 'A "To" block (a function) must be written at the left edge, not inside another block.');
36353
- const { name, text: text2 } = nameWords2(header().slice(1), line, '"To"');
36540
+ const { name, text: text2, col } = nameWords2(header().slice(1), line, '"To"');
36354
36541
  const kids2 = n.children;
36355
36542
  let params = [];
36356
36543
  let bodyNodes = kids2;
@@ -36361,7 +36548,7 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36361
36548
  r++;
36362
36549
  }
36363
36550
  bodyNodes = kids2.slice(r);
36364
- return { k: "func", name, text: text2, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
36551
+ return { k: "func", name, text: text2, col, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
36365
36552
  }
36366
36553
  if (w0 === "receive") fail2("TC111", '"Receive" must be the first line inside a "To" block or a "Screen".');
36367
36554
  if (w0 === "screen" && isSym(ts[ts.length - 1], ":")) {
@@ -36374,9 +36561,36 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36374
36561
  }
36375
36562
  if (w0 === "remember") fail2("TC119", '"Remember" goes at the top of a "Screen", after its "Receive" lines.', "A function keeps nothing between calls; a screen remembers values while it is shown.");
36376
36563
  if (w0 === "show") fail2("TC118", '"Show" is used inside a "Screen" (a screen shows things). In a program, write: Say \u2026');
36564
+ if ((w0 === "a" || w0 === "an") && isOneOf(ts)) {
36565
+ if (!ctx.top) fail2("TC402", 'A data type ("A \u2026 is one of:") must be written at the left edge, not inside another block.');
36566
+ const { name, text: text2, col } = nameWords2(ts.slice(1, -4), line, "A data type");
36567
+ const alts = [];
36568
+ for (const c of n.children) {
36569
+ try {
36570
+ const at2 = c.tokens.findIndex((t) => isWord(t, "with"));
36571
+ const alt = nameWords2(at2 < 0 ? c.tokens : c.tokens.slice(0, at2), c.line, "An alternative");
36572
+ const fields2 = [];
36573
+ if (at2 >= 0) {
36574
+ for (const g of paramGroups(c.tokens.slice(at2 + 1))) {
36575
+ if (!g.typeTokens) throw new CoreError(diag("TC108", c.line, `Write each field with its kind: ${alt.text} with ${g.words.map((x) => x.text).join(" ") || "amount"} as money.`));
36576
+ fields2.push({ ...nameWords2(g.raw, c.line, "A field"), type: typeOf(ep, g.typeTokens, c.line), line: c.line });
36577
+ }
36578
+ }
36579
+ alts.push({ ...alt, fields: fields2, line: c.line });
36580
+ } catch (e2) {
36581
+ if (e2 instanceof CoreError) diagnostics.push(e2.diagnostic);
36582
+ else throw e2;
36583
+ }
36584
+ }
36585
+ if (!alts.length) fail2("TC108", `Write the alternatives under it, one per line, for example: Successful with amount as money.`);
36586
+ const opt2 = (t) => t.k === "optional" ? t : { k: "optional", of: t };
36587
+ const fields = [{ name: "which", text: "which", type: { k: "text" }, line, hidden: true }];
36588
+ for (const a of alts) for (const f of a.fields) if (!fields.some((x) => x.name === f.name)) fields.push({ ...f, type: opt2(f.type) });
36589
+ return { k: "record", name, text: text2, col, fields, rules: [], alts, line };
36590
+ }
36377
36591
  if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has") && isSym(ts[ts.length - 1], ":")) {
36378
36592
  if (!ctx.top) fail2("TC402", 'A record ("A \u2026 has:") must be written at the left edge, not inside another block.');
36379
- const { name, text: text2 } = nameWords2(ts.slice(1, -2), line, "A record");
36593
+ const { name, text: text2, col } = nameWords2(ts.slice(1, -2), line, "A record");
36380
36594
  const fields = [], rules = [];
36381
36595
  for (const c of n.children) {
36382
36596
  try {
@@ -36392,7 +36606,7 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
36392
36606
  else throw e2;
36393
36607
  }
36394
36608
  }
36395
- return { k: "record", name, text: text2, fields, rules, line };
36609
+ return { k: "record", name, text: text2, col, fields, rules, line };
36396
36610
  }
36397
36611
  if (w0 === "expect") return { ...parseExpect(rest2, line, ep), raw: n.raw };
36398
36612
  if (w0 === "never") return parseNever(ts, line, ep);
@@ -36810,8 +37024,9 @@ var Checker = class {
36810
37024
  this.rules = [];
36811
37025
  this.mainNames = /* @__PURE__ */ new Map();
36812
37026
  this.elem = [];
36813
- this.info = { records: [], funcs: [], consts: [], modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
37027
+ this.info = { records: [], funcs: [], consts: [], stores: [], endpoints: [], usesHttp: false, modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
36814
37028
  this.screens = /* @__PURE__ */ new Map();
37029
+ this.narrow = [];
36815
37030
  }
36816
37031
  err(code3, line, msg, hint) {
36817
37032
  this.d.push(diag(code3, line, msg, hint));
@@ -36853,6 +37068,7 @@ var Checker = class {
36853
37068
  }
36854
37069
  }
36855
37070
  for (const s of top) if (s.k === "record") this.checkRecordShape(s);
37071
+ this.info.endpointsAll = [...top.filter((s) => s.k === "func" && s.endpoint), ...(this.imported ?? []).flatMap((inf) => inf.endpoints ?? [])];
36856
37072
  collectMainNames(top, this.mainNames);
36857
37073
  for (const s of top) {
36858
37074
  if (s.k !== "keep") continue;
@@ -36860,6 +37076,24 @@ var Checker = class {
36860
37076
  this.declare(s, "const", s.line, { py: pyName(s.name, "upper"), type: t });
36861
37077
  this.info.consts.push(s);
36862
37078
  }
37079
+ for (const s of top) {
37080
+ if (s.k !== "store") continue;
37081
+ const t = s.type;
37082
+ const rec = t?.k === "list" && t.of?.k === "record" ? this.records.get(t.of.name) : null;
37083
+ if (!rec) {
37084
+ this.err("TC306", s.line, `A store holds a list of records, for example: Store habits as a list of Habit.`, 'Describe the record with "A Habit has:", then store a list of it.');
37085
+ continue;
37086
+ }
37087
+ const plain = (ft) => ft && (["whole", "number", "money", "text", "bool", "date"].includes(ft.k) || ft.k === "optional" && plain(ft.of));
37088
+ const bad = rec.fields.find((f) => !plain(f.type));
37089
+ if (bad) {
37090
+ this.err("TC306", s.line, `"${rec.text ?? rec.name}" can't be stored yet: its field "${bad.text ?? bad.name}" is not a plain value.`, "A stored record's fields are whole numbers, numbers, money, text, yes/no, dates, or one of those or nothing.");
37091
+ continue;
37092
+ }
37093
+ s.record = rec;
37094
+ this.declare(s, "store", s.line, { py: pyName(s.name, "upper"), type: { k: "list", of: { k: "record", name: rec.name, text: rec.text } } });
37095
+ this.info.stores.push(s);
37096
+ }
36863
37097
  for (const s of top) if (s.k === "never") this.addRule(s, null);
36864
37098
  for (const r of this.records.values()) for (const rule of r.rules) this.addRule(rule, r);
36865
37099
  for (const s of top) if (s.k === "func") this.checkFunc(s);
@@ -36877,7 +37111,7 @@ var Checker = class {
36877
37111
  if (needs.length) this.err("TC214", first.line, `"${first.text}" is the first screen, where the app starts, so nothing gives it ${needs.map((p) => p.text).join(", ")}.`, `Put the screen the app starts on first, or give ${needs.length === 1 ? "the input" : "each input"} a value for when it isn't given: Receive ${needs[0].text} (\u2026 if not given).`);
36878
37112
  const main = new Scope2(this.global, "main");
36879
37113
  this.mainScope = main;
36880
- const mainBody = top.filter((s) => !["record", "func", "use", "keep", "never", "test", "screen"].includes(s.k));
37114
+ const mainBody = top.filter((s) => !["record", "func", "use", "keep", "store", "never", "test", "screen"].includes(s.k));
36881
37115
  this.block(mainBody, main, {});
36882
37116
  this.p.main = mainBody;
36883
37117
  this.info.records = [...this.records.values()];
@@ -36918,6 +37152,98 @@ var Checker = class {
36918
37152
  this.resolveType(f.type, f.line);
36919
37153
  r.fieldMap.set(f.name, f);
36920
37154
  }
37155
+ if (r.alts) this.checkAlternatives(r);
37156
+ }
37157
+ /** A data type with alternatives: each alternative's fields, one kind per field name, and no field called "which". */
37158
+ /**
37159
+ * Depending on payment: one case per alternative (or Otherwise). A missing alternative is reported at this line.
37160
+ * Then it runs as If payment is successful … Otherwise if payment is declined …, with the value read once per test.
37161
+ */
37162
+ depending(s, sc, ctx) {
37163
+ const line = s.line;
37164
+ const t = this.ex(s.subject, sc);
37165
+ const r = t.k === "record" ? this.records.get(t.name) : null;
37166
+ const name = s.subject.k === "name" ? s.subject.name : null;
37167
+ const bodies = () => {
37168
+ for (const c of s.cases) this.block(c.body, sc, ctx);
37169
+ if (s.otherwise) this.block(s.otherwise, sc, ctx);
37170
+ };
37171
+ if (!r?.altMap) {
37172
+ if (known(t)) this.err("TC305", line, `"Depending on" chooses by the alternative a value is, but this is ${typeWords4(t)}, not a data type with alternatives.`, "For other values, use When \u2026 / Otherwise when \u2026.");
37173
+ bodies();
37174
+ s.k = "if";
37175
+ s.branches = [];
37176
+ return;
37177
+ }
37178
+ if (!["name", "field"].includes(s.subject.k)) this.err("TC305", line, `"Depending on" reads its value once for each case, so give it a name first.`, `Set result to \u2026, then write: Depending on result:`);
37179
+ const seen = /* @__PURE__ */ new Set();
37180
+ for (const c of s.cases) {
37181
+ if (!r.altMap.has(c.alt)) {
37182
+ this.err("TC217", c.line, `A ${r.text} is ${this.altList(r)}; "${c.text}" isn't one of them.`);
37183
+ this.block(c.body, sc, ctx);
37184
+ continue;
37185
+ }
37186
+ if (seen.has(c.alt)) this.err("TC203", c.line, `"${c.text}" already has a case above.`);
37187
+ seen.add(c.alt);
37188
+ if (name) this.narrow.push({ name, alt: c.alt });
37189
+ try {
37190
+ this.block(c.body, sc, ctx);
37191
+ } finally {
37192
+ if (name) this.narrow.pop();
37193
+ }
37194
+ }
37195
+ if (s.otherwise) this.block(s.otherwise, sc, ctx);
37196
+ const missing = [...r.altMap.values()].filter((a) => !seen.has(a.name));
37197
+ if (missing.length && !s.otherwise) {
37198
+ const ws = missing.map((a) => a.text.toLowerCase());
37199
+ this.err(
37200
+ "TC215",
37201
+ line,
37202
+ `"Depending on ${s.subject.text ?? "this"}" doesn't say what to do when it is ${ws.length <= 2 ? ws.join(" or ") : `${ws.slice(0, -1).join(", ")}, or ${ws[ws.length - 1]}`}.`,
37203
+ `Add ${missing.map((a) => `"${a.text}:"`).join(" and ")} with what to do, or "Otherwise:" for every case not listed.`
37204
+ );
37205
+ }
37206
+ const cases = s.cases.filter((c) => r.altMap.has(c.alt));
37207
+ Object.assign(s, { k: "if", branches: cases.map((c) => ({ cond: this.altTest(s.subject, r, c.alt, false, c.line), body: c.body, line: c.line })), otherwise: s.otherwise });
37208
+ }
37209
+ checkAlternatives(r) {
37210
+ r.altMap = /* @__PURE__ */ new Map();
37211
+ for (const a of r.alts) {
37212
+ if (r.altMap.has(a.name)) this.err("TC203", a.line, `${r.text} already has an alternative "${a.text}".`);
37213
+ a.fieldMap = /* @__PURE__ */ new Map();
37214
+ for (const f of a.fields) {
37215
+ if (f.name === "which") {
37216
+ this.err("TC203", f.line, `"which" is the name Thunder gives to the alternative a ${r.text} is, so a field can't be called that.`, "Give the field another name.");
37217
+ continue;
37218
+ }
37219
+ if (a.fieldMap.has(f.name)) this.err("TC203", f.line, `${a.text} already has a field "${f.text}".`);
37220
+ f.py = pyName(f.name);
37221
+ this.resolveType(f.type, f.line);
37222
+ const shared = r.fieldMap.get(f.name);
37223
+ const plain = (t) => t.k === "optional" ? t.of : t;
37224
+ if (shared && known(f.type) && known(shared.type) && !sameKind(plain(shared.type), plain(f.type))) {
37225
+ this.err("TC303", f.line, `"${f.text}" is ${typeWords4(plain(shared.type))} in another alternative of ${r.text}, so here it can't be ${typeWords4(plain(f.type))}.`, "Use one kind for a field name in every alternative, or give the fields different names.");
37226
+ }
37227
+ a.fieldMap.set(f.name, f);
37228
+ }
37229
+ r.altMap.set(a.name, a);
37230
+ }
37231
+ }
37232
+ /** The alternatives of a data type, as a person reads them: successful, declined, or pending. */
37233
+ altList(r, joiner = "or") {
37234
+ const ws = [...r.altMap.values()].map((a) => a.text.toLowerCase());
37235
+ return ws.length <= 2 ? ws.join(` ${joiner} `) : `${ws.slice(0, -1).join(", ")}, ${joiner} ${ws[ws.length - 1]}`;
37236
+ }
37237
+ /** The alternative a name is known to be here (inside its case, or after "If x is …"), or null. */
37238
+ narrowed(e) {
37239
+ if (e.k !== "name") return null;
37240
+ for (let i = this.narrow.length - 1; i >= 0; i--) if (this.narrow[i].name === e.name) return this.narrow[i].alt;
37241
+ return null;
37242
+ }
37243
+ /** "x is successful", as the program runs it: x's which equals "successful". */
37244
+ altTest(subject, r, alt, neg2, line) {
37245
+ const which = { k: "field", obj: subject, name: "which", text: "which", py: "which", static: true, line, type: { k: "text" } };
37246
+ return { k: "cmp", op: neg2 ? "!=" : "==", l: which, r: { k: "str", parts: [alt], line, type: { k: "text" } }, line, type: { k: "bool" } };
36921
37247
  }
36922
37248
  resolveType(t, line) {
36923
37249
  if (!t) return;
@@ -36984,7 +37310,90 @@ var Checker = class {
36984
37310
  rulesFor(key) {
36985
37311
  return this.rules.filter((r) => r.watchesVar && r.subject === key);
36986
37312
  }
37313
+ /**
37314
+ * An endpoint (When someone calls GET /habits/{name}:): a known method, one per method and path, every {part} of
37315
+ * the path received, and inputs of kinds a request can carry (an input with no kind is text).
37316
+ */
37317
+ checkEndpoint(f) {
37318
+ const ep = f.endpoint;
37319
+ const line = ep.line;
37320
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(ep.method)) this.err("TC108", line, `"${ep.method}" isn't an HTTP method Thunder answers.`, "Use GET, POST, PUT, PATCH, or DELETE.");
37321
+ this.routes ??= /* @__PURE__ */ new Map();
37322
+ const key = `${ep.method} /${ep.segments.map((g) => g.param ? "{}" : g.lit).join("/")}`;
37323
+ if (this.routes.has(key) && this.routes.get(key).path !== ep.path) this.err("TC203", line, `${ep.method} ${ep.path} is answered already, by ${ep.method} ${this.routes.get(key).path} (line ${this.routes.get(key).line}).`, "Each method and path is answered by one endpoint.");
37324
+ else if (!this.routes.has(key)) this.routes.set(key, ep);
37325
+ const plain = (t) => t && (["whole", "number", "money", "text", "bool", "date"].includes(t.k) || t.k === "optional" && plain(t.of));
37326
+ for (const p of f.params) {
37327
+ if (!p.type) p.type = { k: "text" };
37328
+ if (!plain(p.type)) this.err("TC306", p.line, `"${p.text}" can't come from a request: it is ${typeWords4(p.type)}.`, "An endpoint receives whole numbers, numbers, money, text, yes/no, dates, or optional ones of those. Receive a record's fields one by one.");
37329
+ }
37330
+ for (const g of ep.segments.filter((x) => x.param)) {
37331
+ const p = f.params.find((x) => x.name === g.param);
37332
+ if (!p) this.err("TC207", line, `The path has {${g.text}}, but the endpoint doesn't receive "${g.text}".`, `Add: Receive ${g.text} as text (or the kind it is).`);
37333
+ else g.py = pyName(p.name);
37334
+ }
37335
+ this.info.endpoints.push(f);
37336
+ }
37337
+ /** calling GET /habits/walk with name "run": the endpoint that answers it, called directly with those inputs. */
37338
+ callEndpoint(e, sc, o) {
37339
+ const segs = e.path.split("/").filter(Boolean);
37340
+ const f = this.info.endpointsAll?.find((x) => x.endpoint.method === e.method && x.endpoint.segments.length === segs.length && x.endpoint.segments.every((g, i) => g.param || g.lit === segs[i]));
37341
+ if (!f) {
37342
+ const known2 = (this.info.endpointsAll ?? []).map((x) => `${x.endpoint.method} ${x.endpoint.path}`);
37343
+ this.err("TC207", e.line, `Nothing in this program answers ${e.method} ${e.path}.`, known2.length ? `Endpoints: ${known2.join(", ")}.` : "Write one: When someone calls GET /habits:");
37344
+ for (const fl of e.fields) this.ex(fl.e, sc, o);
37345
+ return UNKNOWN;
37346
+ }
37347
+ const given = /* @__PURE__ */ new Map();
37348
+ f.endpoint.segments.forEach((g, i) => {
37349
+ if (g.param) given.set(g.param, this.pathValue(segs[i], f.params.find((p) => p.name === g.param), e.line));
37350
+ });
37351
+ for (const fl of e.fields) {
37352
+ if (!f.params.some((p) => p.name === fl.name)) {
37353
+ this.err("TC207", e.line, `${f.endpoint.method} ${f.endpoint.path} doesn't receive "${fl.text}".`, `It receives: ${f.params.map((p) => p.text).join(", ") || "nothing"}.`);
37354
+ continue;
37355
+ }
37356
+ if (given.has(fl.name)) {
37357
+ this.err("TC203", e.line, `"${fl.text}" is already given by the path.`);
37358
+ continue;
37359
+ }
37360
+ given.set(fl.name, fl.e);
37361
+ }
37362
+ const args = [];
37363
+ const last = f.params.reduce((k, p, i) => given.has(p.name) ? i : k, -1);
37364
+ f.params.forEach((p, i) => {
37365
+ if (given.has(p.name)) {
37366
+ args.push(given.get(p.name));
37367
+ return;
37368
+ }
37369
+ if (p.dflt) {
37370
+ if (i < last) args.push(JSON.parse(JSON.stringify(p.dflt)));
37371
+ return;
37372
+ }
37373
+ if (p.type?.k === "optional") {
37374
+ if (i < last) args.push({ k: "nothing", line: e.line });
37375
+ return;
37376
+ }
37377
+ this.err("TC207", e.line, `${f.endpoint.method} ${f.endpoint.path} needs "${p.text}".`, `Give it: calling ${e.method} ${e.path} with ${p.text} \u2026.`);
37378
+ });
37379
+ Object.assign(e, { k: "call", name: f.name, text: f.text, args });
37380
+ return this.call(e, sc, o);
37381
+ }
37382
+ /** A part of a path written in a test (walk, 3) as the value its input receives. */
37383
+ pathValue(text2, p, line) {
37384
+ const k = p?.type?.k === "optional" ? p.type.of.k : p?.type?.k;
37385
+ if ((k === "whole" || k === "number") && /^-?\d+(\.\d+)?$/.test(text2)) return { k: "num", text: text2, whole: !text2.includes("."), line };
37386
+ if (k === "money" && /^\d+(\.\d+)?$/.test(text2)) return { k: "money", text: text2, line };
37387
+ if (k === "bool" && /^(yes|no|true|false)$/i.test(text2)) return { k: "bool", v: /^(yes|true)$/i.test(text2), line };
37388
+ if (k === "date" && /^\d{4}-\d{2}-\d{2}$/.test(text2)) return { k: "date", text: text2, line };
37389
+ if (k && k !== "text") this.err("TC303", line, `"${text2}" in the path isn't ${typeWords4(p.type)}, which "${p.text}" is.`);
37390
+ return { k: "str", parts: [decodeURIComponent(text2)], line };
37391
+ }
37392
+ checkStatus(n, line, [lo, hi], what) {
37393
+ if (!(n >= lo && n <= hi)) this.err("TC303", line, `${what} ${n}: ${what.startsWith("Give") ? "an answer that worked" : "a request that could not be done"} has a status from ${lo} to ${hi}.`, what.startsWith("Give") ? 'For example 200 (done) or 201 (created). To say no, use Stop with "\u2026" and status 404.' : "For example 400 (bad request), 404 (not found), or 409 (conflict).");
37394
+ }
36987
37395
  checkFunc(f) {
37396
+ if (f.endpoint) this.checkEndpoint(f);
36988
37397
  const sc = new Scope2(this.global, "func");
36989
37398
  sc.func = f;
36990
37399
  f.gives = [];
@@ -37047,15 +37456,25 @@ var Checker = class {
37047
37456
  }
37048
37457
  const t = this.ex(s.e, sc);
37049
37458
  sc.func ? sc.func.gives.push(t) : findFunc(sc)?.gives.push(t);
37459
+ if (s.status != null) this.checkStatus(s.status, line, [200, 299], "Give \u2026 with status");
37050
37460
  return;
37051
37461
  }
37052
37462
  case "stop":
37053
37463
  this.ex(s.e, sc);
37464
+ if (s.status != null) this.checkStatus(s.status, line, [400, 599], "Stop \u2026 and status");
37054
37465
  return;
37466
+ case "depending":
37467
+ return this.depending(s, sc, ctx);
37055
37468
  case "if":
37056
37469
  for (const b of s.branches) {
37470
+ const c = b.cond.k === "isAlt" && b.cond.e.k === "name" ? { name: b.cond.e.name, alt: b.cond.alt } : null;
37057
37471
  this.cond(b.cond, sc);
37058
- this.block(b.body, sc, ctx);
37472
+ if (c && b.cond.k === "cmp") this.narrow.push(c);
37473
+ try {
37474
+ this.block(b.body, sc, ctx);
37475
+ } finally {
37476
+ if (c && b.cond.k === "cmp") this.narrow.pop();
37477
+ }
37059
37478
  }
37060
37479
  if (s.otherwise) this.block(s.otherwise, sc, ctx);
37061
37480
  return;
@@ -37127,6 +37546,10 @@ var Checker = class {
37127
37546
  if (s.targetKind === "list" && known(tt.of) && known(te) && !compatible(tt.of, te)) this.err("TC303", line, `This list holds ${typeWords4(tt.of)}, so ${typeWords4(te)} can't be added to it.`);
37128
37547
  if (s.k === "add" && s.targetKind === "list" && !known(tt.of) && known(te) && s.target.k === "name" && s.target.ref?.type?.k === "list") s.target.ref.type = T("list", { of: te });
37129
37548
  this.afterAssign(s, s.target, sc);
37549
+ if (s.targetKind === "list" || s.targetKind === "map" && s.k === "remove") {
37550
+ const watched = s.target.k === "name" ? s.rules?.length > 0 : s.target.k === "field" && (this.records.get(s.target.record)?.rulesToCheck ?? []).some((r) => r.subject === s.target.name);
37551
+ if (watched && s.targetKind === "list") s.guard = true;
37552
+ }
37130
37553
  return;
37131
37554
  }
37132
37555
  case "increase":
@@ -37322,6 +37745,10 @@ var Checker = class {
37322
37745
  const tgt = s.target;
37323
37746
  if (tgt.k === "name") {
37324
37747
  const g = this.global.vars.get(tgt.name);
37748
+ if (g && g.kind === "store") {
37749
+ this.err("TC205", line, `"${tgt.text}" is a stored list (line ${g.line}): change its items, don't replace it.`, `Use Add \u2026 to ${tgt.text}, Remove \u2026 from ${tgt.text}, or Set ${tgt.text} at <position> to \u2026.`);
37750
+ return;
37751
+ }
37325
37752
  if (g && g.kind === "const") {
37326
37753
  this.err("TC205", line, `"${tgt.text}" is kept at a fixed value (line ${g.line}), so it can't be set.`, "Use a different name for a value that changes, or change the Keep line.");
37327
37754
  return;
@@ -37352,6 +37779,7 @@ var Checker = class {
37352
37779
  }
37353
37780
  } else {
37354
37781
  const tt = this.ex(tgt, sc);
37782
+ if (tgt.k === "field" && tgt.name === "which" && tgt.obj.type?.k === "record" && this.records.get(tgt.obj.type.name)?.altMap) this.err("TC205", line, `Which alternative a ${tgt.obj.type.text ?? "value"} is can't be changed.`, "Build a new one instead: Set payment to a declined Payment with \u2026.");
37355
37783
  this.lvalue(tgt, sc, line);
37356
37784
  if (known(tt) && known(tv) && !compatible(tt, tv)) this.err("TC303", line, `${tgt.k === "field" ? `The field "${tgt.text}"` : "This entry"} holds ${typeWords4(tt)}, so it can't be set to ${typeWords4(tv)}.`);
37357
37785
  }
@@ -37450,6 +37878,46 @@ var Checker = class {
37450
37878
  return T("nothing");
37451
37879
  case "hole":
37452
37880
  return e.type ?? UNKNOWN;
37881
+ case "draftHole":
37882
+ return this.draftHole(e, sc);
37883
+ case "callEndpoint":
37884
+ return this.callEndpoint(e, sc, o);
37885
+ case "httpCall": {
37886
+ this.info.usesHttp = true;
37887
+ const ut = this.ex(e.url, sc, o);
37888
+ if (known(ut) && ut.k !== "text") this.err("TC305", line, `The address to call is text ("https://\u2026"), but this is ${typeWords4(ut)}.`);
37889
+ if (e.body) this.ex(e.body, sc, o);
37890
+ if (!e.as) return T("text");
37891
+ this.resolveType(e.as, line);
37892
+ const rec = e.as.k === "record" ? this.records.get(e.as.name) : e.as.k === "list" && e.as.of?.k === "record" ? this.records.get(e.as.of.name) : null;
37893
+ const plain = (t) => t && (["whole", "number", "money", "text", "bool", "date"].includes(t.k) || t.k === "optional" && plain(t.of));
37894
+ if (!rec) {
37895
+ this.err("TC306", line, `An answer is read as a record or a list of records, for example: as Rate, as list of Rate.`, 'Without "as", the answer is its text.');
37896
+ return UNKNOWN;
37897
+ }
37898
+ const bad = rec.fields.find((f) => !plain(f.type));
37899
+ if (bad) {
37900
+ this.err("TC306", line, `An answer can't be read as ${rec.text} yet: its field "${bad.text}" is not a plain value.`);
37901
+ return UNKNOWN;
37902
+ }
37903
+ e.record = rec;
37904
+ return e.as;
37905
+ }
37906
+ case "isAlt": {
37907
+ const t = this.ex(e.e, sc, o);
37908
+ const r = t.k === "record" ? this.records.get(t.name) : null;
37909
+ if (!r?.altMap) {
37910
+ if (known(t)) this.err("TC305", line, `"is ${e.text}" asks which alternative a value is, but this is ${typeWords4(t)}, not a data type with alternatives.`);
37911
+ return T("bool");
37912
+ }
37913
+ if (!r.altMap.has(e.alt)) {
37914
+ this.err("TC217", line, `A ${r.text} is ${this.altList(r)}; "${e.text}" isn't one of them.`);
37915
+ return T("bool");
37916
+ }
37917
+ const neg2 = e.neg;
37918
+ Object.assign(e, this.altTest(e.e, r, e.alt, false, line));
37919
+ return T("bool");
37920
+ }
37453
37921
  case "today":
37454
37922
  case "date":
37455
37923
  return T("date");
@@ -37477,6 +37945,20 @@ var Checker = class {
37477
37945
  case "field": {
37478
37946
  const ot = this.ex(e.obj, sc, o);
37479
37947
  const r = ot.k === "record" ? this.records.get(ot.name) : null;
37948
+ if (r) e.record = r.name;
37949
+ if (r?.altMap && e.name !== "which" && r.fieldMap.has(e.name)) {
37950
+ const alt = this.narrowed(e.obj);
37951
+ const a = alt ? r.altMap.get(alt) : null;
37952
+ const owners = [...r.altMap.values()].filter((x) => x.fieldMap.has(e.name));
37953
+ const f = a?.fieldMap.get(e.name);
37954
+ e.py = r.fieldMap.get(e.name).py;
37955
+ e.static = true;
37956
+ if (f) return f.type;
37957
+ const who = owners.map((x) => x.text.toLowerCase()).join(" or ");
37958
+ if (a) this.err("TC216", line, `A ${a.text.toLowerCase()} ${r.text} has no ${e.text}; only a ${who} one does.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(", ") || "none"}.`);
37959
+ else this.err("TC216", line, `Only a ${who} ${r.text} has ${/^[aeiou]/i.test(e.text) ? "an" : "a"} ${e.text}, and here it could be any of them.`, e.obj.k === "name" ? `Check which it is first: put this under "Depending on ${e.obj.text}:" in the ${owners[0]?.text ?? ""} case, or under "If ${e.obj.text} is ${owners[0]?.text.toLowerCase() ?? ""}:".` : `Set it to a name first, then check which it is with "Depending on \u2026:".`);
37960
+ return UNKNOWN;
37961
+ }
37480
37962
  if (r) {
37481
37963
  const f = r.fieldMap.get(e.name);
37482
37964
  if (!f) {
@@ -37630,7 +38112,13 @@ var Checker = class {
37630
38112
  return this.arith(e.op, l, r, line);
37631
38113
  }
37632
38114
  case "cmp": {
37633
- const l = this.ex(e.l, sc, o), r = this.ex(e.r, sc, o);
38115
+ const l = this.ex(e.l, sc, o);
38116
+ const lr = l.k === "record" ? this.records.get(l.name) : null;
38117
+ if (lr?.altMap && e.r.k === "name" && !sc.get(e.r.name) && !this.global.vars.get(e.r.name)) {
38118
+ this.err("TC217", line, `A ${lr.text} is ${this.altList(lr)}; "${e.r.text}" isn't one of them.`);
38119
+ return T("bool");
38120
+ }
38121
+ const r = this.ex(e.r, sc, o);
37634
38122
  this.comparable(l, r, line, e.op);
37635
38123
  return T("bool");
37636
38124
  }
@@ -37667,6 +38155,11 @@ var Checker = class {
37667
38155
  if (el) {
37668
38156
  const r = el.type.k === "record" ? this.records.get(el.type.name) : null;
37669
38157
  if (r && r.fieldMap.has(e.name)) {
38158
+ const shadowed = sc.get(e.name);
38159
+ if (shadowed && ["param", "input", "var", "item", "state"].includes(shadowed.kind) && !el.reported?.has(e.name)) {
38160
+ (el.reported ??= /* @__PURE__ */ new Set()).add(e.name);
38161
+ this.err("TC219", e.line, `Here "${e.text}" means each ${r.text}'s ${e.text}, so your own "${e.text}"${shadowed.line ? ` (line ${shadowed.line})` : ""} isn't used.`, `Give your value another name, for example "wanted ${e.text}", and write: where ${e.text} is wanted ${e.text}.`);
38162
+ }
37670
38163
  const f = r.fieldMap.get(e.name);
37671
38164
  e.ref = { kind: "elemField", py: f.py };
37672
38165
  return f.type;
@@ -37717,6 +38210,9 @@ var Checker = class {
37717
38210
  return UNKNOWN;
37718
38211
  }
37719
38212
  e.py = f.py;
38213
+ e.args.forEach((a, k) => {
38214
+ if (a.k === "draftHole" && !a.want && f.params[k]?.type) a.expected = f.params[k].type;
38215
+ });
37720
38216
  const ts = e.args.map((a) => this.ex(a, sc, o));
37721
38217
  const required = f.params.filter((p) => !p.dflt).length;
37722
38218
  if (ts.length < required || ts.length > f.params.length) {
@@ -37732,6 +38228,81 @@ var Checker = class {
37732
38228
  });
37733
38229
  return entry3?.ret ?? UNKNOWN;
37734
38230
  }
38231
+ /**
38232
+ * A hole in a draft (TC120): what kind of value it needs (written, or expected where it stands) and what is
38233
+ * available here with that kind. Thunder asks; it never chooses a value. The hole has its kind, so nothing else on
38234
+ * the line is reported because of it.
38235
+ */
38236
+ /** a successful Payment with amount $5: the alternative's own fields, all it needs, and "which" set for it. */
38237
+ newAlternative(e, r, sc, o) {
38238
+ const ty = T("record", { name: r.name, text: r.text });
38239
+ const a = e.alt ? r.altMap.get(e.alt) : null;
38240
+ if (!a) {
38241
+ for (const f of e.fields) this.ex(f.e, sc, o);
38242
+ const kinds = [...r.altMap.values()].map((x) => `a ${x.text.toLowerCase()} ${r.text}`);
38243
+ if (e.alt) this.err("TC217", e.line, `A ${r.text} is ${this.altList(r)}; "${e.altText}" isn't one of them.`);
38244
+ else this.err("TC217", e.line, `Say which ${r.text} it is: ${kinds.length <= 2 ? kinds.join(" or ") : `${kinds.slice(0, -1).join(", ")}, or ${kinds[kinds.length - 1]}`}.`, `For example: ${kinds[0]}${r.alts[0]?.fields.length ? " with \u2026" : ""}.`);
38245
+ return ty;
38246
+ }
38247
+ const given = /* @__PURE__ */ new Set();
38248
+ for (const f of e.fields) {
38249
+ const def = a.fieldMap.get(f.name);
38250
+ if (def && f.e.k === "draftHole" && !f.e.want) f.e.expected = def.type;
38251
+ const t = this.ex(f.e, sc, o);
38252
+ if (!def) {
38253
+ const others = [...r.altMap.values()].filter((x) => x.fieldMap.has(f.name)).map((x) => x.text.toLowerCase());
38254
+ this.err("TC206", e.line, `A ${a.text.toLowerCase()} ${r.text} has no field "${f.text}"${others.length ? ` (a ${others.join(" or ")} one does)` : ""}.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(", ") || "none"}.`);
38255
+ continue;
38256
+ }
38257
+ f.py = def.py;
38258
+ if (given.has(f.name)) this.err("TC203", e.line, `The field "${f.text}" is given twice.`);
38259
+ given.add(f.name);
38260
+ if (known(def.type) && known(t) && !compatible(def.type, t)) this.err("TC303", e.line, `A ${a.text.toLowerCase()} ${r.text}'s ${def.text} is ${typeWords4(def.type)}, but ${typeWords4(t)} was given.`);
38261
+ }
38262
+ const missing = a.fields.filter((f) => !given.has(f.name) && f.type.k !== "optional" && f.type.k !== "list" && f.type.k !== "map");
38263
+ if (missing.length) this.err("TC210", e.line, `A ${a.text.toLowerCase()} ${r.text} needs ${missing.map((f) => f.text).join(", ")}.`, `Write: a ${a.text.toLowerCase()} ${r.text} with ${a.fields.map((f) => `${f.text} \u2026`).join(" and ")}.`);
38264
+ e.fields.unshift({ name: "which", text: "which", py: "which", e: { k: "str", parts: [a.name], line: e.line, type: T("text") }, line: e.line });
38265
+ return ty;
38266
+ }
38267
+ draftHole(e, sc) {
38268
+ const named2 = (t) => !t ? t : t.k === "record" ? { ...t, text: this.records.get(t.name)?.text ?? t.text } : t.of ? { ...t, of: named2(t.of) } : t;
38269
+ const want = named2(e.want ?? e.expected ?? null);
38270
+ const same = (w, t) => {
38271
+ if (!known(w) || !known(t)) return false;
38272
+ if (w.k === "optional") return t.k === "optional" ? same(w.of, t.of) : same(w.of, t);
38273
+ if (w.k === "number") return t.k === "number" || t.k === "whole";
38274
+ if (w.k !== t.k) return false;
38275
+ if (w.k === "record") return w.name === t.name;
38276
+ if (w.k === "list") return !known(w.of) || same(w.of, t.of);
38277
+ return true;
38278
+ };
38279
+ const fits = (t) => !want || !known(want) || same(want, t);
38280
+ const what = { param: "input", input: "input", var: "value", state: "remembered value", item: "item", const: "kept value", store: "stored list" };
38281
+ const seen = /* @__PURE__ */ new Set();
38282
+ const available = [];
38283
+ for (let at2 = sc; at2; at2 = at2.parent) {
38284
+ for (const [name, v] of at2.vars) {
38285
+ if (seen.has(name) || !what[v.kind]) continue;
38286
+ seen.add(name);
38287
+ if (fits(v.type)) available.push({ name: v.text ?? name, what: what[v.kind], kind: known(v.type) ? typeWords4(v.type) : null });
38288
+ }
38289
+ }
38290
+ if (want && known(want)) {
38291
+ for (const f of this.funcs.values()) {
38292
+ const ret = this.global.vars.get(f.name)?.ret;
38293
+ if (same(want, ret)) available.push({ name: f.text, what: "function", kind: typeWords4(ret), call: f.params.length ? `${f.text} with ${f.params.map((p) => p.text).join(" and ")}` : f.text });
38294
+ }
38295
+ }
38296
+ const needs = want ? typeWords4(want) : "a value";
38297
+ const typed = want && known(want);
38298
+ const shown = available.slice(0, 8).map((a) => a.what === "function" ? `${a.call} (a function)` : `${a.name} (${a.what}${!typed && a.kind ? `, ${a.kind}` : ""})`);
38299
+ const more = available.length > 8 ? `, and ${available.length - 8} more` : "";
38300
+ const hint = !available.length ? `Nothing here is ${needs} yet. Write the value, or receive it as an input.` : typed ? `Here, ${needs} could come from: ${shown.join(", ")}${more}.` : `Values here: ${shown.join(", ")}${more}. Write the kind after the ? (?number) to see only what fits.`;
38301
+ const d = diag("TC120", e.line, `This is a hole: it needs ${needs}, and Thunder won't choose it for you. Fill it in before the program can run.`, hint);
38302
+ d.hole = { col: e.col ?? null, needs: want ? needs : null, written: !!e.want, available };
38303
+ this.d.push(d);
38304
+ return want ?? UNKNOWN;
38305
+ }
37735
38306
  newRecord(e, sc, o) {
37736
38307
  const r = this.records.get(e.record);
37737
38308
  if (!r) {
@@ -37739,9 +38310,11 @@ var Checker = class {
37739
38310
  return UNKNOWN;
37740
38311
  }
37741
38312
  e.py = r.py;
38313
+ if (r.altMap) return this.newAlternative(e, r, sc, o);
37742
38314
  const given = /* @__PURE__ */ new Set();
37743
38315
  for (const f of e.fields) {
37744
38316
  const def = r.fieldMap.get(f.name);
38317
+ if (f.e.k === "draftHole" && !f.e.want && def?.type) f.e.expected = def.type;
37745
38318
  const t = this.ex(f.e, sc, o);
37746
38319
  if (!def) {
37747
38320
  const g = closest(f.name, [...r.fieldMap.keys()]);
@@ -38032,6 +38605,12 @@ var Gen = class {
38032
38605
  this.blank();
38033
38606
  for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line);
38034
38607
  }
38608
+ const stores = (this.info.stores ?? []).filter(own);
38609
+ if (stores.length) {
38610
+ this.blank();
38611
+ const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
38612
+ 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);
38613
+ }
38035
38614
  const tests = this.info.tests;
38036
38615
  for (const t of tests) {
38037
38616
  this.blank();
@@ -38046,16 +38625,29 @@ var Gen = class {
38046
38625
  for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
38047
38626
  this.emit("]");
38048
38627
  }
38628
+ const endpoints = (this.info.endpoints ?? []).filter(own);
38629
+ if (endpoints.length) {
38630
+ this.blank();
38631
+ const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
38632
+ this.emit("THUNDER_ROUTES = [");
38633
+ for (const f of endpoints) {
38634
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
38635
+ 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"})`);
38636
+ this.emit(` (${py(f.endpoint.method)}, ${py(f.endpoint.path)}, ${f.py}, [${ins.join(", ")}]),`, f.line);
38637
+ }
38638
+ this.emit("]");
38639
+ }
38049
38640
  const main = this.p.main ?? [];
38050
38641
  this.blank();
38051
- if (main.length) {
38642
+ if (main.length || endpoints.length) {
38052
38643
  this.emit("def main():");
38053
38644
  this.ind++;
38054
- this.block(main);
38645
+ if (main.length) this.block(main);
38646
+ else this.emit("pass");
38055
38647
  this.ind--;
38056
38648
  this.blank();
38057
38649
  this.emit('if __name__ == "__main__":');
38058
- this.emit(` ${this.R("run")}(main, __file__)`);
38650
+ this.emit(` ${this.R("run")}(main, __file__${endpoints.length ? ", routes=THUNDER_ROUTES" : ""})`);
38059
38651
  }
38060
38652
  body2.push(...this.out);
38061
38653
  const head = [
@@ -38089,6 +38681,7 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
38089
38681
  this.emit(`${f.py}: ${t}${dflt}`, f.line);
38090
38682
  }
38091
38683
  if (!r.fields.length) this.emit("pass");
38684
+ 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);
38092
38685
  const rules = r.rulesToCheck ?? [];
38093
38686
  if (rules.length) {
38094
38687
  this.out.push("");
@@ -38187,11 +38780,14 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
38187
38780
  return;
38188
38781
  }
38189
38782
  case "give":
38783
+ if (s.status != null) this.emit(`${this.R("answer_status")}(${s.status})`, L);
38190
38784
  this.emit(s.e.k === "nothing" ? "return None" : `return ${this.x(s.e).c}`, L);
38191
38785
  return;
38192
- case "stop":
38193
- 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);
38786
+ case "stop": {
38787
+ const msg = s.e.type?.k === "text" ? this.x(s.e).c : `${this.R("show")}(${this.x(s.e).c})`;
38788
+ this.emit(s.status != null ? `raise ${this.R("stop_with")}(${msg}, ${s.status})` : `raise ${this.R("Stop")}(${msg})`, L);
38194
38789
  return;
38790
+ }
38195
38791
  case "if":
38196
38792
  s.branches.forEach((b, k) => {
38197
38793
  this.emit(`${k === 0 ? "if" : "elif"} ${this.yn(b.cond).c}:`, b.line);
@@ -38242,6 +38838,14 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
38242
38838
  case "remove": {
38243
38839
  const v = this.x(s.e).c;
38244
38840
  const target = this.lv(s.target);
38841
+ if (s.guard) {
38842
+ const copy = `_copy_${s.line}_`;
38843
+ this.emit(`${copy} = list(${target})`, L);
38844
+ this.emit(s.k === "add" ? `${copy}.append(${v})` : `${this.R("remove_from")}(${copy}, ${v})`, L);
38845
+ if (s.target.k === "name") this.assign(s, target, copy);
38846
+ else this.store(s.target, copy, L);
38847
+ return;
38848
+ }
38245
38849
  if (s.targetKind === "list") this.emit(s.k === "add" ? `${target}.append(${v})` : `${this.R("remove_from")}(${target}, ${v})`, L);
38246
38850
  else if (s.targetKind === "map") this.emit(`${this.R("remove_from")}(${target}, ${v})`, L);
38247
38851
  else if (s.targetKind === "number") {
@@ -38419,6 +39023,12 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
38419
39023
  return A("None");
38420
39024
  case "paren":
38421
39025
  return sub2(e.e);
39026
+ // the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
39027
+ case "httpCall": {
39028
+ const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
39029
+ 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";
39030
+ return A(`${this.R("http_call")}(${py(e.method)}, ${sub2(e.url).c}, ${e.body ? sub2(e.body).c : "None"}, ${as})`);
39031
+ }
38422
39032
  case "today":
38423
39033
  this.needDate = true;
38424
39034
  return A("date.today()");
@@ -39373,7 +39983,8 @@ def _callers(tb):
39373
39983
 
39374
39984
 
39375
39985
  def describe_error(error):
39376
- src, line, from_python = thunder_place(error.__traceback__)
39986
+ placed = getattr(error, "thunder_where", None) # a stored list's file: its Store line
39987
+ src, line, from_python = (*placed, False) if placed else thunder_place(error.__traceback__)
39377
39988
  message = explain(error)
39378
39989
  code = _code(error)
39379
39990
  # Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
@@ -39388,15 +39999,376 @@ def describe_error(error):
39388
39999
  return "%s: %s [%s]" % (where, message, code)
39389
40000
 
39390
40001
 
39391
- def run(main, file=None):
39392
- """Runs a generated program; an error is reported against the Thunder line, then the program exits with 1."""
40002
+ # ── Stored lists (Store habits as a list of Habit): data/<name>.json, the format of store-format.mjs ─────────────
40003
+ _STORES = []
40004
+ _STORE_KINDS = {"whole": "a whole number", "number": "a number", "money": "money", "text": "text", "bool": "yes or no", "date": "a date"}
40005
+
40006
+
40007
+ def new_store(source, line, name, cls, kinds):
40008
+ """A stored list: empty until the program starts (run fills it), saved when the program finishes well.
40009
+ A file it can't read is reported at its Store line (source, line), as on the Thunder engine and TypeScript."""
40010
+ items = []
40011
+ _STORES.append((source, line, name, cls, kinds, items))
40012
+ return items
40013
+
40014
+
40015
+ def _store_encode(v, kind):
40016
+ if kind.startswith("?"):
40017
+ return None if v is None else _store_encode(v, kind[1:])
40018
+ if v is None:
40019
+ return None
40020
+ if kind == "whole":
40021
+ return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
40022
+ if kind == "number":
40023
+ return str(v)
40024
+ if kind == "money":
40025
+ return str(v).replace("$", "")
40026
+ if kind == "date":
40027
+ return v.isoformat()
40028
+ return v
40029
+
40030
+
40031
+ def _store_decode(x, kind, where, has="the file has"):
40032
+ if kind.startswith("?"):
40033
+ return None if x is None else _store_decode(x, kind[1:], where, has)
40034
+ def bad():
40035
+ return ConversionFailed("%s should be %s, but %s %s." % (where, _STORE_KINDS.get(kind, "a value"), has, json.dumps(x)))
40036
+ if kind == "whole":
40037
+ if isinstance(x, int) and not isinstance(x, bool):
40038
+ return x
40039
+ if isinstance(x, str) and re.fullmatch(r"-?\d+", x):
40040
+ return int(x)
40041
+ raise bad()
40042
+ if kind == "number":
40043
+ if isinstance(x, int) and not isinstance(x, bool):
40044
+ return x
40045
+ if isinstance(x, str):
40046
+ if re.fullmatch(r"-?\d+", x):
40047
+ return int(x)
40048
+ try:
40049
+ return Decimal(x)
40050
+ except InvalidOperation:
40051
+ raise bad()
40052
+ raise bad()
40053
+ if kind == "money":
40054
+ try:
40055
+ return Money(Decimal(str(x)))
40056
+ except (InvalidOperation, ValueError):
40057
+ raise bad()
40058
+ if kind == "text":
40059
+ if isinstance(x, str):
40060
+ return x
40061
+ raise bad()
40062
+ if kind == "bool":
40063
+ if isinstance(x, bool):
40064
+ return x
40065
+ raise bad()
40066
+ if kind == "date":
40067
+ try:
40068
+ return date.fromisoformat(x)
40069
+ except (TypeError, ValueError):
40070
+ raise bad()
40071
+ return x
40072
+
40073
+
40074
+ def _store_file(name):
40075
+ return "data/%s.json" % name
40076
+
40077
+
40078
+ def _fill_stores():
40079
+ import os
40080
+ for source, line, name, cls, kinds, items in _STORES:
40081
+ path = _store_file(name)
40082
+ if not os.path.exists(path):
40083
+ continue
40084
+ try:
40085
+ items[:] = _read_store(path, cls, kinds)
40086
+ except Exception as error: # noqa: BLE001 - reported at the Store line
40087
+ error.thunder_where = (source, line)
40088
+ raise
40089
+
40090
+
40091
+ def _read_store(path, cls, kinds):
40092
+ """The records in a store's file; a problem names the item and field."""
40093
+ with open(path, encoding="utf-8") as fh:
40094
+ text = fh.read()
40095
+ try:
40096
+ rows = json.loads(text)
40097
+ except ValueError as error:
40098
+ raise ConversionFailed("%s is not a list Thunder can read (%s)." % (path, error))
40099
+ if not isinstance(rows, list):
40100
+ raise ConversionFailed("%s should hold a list, written [ … ]." % path)
40101
+ return [_record_from(row, cls, kinds, "%s, item %d" % (path, i + 1)) for i, row in enumerate(rows)]
40102
+
40103
+
40104
+ def _record_from(row, cls, kinds, where, has="the file has"):
40105
+ """A record from a JSON object, each field read by its kind; a problem names where it is and the field."""
40106
+ if not isinstance(row, dict):
40107
+ raise ConversionFailed("%s should be a record, written { … }." % where)
40108
+ given = {}
40109
+ for field_name, kind in kinds.items():
40110
+ if field_name not in row:
40111
+ if kind.startswith("?"):
40112
+ given[field_name] = None
40113
+ continue
40114
+ raise ConversionFailed('%s has no "%s".' % (where, field_name))
40115
+ given[field_name] = _store_decode(row[field_name], kind, '%s, "%s"' % (where, field_name), has)
40116
+ return cls(**given)
40117
+
40118
+
40119
+ def _save_stores():
40120
+ import os
40121
+ for source, line, name, cls, kinds, items in _STORES:
40122
+ path = _store_file(name)
40123
+ rows = [{f: _store_encode(getattr(item, f), kind) for f, kind in kinds.items()} for item in items]
40124
+ os.makedirs(os.path.dirname(path), exist_ok=True)
40125
+ with open(path + ".saving", "w", encoding="utf-8") as fh:
40126
+ fh.write(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
40127
+ os.replace(path + ".saving", path)
40128
+
40129
+
40130
+ # ── HTTP (When someone calls GET /habits: and the answer from GET "…"): data in the stored-list format ──────────
40131
+ class CallFailed(ThunderError):
40132
+ code = "TC510"
40133
+
40134
+
40135
+ _ANSWER_STATUS = [None]
40136
+
40137
+
40138
+ def answer_status(status):
40139
+ """Give … with status 201: the status this request answers with (a direct call in a test ignores it)."""
40140
+ _ANSWER_STATUS[0] = status
40141
+
40142
+
40143
+ def stop_with(message, status):
40144
+ """Stop with "…" and status 404: a Stop that an endpoint answers with that status."""
40145
+ error = Stop(message)
40146
+ error.status = status
40147
+ return error
40148
+
40149
+
40150
+ def _data_ready(v):
40151
+ """A value as JSON data, written by its kind: whole numbers as numbers (text when too large), numbers and money as
40152
+ exact text, dates as "2026-11-28", records as objects. The same on every target."""
40153
+ if v is None or isinstance(v, (bool, str)):
40154
+ return v
40155
+ if isinstance(v, int):
40156
+ return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
40157
+ if isinstance(v, Decimal):
40158
+ return str(v)
40159
+ if isinstance(v, Money):
40160
+ return str(v).replace("$", "", 1)
40161
+ if isinstance(v, date):
40162
+ return v.isoformat()
40163
+ if isinstance(v, (list, tuple)):
40164
+ return [_data_ready(x) for x in v]
40165
+ if isinstance(v, dict):
40166
+ out = {}
40167
+ for k, x in v.items():
40168
+ if not isinstance(k, str):
40169
+ raise KindMismatch("A JSON object's keys are text, but one is %s." % show(k))
40170
+ out[k] = _data_ready(x)
40171
+ return out
40172
+ if is_dataclass(v):
40173
+ alts = getattr(type(v), "__thunder_alts__", None)
40174
+ if alts is not None: # an alternative of a data type: "which" and the fields it has
40175
+ keep = ("which",) + tuple(alts.get(v.which, ()))
40176
+ return {name: _data_ready(getattr(v, name)) for name in keep}
40177
+ return {f.name: _data_ready(getattr(v, f.name)) for f in fields(v)}
40178
+ raise KindMismatch("%s can't be sent as JSON." % show(v))
40179
+
40180
+
40181
+ def data_json(v):
40182
+ return json.dumps(_data_ready(v), ensure_ascii=False, separators=(",", ":"))
40183
+
40184
+
40185
+ def _unreachable_reason(error):
40186
+ """Why a service could not be reached, in words that are the same on every target."""
40187
+ import socket
40188
+ reason = getattr(error, "reason", error)
40189
+ if isinstance(reason, (TimeoutError, socket.timeout)):
40190
+ return "no answer within 30 seconds"
40191
+ if isinstance(reason, ConnectionRefusedError):
40192
+ return "nothing is answering there"
40193
+ if isinstance(reason, socket.gaierror):
40194
+ return "the address could not be found"
40195
+ return str(reason)
40196
+
40197
+
40198
+ def http_call(method, url, body, read_as):
40199
+ """the answer from GET "…": the answer's text, or records read from it (read_as = (record, kinds, many))."""
40200
+ import urllib.error
40201
+ import urllib.request
40202
+ where = "The answer from %s %s" % (method, url)
40203
+ data = data_json(body).encode("utf-8") if body is not None else None
40204
+ headers = {"Accept": "application/json"}
40205
+ if data is not None:
40206
+ headers["Content-Type"] = "application/json"
40207
+ request = urllib.request.Request(url, data=data, method=method, headers=headers)
40208
+ try:
40209
+ with urllib.request.urlopen(request, timeout=30) as reply:
40210
+ text = reply.read().decode("utf-8")
40211
+ except urllib.error.HTTPError as error:
40212
+ raise CallFailed("%s %s answered %d: %s" % (method, url, error.code, error.read().decode("utf-8", "replace").strip()[:300]))
40213
+ except (urllib.error.URLError, OSError, ValueError) as error:
40214
+ raise CallFailed("%s %s could not be reached (%s)." % (method, url, _unreachable_reason(error)))
40215
+ if read_as is None:
40216
+ return text
40217
+ cls, kinds, many = read_as
39393
40218
  try:
40219
+ answer = json.loads(text)
40220
+ except ValueError:
40221
+ raise ConversionFailed("%s is not JSON Thunder can read." % where)
40222
+ if many:
40223
+ if not isinstance(answer, list):
40224
+ raise ConversionFailed("%s should be a list, written [ … ]." % where)
40225
+ return [_record_from(row, cls, kinds, "%s, item %d" % (where, i + 1), "it has") for i, row in enumerate(answer)]
40226
+ return _record_from(answer, cls, kinds, where, "it has")
40227
+
40228
+
40229
+ def _input_value(raw, kind, where, from_text):
40230
+ """A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false."""
40231
+ plain = kind.lstrip("?")
40232
+ if from_text and plain == "bool" and isinstance(raw, str) and raw.lower() in ("yes", "no", "true", "false"):
40233
+ raw = raw.lower() in ("yes", "true")
40234
+ return _store_decode(raw, kind, where, "the request has")
40235
+
40236
+
40237
+ def _serve(routes):
40238
+ """Answer requests on this machine, one at a time, until stopped (Ctrl+C). Stored lists are saved after each
40239
+ request that finishes well."""
40240
+ import os
40241
+ import urllib.parse
40242
+ from http.server import BaseHTTPRequestHandler, HTTPServer
40243
+
40244
+ host = os.environ.get("THUNDER_HOST", "127.0.0.1")
40245
+ port = int(os.environ.get("THUNDER_PORT", "8080"))
40246
+ table = []
40247
+ for method, path, handler, inputs in routes:
40248
+ parts = [p for p in path.split("/") if p]
40249
+ table.append((method, path, parts, handler, inputs))
40250
+
40251
+ def match(parts, request_parts):
40252
+ if len(parts) != len(request_parts):
40253
+ return None
40254
+ found = {}
40255
+ for want, got in zip(parts, request_parts):
40256
+ if want.startswith("{") and want.endswith("}"):
40257
+ found[want[1:-1].strip().lower()] = urllib.parse.unquote(got)
40258
+ elif want != got:
40259
+ return None
40260
+ return found
40261
+
40262
+ class Handler(BaseHTTPRequestHandler):
40263
+ server_version = "Thunder"
40264
+
40265
+ def answer(self, status, value):
40266
+ data = data_json(value).encode("utf-8")
40267
+ self.send_response(status)
40268
+ self.send_header("Content-Type", "application/json; charset=utf-8")
40269
+ self.send_header("Content-Length", str(len(data)))
40270
+ self.end_headers()
40271
+ self.wfile.write(data)
40272
+ print("%s %s -> %d" % (self.command, self.path, status), flush=True)
40273
+
40274
+ def handle_any(self):
40275
+ url = urllib.parse.urlsplit(self.path)
40276
+ request_parts = [p for p in url.path.split("/") if p]
40277
+ query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()}
40278
+ chosen, methods = None, []
40279
+ for method, path, parts, handler, inputs in table:
40280
+ found = match(parts, request_parts)
40281
+ if found is None:
40282
+ continue
40283
+ methods.append(method)
40284
+ if method == self.command:
40285
+ chosen = (method, path, handler, inputs, found)
40286
+ if chosen is None:
40287
+ if methods:
40288
+ return self.answer(405, {"problem": "%s answers only %s." % (url.path, ", ".join(methods))})
40289
+ return self.answer(404, {"problem": "Nothing here answers %s %s." % (self.command, url.path)})
40290
+ method, path, handler, inputs, found = chosen
40291
+ body = {}
40292
+ length = int(self.headers.get("Content-Length") or 0)
40293
+ if length:
40294
+ try:
40295
+ body = json.loads(self.rfile.read(length).decode("utf-8"))
40296
+ except ValueError:
40297
+ return self.answer(400, {"problem": "The request's body is not JSON Thunder can read."})
40298
+ if not isinstance(body, dict):
40299
+ return self.answer(400, {"problem": "The request's body should be a JSON object, written { … }."})
40300
+ args = {}
40301
+ try:
40302
+ for text, py_name, kind, source, has_default in inputs:
40303
+ key = text.lower()
40304
+ if source == "path":
40305
+ args[py_name] = _input_value(found[key], kind, '"%s"' % text, True)
40306
+ elif key in query:
40307
+ args[py_name] = _input_value(query[key], kind, '"%s"' % text, True)
40308
+ elif py_name in query:
40309
+ args[py_name] = _input_value(query[py_name], kind, '"%s"' % text, True)
40310
+ elif text in body or key in body or py_name in body:
40311
+ raw = body[text] if text in body else body[key] if key in body else body[py_name]
40312
+ args[py_name] = _input_value(raw, kind, '"%s"' % text, False)
40313
+ elif not has_default:
40314
+ if kind.startswith("?"):
40315
+ args[py_name] = None
40316
+ else:
40317
+ return self.answer(400, {"problem": "%s %s needs %s (%s)." % (method, path, text, _STORE_KINDS.get(kind, kind))})
40318
+ except ThunderError as error:
40319
+ return self.answer(400, {"problem": explain(error)})
40320
+ _ANSWER_STATUS[0] = None
40321
+ try:
40322
+ value = handler(**args)
40323
+ except Stop as error:
40324
+ return self.answer(getattr(error, "status", 400), {"problem": explain(error)})
40325
+ except RuleBroken as error:
40326
+ return self.answer(422, {"problem": explain(error)})
40327
+ except Exception as error: # noqa: BLE001 - reported in Thunder words, the server keeps answering
40328
+ print(describe_error(error), file=sys.stderr, flush=True)
40329
+ return self.answer(500, {"problem": explain(error)})
40330
+ status = _ANSWER_STATUS[0] or 200
40331
+ try:
40332
+ _save_stores()
40333
+ data = data_json(value)
40334
+ except Exception as error: # noqa: BLE001
40335
+ print(describe_error(error), file=sys.stderr, flush=True)
40336
+ return self.answer(500, {"problem": explain(error)})
40337
+ self.answer(status, json.loads(data) if data != "null" else None)
40338
+
40339
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
40340
+
40341
+ def log_message(self, *args):
40342
+ pass
40343
+
40344
+ server = HTTPServer((host, port), Handler)
40345
+ print("Thunder is answering on http://%s:%d" % (host, port), flush=True)
40346
+ for method, path, handler, inputs in routes:
40347
+ print(" %s %s" % (method, path), flush=True)
40348
+ print("Press Ctrl+C to stop.", flush=True)
40349
+ try:
40350
+ server.serve_forever()
40351
+ except KeyboardInterrupt:
40352
+ print("Stopped answering.", flush=True)
40353
+ finally:
40354
+ server.server_close()
40355
+
40356
+
40357
+ def run(main, file=None, routes=None):
40358
+ """Runs a generated program; an error is reported against the Thunder line, then the program exits with 1.
40359
+ Stored lists are filled first and saved only when the program finishes well. With endpoints, it then answers
40360
+ requests until stopped."""
40361
+ try:
40362
+ _fill_stores()
39394
40363
  main()
40364
+ _save_stores()
39395
40365
  except KeyboardInterrupt:
39396
40366
  raise
39397
40367
  except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
39398
40368
  print(describe_error(error), file=sys.stderr)
39399
40369
  sys.exit(1)
40370
+ if routes:
40371
+ _serve(routes)
39400
40372
 
39401
40373
 
39402
40374
  def run_tests(modules):
@@ -39420,19 +40392,26 @@ def run_tests(modules):
39420
40392
  `;
39421
40393
 
39422
40394
  // src/core/index.mjs
39423
- function compileCore(source, { file = "main.thunder", imported = [], srcModules = [] } = {}) {
39424
- const seed = imported.length ? {
40395
+ function seedFrom(imported = []) {
40396
+ return imported.length ? {
39425
40397
  known: imported.flatMap((r) => [...r.program.names.known].filter(([, kind]) => kind !== "var")),
39426
40398
  fields: imported.flatMap((r) => [...r.program.names.fields]),
39427
40399
  records: imported.flatMap((r) => [...r.program.names.records]),
39428
40400
  recordFields: imported.flatMap((r) => [...r.program.names.recordFields ?? []]),
39429
- funcInputs: imported.flatMap((r) => [...r.program.names.funcInputs ?? []])
40401
+ funcInputs: imported.flatMap((r) => [...r.program.names.funcInputs ?? []]),
40402
+ alts: imported.flatMap((r) => [...r.program.names.alts ?? []]),
40403
+ altsOf: imported.flatMap((r) => [...r.program.names.altsOf ?? []])
39430
40404
  } : null;
40405
+ }
40406
+ function compileCore(source, { file = "main.thunder", imported = [], srcModules = [] } = {}) {
40407
+ const seed = seedFrom(imported);
39431
40408
  const program = parseCore(source, { seed });
39432
40409
  const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
39433
40410
  const ok = diagnostics.length === 0;
39434
40411
  const python = ok ? toPython(program, info, { source: file, imports: srcModules }) : null;
39435
- return { ok, diagnostics, python, program, info, file };
40412
+ const holes = diagnostics.filter((d) => d.code === "TC120");
40413
+ const draft = holes.length > 0 && holes.length === diagnostics.length;
40414
+ return { ok, diagnostics, python, program, info, file, holes, draft };
39436
40415
  }
39437
40416
 
39438
40417
  // src/core/engine-values.mjs
@@ -39451,6 +40430,7 @@ var KindMismatch = (m) => new ThunderErr("TC506", m, "TypeError");
39451
40430
  var ConversionFailed = (m) => new ThunderErr("TC509", m, "ValueError");
39452
40431
  var MissingValue = (m) => new ThunderErr("TC503", m, "LookupError");
39453
40432
  var DividedByZero = (m) => new ThunderErr("TC501", m, "ZeroDivisionError");
40433
+ var CallFailed = (m) => new ThunderErr("TC510", m, "CallFailed");
39454
40434
  var PyErr = class extends Error {
39455
40435
  constructor(pyType2, message2, args) {
39456
40436
  super(message2);
@@ -40385,6 +41365,14 @@ function addTo(target, value) {
40385
41365
  }
40386
41366
  return add(target, value);
40387
41367
  }
41368
+ function copyList(target) {
41369
+ if (!Array.isArray(target)) throw attrErr(target, "append");
41370
+ return [...target];
41371
+ }
41372
+ function appendTo(target, value) {
41373
+ if (!Array.isArray(target)) throw attrErr(target, "append");
41374
+ target.push(value);
41375
+ }
40388
41376
  function removeFrom(target, value) {
40389
41377
  if (target instanceof PyDict) {
40390
41378
  if (!target.has(value)) throw MissingValue(`There is no entry for ${show2(value)} to remove.`);
@@ -40617,6 +41605,120 @@ function stripPunct(w) {
40617
41605
  return a.slice(i, j).join("");
40618
41606
  }
40619
41607
 
41608
+ // src/core/store-format.mjs
41609
+ var kindWords3 = { whole: "a whole number", number: "a number", money: "money", text: "text", bool: "yes or no", date: "a date" };
41610
+ function encode(v, t) {
41611
+ if (t.k === "optional") return v === null || v === void 0 ? null : encode(v, t.of);
41612
+ if (v === null || v === void 0) return null;
41613
+ switch (t.k) {
41614
+ case "whole":
41615
+ return typeof v === "bigint" && v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
41616
+ case "number":
41617
+ return String(v);
41618
+ case "money":
41619
+ return v instanceof Money ? v.toString().replace("$", "") : String(v);
41620
+ case "date":
41621
+ return v instanceof PyDate ? v.iso() : String(v);
41622
+ default:
41623
+ return v;
41624
+ }
41625
+ }
41626
+ function decode(x, t, where2, has2 = "the file has") {
41627
+ if (t.k === "optional") return x === null ? null : decode(x, t.of, where2, has2);
41628
+ const bad = () => ConversionFailed(`${where2} should be ${kindWords3[t.k] ?? "a value"}, but ${has2} ${JSON.stringify(x)}.`);
41629
+ switch (t.k) {
41630
+ case "whole":
41631
+ if (typeof x === "number" && Number.isInteger(x)) return BigInt(x);
41632
+ if (typeof x === "string" && /^-?\d+$/.test(x)) return BigInt(x);
41633
+ throw bad();
41634
+ case "number": {
41635
+ if (typeof x === "number" && Number.isInteger(x)) return BigInt(x);
41636
+ const d = typeof x === "string" ? Dec.parse(x) : null;
41637
+ if (!d) throw bad();
41638
+ return /^-?\d+$/.test(x) ? BigInt(x) : d;
41639
+ }
41640
+ case "money": {
41641
+ const d = typeof x === "string" ? Dec.parse(x) : typeof x === "number" ? Dec.parse(String(x)) : null;
41642
+ if (!d) throw bad();
41643
+ return new Money(d);
41644
+ }
41645
+ case "text":
41646
+ if (typeof x === "string") return x;
41647
+ throw bad();
41648
+ case "bool":
41649
+ if (typeof x === "boolean") return x;
41650
+ throw bad();
41651
+ case "date": {
41652
+ const d = typeof x === "string" ? PyDate.parse(x) : null;
41653
+ if (!d) throw bad();
41654
+ return d;
41655
+ }
41656
+ default:
41657
+ return x;
41658
+ }
41659
+ }
41660
+ function storeToText(list3, cls) {
41661
+ const rows = list3.map((rec) => Object.fromEntries(cls.fields.map((f) => [f.py, encode(rec.f.get(f.py), f.type ?? { k: "text" })])));
41662
+ return `${JSON.stringify(rows, null, 2)}
41663
+ `;
41664
+ }
41665
+ function storeFromText(text2, cls, name, make) {
41666
+ let rows;
41667
+ try {
41668
+ rows = JSON.parse(text2);
41669
+ } catch (e) {
41670
+ throw ConversionFailed(`${name} is not a list Thunder can read (${e.message}).`);
41671
+ }
41672
+ if (!Array.isArray(rows)) throw ConversionFailed(`${name} should hold a list, written [ \u2026 ].`);
41673
+ return rows.map((row, i) => recordFrom(row, cls, `${name}, item ${i + 1}`, make));
41674
+ }
41675
+ function recordFrom(row, cls, where2, make, has2 = "the file has") {
41676
+ if (!row || typeof row !== "object" || Array.isArray(row)) throw ConversionFailed(`${where2} should be a record, written { \u2026 }.`);
41677
+ const given = /* @__PURE__ */ new Map();
41678
+ for (const f of cls.fields) {
41679
+ const t = f.type ?? { k: "text" };
41680
+ if (!(f.py in row)) {
41681
+ if (t.k === "optional") {
41682
+ given.set(f.py, null);
41683
+ continue;
41684
+ }
41685
+ throw ConversionFailed(`${where2} has no "${f.py}".`);
41686
+ }
41687
+ given.set(f.py, decode(row[f.py], t, `${where2}, "${f.py}"`, has2));
41688
+ }
41689
+ return make(given);
41690
+ }
41691
+ function dataReady(v) {
41692
+ if (v === null || v === void 0 || typeof v === "boolean" || typeof v === "string") return v ?? null;
41693
+ if (typeof v === "bigint") return v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
41694
+ if (v instanceof Dec) return String(v);
41695
+ if (v instanceof Money) return v.toString().replace("$", "");
41696
+ if (v instanceof PyDate) return v.iso();
41697
+ if (Array.isArray(v)) return v.map(dataReady);
41698
+ if (v instanceof Tuple) return v.items.map(dataReady);
41699
+ if (v instanceof PyDict) {
41700
+ const out = {};
41701
+ for (const [k, x] of v.m.values()) {
41702
+ if (typeof k !== "string") throw KindMismatch(`A JSON object's keys are text, but one is ${show2(k)}.`);
41703
+ out[k] = dataReady(x);
41704
+ }
41705
+ return out;
41706
+ }
41707
+ if (v instanceof RecordVal) {
41708
+ const keep = v.cls.alts ? ["which", ...v.cls.alts[v.f.get("which")] ?? []] : v.cls.fields.map((f) => f.py);
41709
+ return Object.fromEntries(keep.map((py2) => [py2, dataReady(v.f.get(py2))]));
41710
+ }
41711
+ throw KindMismatch(`${show2(v)} can't be sent as JSON.`);
41712
+ }
41713
+ var dataJson = (v) => JSON.stringify(dataReady(v));
41714
+ function unreachableReason(out) {
41715
+ if (out.name === "TimeoutError" || out.name === "AbortError") return "no answer within 30 seconds";
41716
+ if (out.error === "ECONNREFUSED") return "nothing is answering there";
41717
+ if (out.error === "ENOTFOUND" || out.error === "EAI_AGAIN") return "the address could not be found";
41718
+ return out.error;
41719
+ }
41720
+ var storeFile = (s) => `data/${s.py.toLowerCase()}.json`;
41721
+
40620
41722
  // src/core/engine-core.mjs
40621
41723
  var Return = class {
40622
41724
  constructor(v) {
@@ -40632,6 +41734,8 @@ var nativeOverflow = (e) => {
40632
41734
  };
40633
41735
  var NeedsDeeperStack = class extends Error {
40634
41736
  };
41737
+ var OutOfSteps = class extends Error {
41738
+ };
40635
41739
  var MAX_FRAMES2 = MAX_FRAMES;
40636
41740
  var CONTAINER_KINDS = /* @__PURE__ */ new Set(["if", "each", "range", "times", "while", "tryFail"]);
40637
41741
  var MAX_RECORDED = 2e4;
@@ -40658,13 +41762,19 @@ var Engine = class {
40658
41762
  // readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
40659
41763
  // (a browser), reading a file is reported as a missing file.
40660
41764
  // record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
40661
- constructor({ cwd = ".", deeper = false, readText = null, record = false } = {}) {
41765
+ // http(method, url, bodyText) -> { status, text } | { error }: calls another service and waits for the answer.
41766
+ // Without it (a browser), "the answer from …" says it can't run here.
41767
+ constructor({ cwd = ".", deeper = false, readText = null, record = false, store = null, http = null } = {}) {
41768
+ this.http = http;
41769
+ this.answeredStatus = null;
41770
+ this.dataFiles = store;
40662
41771
  this.cwd = cwd;
40663
41772
  this.rec = record ? { steps: [], truncated: false } : null;
40664
41773
  this.readText = readText;
40665
41774
  this.deeper = deeper;
40666
41775
  this.frames = [];
40667
41776
  this.out = [];
41777
+ this.budget = null;
40668
41778
  }
40669
41779
  // ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
40670
41780
  load(result, imports = []) {
@@ -40673,6 +41783,12 @@ var Engine = class {
40673
41783
  for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
40674
41784
  for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
40675
41785
  for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
41786
+ mod.stores = (result.info.stores ?? []).filter(own).map((s) => {
41787
+ const list3 = [];
41788
+ mod.globals.set(s.py, list3);
41789
+ return { s, list: list3, cls: mod.globals.get(s.record.py) };
41790
+ });
41791
+ for (const m of imports) for (const st of m.stores ?? []) mod.stores.push(st);
40676
41792
  const consts = result.info.consts.filter(own);
40677
41793
  if (consts.length) {
40678
41794
  const frame = { file: mod.file, line: 0 };
@@ -40692,7 +41808,8 @@ var Engine = class {
40692
41808
  const f = r.fieldMap.get(rule.subject);
40693
41809
  (rules.get(f.py) ?? rules.set(f.py, []).get(f.py)).push(rule);
40694
41810
  }
40695
- return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod };
41811
+ const alts = r.alts ? Object.fromEntries(r.alts.map((a) => [a.name, a.fields.map((f) => f.py)])) : null;
41812
+ return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod, alts };
40696
41813
  }
40697
41814
  // ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
40698
41815
  withFrame(frame, fn) {
@@ -40701,7 +41818,7 @@ var Engine = class {
40701
41818
  try {
40702
41819
  return fn();
40703
41820
  } catch (e) {
40704
- if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
41821
+ if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
40705
41822
  if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
40706
41823
  const err = asPyErr(e);
40707
41824
  if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
@@ -40728,7 +41845,7 @@ var Engine = class {
40728
41845
  const locals = /* @__PURE__ */ new Map();
40729
41846
  const env = { mod, locals, frame };
40730
41847
  f.params.forEach((p, i) => {
40731
- let v = i < args.length ? args[i] : p.dflt ? p.dflt.k === "name" ? NOT_GIVEN : this.x(p.dflt, env) : void 0;
41848
+ let v = i < args.length && args[i] !== NOT_GIVEN ? args[i] : p.dflt ? p.dflt.k === "name" ? NOT_GIVEN : this.x(p.dflt, env) : void 0;
40732
41849
  if (v === void 0) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
40733
41850
  locals.set(p.py, v);
40734
41851
  });
@@ -40749,6 +41866,36 @@ var Engine = class {
40749
41866
  return null;
40750
41867
  });
40751
41868
  }
41869
+ /** the answer from GET "…" [with …] [as Rate]: the answer's text, or records read from it. */
41870
+ httpCall(e, env) {
41871
+ const url = this.x(e.url, env);
41872
+ const body2 = e.body ? dataJson(this.x(e.body, env)) : null;
41873
+ if (!this.http) throw CallFailed(`${e.method} ${pyStr(url)} can't be called here: calls to other services run with the thunder command, not in the browser.`);
41874
+ const out = this.http(e.method, url, body2);
41875
+ if (out.error) throw CallFailed(`${e.method} ${url} could not be reached (${unreachableReason(out)}).`);
41876
+ if (out.status < 200 || out.status > 299) throw CallFailed(`${e.method} ${url} answered ${out.status}: ${out.text.trim().slice(0, 300)}`);
41877
+ if (!e.record) return out.text;
41878
+ const where2 = `The answer from ${e.method} ${url}`;
41879
+ let data;
41880
+ try {
41881
+ data = JSON.parse(out.text);
41882
+ } catch {
41883
+ throw ConversionFailed(`${where2} is not JSON Thunder can read.`);
41884
+ }
41885
+ const cls = env.mod.globals.get(e.record.py);
41886
+ const make = (given) => this.newRecord(cls, given);
41887
+ if (e.as.k === "list") {
41888
+ if (!Array.isArray(data)) throw ConversionFailed(`${where2} should be a list, written [ \u2026 ].`);
41889
+ return data.map((row, i) => recordFrom(row, cls, `${where2}, item ${i + 1}`, make, "it has"));
41890
+ }
41891
+ return recordFrom(data, cls, where2, make, "it has");
41892
+ }
41893
+ /** An endpoint answering one request: its value and status, or the error it stopped with. Output so far is kept. */
41894
+ answer(mod, f, args) {
41895
+ this.answeredStatus = null;
41896
+ const value = this.call(mod.globals.get(f.py), args);
41897
+ return { value, status: this.answeredStatus ?? 200 };
41898
+ }
40752
41899
  never(rule, value, env) {
40753
41900
  never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value);
40754
41901
  }
@@ -40802,6 +41949,7 @@ var Engine = class {
40802
41949
  }
40803
41950
  }
40804
41951
  stmt(s, env) {
41952
+ if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
40805
41953
  if (this.rec) return this.recordStep(s, env);
40806
41954
  return this.runStmt(s, env);
40807
41955
  }
@@ -40890,11 +42038,16 @@ var Engine = class {
40890
42038
  this.storeAt(t, v, env);
40891
42039
  return;
40892
42040
  }
40893
- case "give":
40894
- throw new Return(s.e.k === "nothing" ? null : this.x(s.e, env));
42041
+ case "give": {
42042
+ const v = s.e.k === "nothing" ? null : this.x(s.e, env);
42043
+ if (s.status != null) this.answeredStatus = s.status;
42044
+ throw new Return(v);
42045
+ }
40895
42046
  case "stop": {
40896
42047
  const v = this.x(s.e, env);
40897
- throw Stop(s.e.type?.k === "text" ? pyStr(v) : show2(v));
42048
+ const err = Stop(s.e.type?.k === "text" ? pyStr(v) : show2(v));
42049
+ if (s.status != null) err.status = s.status;
42050
+ throw err;
40898
42051
  }
40899
42052
  case "if":
40900
42053
  for (const b of s.branches) {
@@ -40997,7 +42150,7 @@ var Engine = class {
40997
42150
  try {
40998
42151
  this.stmt(s.stmt, env);
40999
42152
  } catch (e) {
41000
- if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
42153
+ if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
41001
42154
  if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
41002
42155
  const err = asPyErr(e);
41003
42156
  fr.line = L;
@@ -41017,6 +42170,14 @@ var Engine = class {
41017
42170
  const isName2 = s.target.k === "name";
41018
42171
  const target = this.x(s.target, env);
41019
42172
  const py2 = isName2 ? s.target.ref?.py ?? "unknown" : null;
42173
+ if (s.guard) {
42174
+ const copy = copyList(target);
42175
+ if (s.k === "add") appendTo(copy, v);
42176
+ else this.removeFrom(copy, v);
42177
+ if (isName2) this.assign(s, py2, copy, env);
42178
+ else this.store(s.target, copy, env);
42179
+ return;
42180
+ }
41020
42181
  if (s.targetKind === "list") {
41021
42182
  if (s.k === "add") {
41022
42183
  if (!Array.isArray(target)) throw attrErr(target, "append");
@@ -41046,6 +42207,7 @@ var Engine = class {
41046
42207
  }
41047
42208
  if (s.mode === "fail") {
41048
42209
  const msg = s.msg ? this.x(s.msg, env) : null;
42210
+ let outOfSteps = null;
41049
42211
  expectFailure(() => {
41050
42212
  try {
41051
42213
  this.x(s.e, env);
@@ -41053,9 +42215,11 @@ var Engine = class {
41053
42215
  if (e instanceof Return) return;
41054
42216
  if (e instanceof NeedsDeeperStack) throw e;
41055
42217
  if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
42218
+ if (e instanceof OutOfSteps) outOfSteps = e;
41056
42219
  throw e;
41057
42220
  }
41058
42221
  }, text2, msg);
42222
+ if (outOfSteps) throw outOfSteps;
41059
42223
  return;
41060
42224
  }
41061
42225
  const actual = this.x(s.e, env);
@@ -41153,6 +42317,8 @@ var Engine = class {
41153
42317
  return null;
41154
42318
  case "paren":
41155
42319
  return sub2(e.e);
42320
+ case "httpCall":
42321
+ return this.httpCall(e, env);
41156
42322
  case "today":
41157
42323
  return PyDate.today();
41158
42324
  case "date": {
@@ -41316,17 +42482,37 @@ var Engine = class {
41316
42482
  // ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
41317
42483
  runMain(mod) {
41318
42484
  const main = mod.r.program.main ?? [];
41319
- if (!main.length) return;
41320
- const frame = { file: mod.file, line: 0 };
41321
- this.withFrame(frame, () => {
41322
- const env = { mod, locals: /* @__PURE__ */ new Map(), frame };
41323
- try {
41324
- this.block(main, env);
41325
- } catch (e) {
41326
- if (e instanceof Return) return;
41327
- throw e;
41328
- }
41329
- });
42485
+ this.fillStores(mod);
42486
+ if (main.length) {
42487
+ const frame = { file: mod.file, line: 0 };
42488
+ this.withFrame(frame, () => {
42489
+ const env = { mod, locals: /* @__PURE__ */ new Map(), frame };
42490
+ try {
42491
+ this.block(main, env);
42492
+ } catch (e) {
42493
+ if (e instanceof Return) return;
42494
+ throw e;
42495
+ }
42496
+ });
42497
+ }
42498
+ this.saveStores(mod);
42499
+ }
42500
+ /** Each stored list, filled from its file (data/<name>.json); a missing file is an empty list. */
42501
+ fillStores(mod) {
42502
+ if (!this.dataFiles) return;
42503
+ for (const st of mod.stores ?? []) {
42504
+ const file = storeFile(st.s);
42505
+ const text2 = this.dataFiles.load(file);
42506
+ if (text2 == null) continue;
42507
+ const frame = { file: mod.file, line: st.s.line };
42508
+ this.withFrame(frame, () => {
42509
+ st.list.splice(0, st.list.length, ...storeFromText(text2, st.cls, file, (given) => this.newRecord(st.cls, given)));
42510
+ });
42511
+ }
42512
+ }
42513
+ saveStores(mod) {
42514
+ if (!this.dataFiles) return;
42515
+ for (const st of mod.stores ?? []) this.dataFiles.save(storeFile(st.s), storeToText(st.list, st.cls));
41330
42516
  }
41331
42517
  runTest(mod, t) {
41332
42518
  const frame = { file: mod.file, line: t.line };
@@ -41349,13 +42535,13 @@ function notCompiled(results) {
41349
42535
  Nothing was run: fix the problems first.
41350
42536
  `, notCompiled: true, steps: [] };
41351
42537
  }
41352
- function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } = {}) {
42538
+ function runInProcess({ entry: entry3, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
41353
42539
  const broken = notCompiled([entry3]);
41354
42540
  if (broken) return broken;
41355
42541
  const uses = pythonModulesUsed([entry3]);
41356
42542
  if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
41357
42543
  `, refused: uses };
41358
- const eng = new Engine({ cwd, deeper, readText });
42544
+ const eng = new Engine({ cwd, deeper, readText, store, http });
41359
42545
  let stderr = "", status = 0;
41360
42546
  try {
41361
42547
  const mod = eng.load(entry3);
@@ -41371,13 +42557,13 @@ function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } =
41371
42557
  }
41372
42558
  return { status, stdout: eng.out.join(""), stderr };
41373
42559
  }
41374
- function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
42560
+ function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
41375
42561
  const broken = notCompiled(results);
41376
42562
  if (broken) return broken;
41377
42563
  const uses = pythonModulesUsed(results);
41378
42564
  if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
41379
42565
  `, refused: uses };
41380
- const eng = new Engine({ cwd, deeper, readText });
42566
+ const eng = new Engine({ cwd, deeper, readText, http });
41381
42567
  const mods = [];
41382
42568
  const srcMods = [];
41383
42569
  for (const r of results) {
@@ -41989,7 +43175,7 @@ var FunctionPrinter = class {
41989
43175
  if (f === "sum" && one) return `the sum of ${paren(this.value(one, item3))}`;
41990
43176
  if (f === "min" && one) return `the smallest of ${paren(this.value(one, item3))}`;
41991
43177
  if (f === "max" && one) return `the largest of ${paren(this.value(one, item3))}`;
41992
- if (f === "round") nt("Python round() rounds halves to even; Thunder rounds half up");
43178
+ if (f === "round") nt("Python round() rounds halves to even; Thunder rounds halves away from zero");
41993
43179
  if (f === "sorted") return this.sorted(e, item3);
41994
43180
  if (f === "abs" && one) return `the absolute value of ${paren(this.value(one, item3))}`;
41995
43181
  if ((f === "max" || f === "min") && args.length >= 2) {
@@ -43124,22 +44310,26 @@ var end = (repo, at2, extra = {}) => ({ repo: repo.name, member: at2.member, lab
43124
44310
  var distinctive = (segs) => segs.some((s) => s !== "*");
43125
44311
  var lower2 = (segs) => segs.map((s) => s.toLowerCase());
43126
44312
  var pathMatch = (a, b) => segsMatch(lower2(a), lower2(b));
43127
- function buildTrace(repos) {
44313
+ function buildTrace(repos, { core = null } = {}) {
43128
44314
  const names = /* @__PURE__ */ new Set();
43129
44315
  const read = repos.map((r) => {
43130
44316
  if (!r.name || names.has(r.name)) throw new Error(`Each repository needs its own name; "${r.name}" is used twice.`);
43131
44317
  names.add(r.name);
43132
- const model = thunderModel(r.files, { name: r.name });
43133
- const facts = serviceFacts(model, r.files);
44318
+ const other = r.files.filter((f) => !/\.thunder$/i.test(f.path));
44319
+ const model = thunderModel(other, { name: r.name });
44320
+ const facts = serviceFacts(model, other);
44321
+ const cf = r.coreFacts ?? (core ? core(r.files) : { routes: [], requests: [], unknown: [], files: 0 });
44322
+ for (const k of ["routes", "requests", "unknown"]) facts[k] = [...facts[k], ...cf[k]];
44323
+ const coreFiles = cf.files;
43134
44324
  const real = (x) => !isTestFile(x.file);
43135
- const data = dataFacts(r.files, model);
44325
+ const data = dataFacts(other, model);
43136
44326
  const testItems = ["routes", "listeners", "requests", "publishes"].reduce((n, k) => n + facts[k].filter((x) => !real(x)).length, 0) + data.testItems;
43137
44327
  return {
43138
44328
  name: r.name,
43139
44329
  sha: r.sha ?? null,
43140
44330
  dirty: !!r.dirty,
43141
- files: model.files.length,
43142
- languages: [...new Set(model.files.map((f) => f.language))].sort(),
44331
+ files: model.files.length + coreFiles,
44332
+ languages: [.../* @__PURE__ */ new Set([...model.files.map((f) => f.language), ...coreFiles ? ["thunder"] : []])].sort(),
43143
44333
  routes: facts.routes.filter(real),
43144
44334
  listeners: facts.listeners.filter(real),
43145
44335
  requests: facts.requests.filter(real),
@@ -43405,11 +44595,107 @@ function writeRuleAcross(files, { decision, rule, when }) {
43405
44595
  return { ...result, ok: true };
43406
44596
  }
43407
44597
 
44598
+ // src/core/kind.mjs
44599
+ var MISSION_KEYWORDS = /* @__PURE__ */ new Set([
44600
+ "mission",
44601
+ "note",
44602
+ "goal",
44603
+ "why",
44604
+ "requires",
44605
+ "requires_skill",
44606
+ "demonstrates",
44607
+ "input",
44608
+ "output",
44609
+ "guarantees",
44610
+ "guarantee",
44611
+ "never",
44612
+ "constraints",
44613
+ "invariant",
44614
+ "assumptions",
44615
+ "risks",
44616
+ "target",
44617
+ "style",
44618
+ "verify",
44619
+ "errors",
44620
+ "examples",
44621
+ "service",
44622
+ "api",
44623
+ "event",
44624
+ "database",
44625
+ "architecture",
44626
+ "selection",
44627
+ "use",
44628
+ "title",
44629
+ "for",
44630
+ "persona",
44631
+ "customer",
44632
+ "problem",
44633
+ "evidence",
44634
+ "outcome",
44635
+ "metric",
44636
+ "scope",
44637
+ "non_goal",
44638
+ "owner",
44639
+ "unknown",
44640
+ "question",
44641
+ "assumption",
44642
+ "experience",
44643
+ "pattern",
44644
+ "style_intent",
44645
+ "decision",
44646
+ "property",
44647
+ "scenario",
44648
+ "evaluation",
44649
+ "capability",
44650
+ "interface",
44651
+ "component",
44652
+ "artifact",
44653
+ "outcome_contract",
44654
+ "release",
44655
+ "result",
44656
+ "learning",
44657
+ "test",
44658
+ "data",
44659
+ "waiver",
44660
+ "command",
44661
+ "on",
44662
+ "lifecycle",
44663
+ "always",
44664
+ "eventually",
44665
+ "until",
44666
+ "conflict",
44667
+ "implement",
44668
+ "requires_skills",
44669
+ "approval",
44670
+ "inferred",
44671
+ "maps_to",
44672
+ "needs_review",
44673
+ "source",
44674
+ "confidence"
44675
+ ]);
44676
+ function firstCodeLine(source) {
44677
+ for (const raw of String(source).split(/\r?\n/)) {
44678
+ const line = raw.trim();
44679
+ if (line && !line.startsWith("#")) return { text: line, indented: raw.length > 0 && /^\s/.test(raw) };
44680
+ }
44681
+ return null;
44682
+ }
44683
+ function fileKind(source) {
44684
+ const first = firstCodeLine(source);
44685
+ if (!first) return { kind: "mission", reason: "the file has no lines yet" };
44686
+ const m = /^([a-z_]+)(?:\s+([A-Za-z_][\w.-]*))?\s*$/.exec(first.text);
44687
+ if (!first.indented && m && MISSION_KEYWORDS.has(m[1])) return { kind: "mission", reason: `its first line starts with the mission keyword "${m[1]}"` };
44688
+ return { kind: "program", reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}\u2026` : first.text}") cannot start a mission` };
44689
+ }
44690
+ var isCoreProgram = (path, source) => /\.thunder$/i.test(path) && fileKind(source ?? "").kind === "program";
44691
+
43408
44692
  // src/review.mjs
43409
44693
  var REVIEW_SCHEMA = "thunder-review-v1";
43410
44694
  var SEVERITY_ORDER = ["risk", "meaning", "form"];
43411
44695
  var KIND_ORDER = [
43412
44696
  "unreadable",
44697
+ "test-fails",
44698
+ "callers",
43413
44699
  "not-read",
43414
44700
  "infrastructure",
43415
44701
  "stop-removed",
@@ -43894,7 +45180,13 @@ function compareMember(o, n, items, { extracted = false } = {}) {
43894
45180
  if (o.m.rule && n.m.rule && !o.m.rule.partial && !n.m.rule.partial) {
43895
45181
  const r = comparePlainRules(o.m.rule, n.m.rule);
43896
45182
  if (r.same) {
43897
- formOnly(`same answer on all ${r.tried} edge cases, run on both versions.`);
45183
+ items.push(item2(
45184
+ renamedOrMoved.length ? moveKind : "form",
45185
+ "form",
45186
+ subject,
45187
+ whereOf2(n),
45188
+ `${renamedOrMoved.length ? `${cap5(renamedOrMoved.join(" and "))}. ` : ""}The code changed, but the answers are the same: Tested on ${r.capped ? `the first ${r.tried} of ${r.total}` : `all ${r.tried}`} edge cases, run on both versions (not every input).`
45189
+ ));
43898
45190
  return "form";
43899
45191
  }
43900
45192
  noteMove();
@@ -44020,7 +45312,7 @@ function mostlyIn(a, b) {
44020
45312
  }
44021
45313
  return hit / want.length >= 0.75;
44022
45314
  }
44023
- function thunderReview(oldFiles, newFiles) {
45315
+ function thunderReview(oldFiles, newFiles, { core = null, context = null } = {}) {
44024
45316
  detailsCache = /* @__PURE__ */ new WeakMap();
44025
45317
  const A = side(oldFiles || []), B = side(newFiles || []);
44026
45318
  const items = [];
@@ -44099,11 +45391,14 @@ function thunderReview(oldFiles, newFiles) {
44099
45391
  { before: null, after: n.text }
44100
45392
  ));
44101
45393
  compareThings(A, B, items);
45394
+ const coreRead = core ? coreReview(core, oldFiles || [], newFiles || [], context, items) : { paths: /* @__PURE__ */ new Set(), result: null };
45395
+ const corePaths = coreRead.paths;
44102
45396
  const paths = [.../* @__PURE__ */ new Set([...A.sources.keys(), ...B.sources.keys()])];
44103
45397
  const notRead = [];
44104
45398
  for (const p of paths) {
44105
45399
  const before = A.sources.get(p), after = B.sources.get(p);
44106
45400
  if (before === after) continue;
45401
+ if (corePaths.has(p)) continue;
44107
45402
  const lang = !isInfra(p) && readableLanguage(p);
44108
45403
  if (!lang) {
44109
45404
  if (isInfra(p)) items.push(item2("infrastructure", "risk", p, { file: p, line: 1 }, `${before == null ? "New" : after == null ? "Removed" : "Changed"} infrastructure or pipeline file. Thunder does not read these in this version, so check it yourself.`, before != null && after != null ? lineChanges(before.split("\n"), after.split("\n")) : null));
@@ -44169,7 +45464,39 @@ function thunderReview(oldFiles, newFiles) {
44169
45464
  const count = (s) => items.filter((x) => x.severity === s).length;
44170
45465
  const summary = { meaning: count("meaning"), risk: count("risk"), form: count("form"), unchanged, files: paths.filter((p) => A.sources.get(p) !== B.sources.get(p)).length };
44171
45466
  const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
44172
- return { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? "Only files Thunder does not read changed." : summaryLine(summary), items, notRead };
45467
+ const out = { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? "Only files Thunder does not read changed." : summaryLine(summary), items, notRead };
45468
+ if (coreRead.result) Object.defineProperty(out, "core", { value: coreRead.result, enumerable: false });
45469
+ return out;
45470
+ }
45471
+ function coreKind(c) {
45472
+ if (c.change === "not-compiled") return "unreadable";
45473
+ if (c.kind === "test" && c.severity === "risk" && c.change !== "removed") return "test-fails";
45474
+ if (c.change === "added" || c.change === "removed" || c.change === "renamed") return c.kind === "never" && c.change === "removed" ? "stop-removed" : c.change;
45475
+ if (c.kind === "keep") return "rule-limit";
45476
+ if (c.kind === "function" && c.behaviour?.changed) return "rule-answer";
45477
+ if (c.kind === "never") return "stop-changed";
45478
+ if (c.kind === "record" || c.kind === "store") return "thing";
45479
+ if (c.kind === "main") return "outside";
45480
+ return "steps";
45481
+ }
45482
+ var CORE_SUBJECT = { keep: (c) => `${c.subject} (kept value)`, main: (c) => c.subject };
45483
+ function coreReview(coreChanges, oldFiles, newFiles, context, items) {
45484
+ const core = (fs) => fs.filter((f) => f && isCoreProgram(f.path, f.source));
45485
+ const merge = (changed, extra) => {
45486
+ const have = new Set(changed.map((f) => f.path));
45487
+ return [...changed, ...core(extra ?? []).filter((f) => !have.has(f.path))];
45488
+ };
45489
+ const oldCore = core(oldFiles), newCore = core(newFiles);
45490
+ if (!oldCore.length && !newCore.length) return { paths: /* @__PURE__ */ new Set(), result: null };
45491
+ const r = coreChanges(merge(oldCore, context?.old), merge(newCore, context?.new));
45492
+ for (const c of r.changes) {
45493
+ const look = (c.affects ?? []).slice(0, 6).map((x) => `${x.subject} (\`${x.file}:${x.line}\`${x.test ? `, ${x.test === "fails" ? "**fails now**" : "passes"}` : ""})`);
45494
+ const more = (c.affects?.length ?? 0) > 6 ? `, and ${c.affects.length - 6} more` : "";
45495
+ const says = look.length ? `${c.says} Look again at: ${look.join(", ")}${more}.` : c.says;
45496
+ const evidence = c.before || c.after ? { before: c.before, after: c.after } : null;
45497
+ items.push(item2(coreKind(c), c.severity, (CORE_SUBJECT[c.kind] ?? ((x) => x.subject))(c), { file: c.file, line: c.line }, says, evidence));
45498
+ }
45499
+ return { paths: new Set([...oldCore, ...newCore].map((f) => f.path)), result: r };
44173
45500
  }
44174
45501
  var plural3 = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
44175
45502
  function summaryLine(s) {