@skillstech/thunderlang 0.5.9 → 0.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2423,7 +2423,7 @@ function notesSummary(ast) {
2423
2423
  byLens
2424
2424
  };
2425
2425
  }
2426
- var COMPILER_VERSION = "0.5.9";
2426
+ var COMPILER_VERSION = "0.5.11";
2427
2427
  var PROOF_SCHEMA_VERSION = "0.1.0";
2428
2428
  var SOURCE_PRODUCT = "skillstech-compiler";
2429
2429
  function buildContractGraph(ast, generatedAt) {
@@ -4164,6 +4164,7 @@ function liftDiagnostics(lift, facts) {
4164
4164
  return d;
4165
4165
  }
4166
4166
  function languageForFile(file) {
4167
+ if (/\.sql$/i.test(file)) return "sql";
4167
4168
  if (/\.rs$/i.test(file)) return "rust";
4168
4169
  if (/\.(pl|pm|t)$/i.test(file)) return "perl";
4169
4170
  if (/\.pyi?$/i.test(file)) return "python";
@@ -4548,9 +4549,9 @@ function parseSelection(lines) {
4548
4549
  if (/^require\b/.test(t)) {
4549
4550
  require2.push(t.replace(/^require\s+/, ""));
4550
4551
  } else if (/^prefer\b/.test(t)) {
4551
- const words5 = t.replace(/^prefer\s+/, "").split(/\s+/);
4552
- const direction = MAX_WORDS.has(words5[0]) ? "max" : MIN_WORDS.has(words5[0]) ? "min" : "min";
4553
- prefer.push({ metric: normalizeMetric(words5.slice(1).join(" ")), direction });
4552
+ const words6 = t.replace(/^prefer\s+/, "").split(/\s+/);
4553
+ const direction = MAX_WORDS.has(words6[0]) ? "max" : MIN_WORDS.has(words6[0]) ? "min" : "min";
4554
+ prefer.push({ metric: normalizeMetric(words6.slice(1).join(" ")), direction });
4554
4555
  }
4555
4556
  }
4556
4557
  return { require: require2, prefer, requireAllChecks: require2.some((r) => /verification|all/.test(r)) };
@@ -9021,8 +9022,8 @@ function identifierWords(text) {
9021
9022
  return String(text).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
9022
9023
  }
9023
9024
  var lineHitsTerm = (text, terms) => {
9024
- const words5 = identifierWords(text);
9025
- return terms.some((term) => words5.some((w) => w === term || w.endsWith(term)));
9025
+ const words6 = identifierWords(text);
9026
+ return terms.some((term) => words6.some((w) => w === term || w.endsWith(term)));
9026
9027
  };
9027
9028
  function addedLines(before, after) {
9028
9029
  const afterLines = String(after ?? "").split(/\r?\n/);
@@ -9126,9 +9127,9 @@ var SECRET_TYPES2 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jw
9126
9127
  var SECRET_NAME = /pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card/i;
9127
9128
  var isSecretField = (f) => f && (SECRET_TYPES2.has(String(f.type || "").toLowerCase()) || SECRET_NAME.test(f.name || ""));
9128
9129
  function pascalish(text) {
9129
- const words5 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
9130
- if (words5.length === 1) return words5[0].charAt(0).toUpperCase() + words5[0].slice(1);
9131
- return words5.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
9130
+ const words6 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
9131
+ if (words6.length === 1) return words6[0].charAt(0).toUpperCase() + words6[0].slice(1);
9132
+ return words6.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
9132
9133
  }
9133
9134
  var normRules = (list) => (Array.isArray(list) ? list : []).map((r) => typeof r === "string" ? { statement: r } : { ...r }).filter((r) => r.statement);
9134
9135
  function draftIntent(brief = {}) {
@@ -9208,9 +9209,426 @@ function draftIntent(brief = {}) {
9208
9209
  return { schema: DRAFT_SCHEMA, source, review, diagnostics };
9209
9210
  }
9210
9211
 
9212
+ // src/sql.mjs
9213
+ var words2 = (s) => String(s).replace(/^["`[]|["`\]]$/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
9214
+ var unquote = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/, "$1");
9215
+ var bare = (name) => unquote(String(name).split(".").pop());
9216
+ var singular = (w) => w.replace(/ies$/, "y").replace(/(ss|sh|ch|x)es$/, "$1").replace(/([^s])s$/, "$1");
9217
+ var article = (w) => /^[aeiou]/i.test(w) ? `an ${w}` : `a ${w}`;
9218
+ function lineFinder(src) {
9219
+ const starts = [0];
9220
+ for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
9221
+ return (idx) => {
9222
+ let lo = 0, hi = starts.length - 1;
9223
+ while (lo < hi) {
9224
+ const mid = lo + hi + 1 >> 1;
9225
+ if (starts[mid] <= idx) lo = mid;
9226
+ else hi = mid - 1;
9227
+ }
9228
+ return lo + 1;
9229
+ };
9230
+ }
9231
+ function mask(src) {
9232
+ let out = "";
9233
+ for (let i = 0; i < src.length; i++) {
9234
+ const c = src[i];
9235
+ if (c === "-" && src[i + 1] === "-") {
9236
+ const n = src.indexOf("\n", i);
9237
+ const end = n < 0 ? src.length : n;
9238
+ out += " ".repeat(end - i);
9239
+ i = end - 1;
9240
+ continue;
9241
+ }
9242
+ if (c === "/" && src[i + 1] === "*") {
9243
+ const n = src.indexOf("*/", i + 2);
9244
+ const end = n < 0 ? src.length : n + 2;
9245
+ out += src.slice(i, end).replace(/[^\n]/g, " ");
9246
+ i = end - 1;
9247
+ continue;
9248
+ }
9249
+ if (c === "'") {
9250
+ let j = i + 1;
9251
+ for (; j < src.length; j++) {
9252
+ if (src[j] === "'" && src[j + 1] === "'") {
9253
+ j++;
9254
+ continue;
9255
+ }
9256
+ if (src[j] === "'") break;
9257
+ }
9258
+ out += "'" + src.slice(i + 1, j).replace(/[^\n]/g, "x") + (j < src.length ? "'" : "");
9259
+ i = j;
9260
+ continue;
9261
+ }
9262
+ out += c;
9263
+ }
9264
+ return out;
9265
+ }
9266
+ function parenEnd(m, open) {
9267
+ for (let i = open, d = 0; i < m.length; i++) {
9268
+ if (m[i] === "(") d++;
9269
+ else if (m[i] === ")" && --d === 0) return i;
9270
+ }
9271
+ return -1;
9272
+ }
9273
+ function splitTop(text, masked = mask(text)) {
9274
+ const out = [];
9275
+ let d = 0, start = 0;
9276
+ for (let i = 0; i < masked.length; i++) {
9277
+ if (masked[i] === "(") d++;
9278
+ else if (masked[i] === ")") d--;
9279
+ else if (masked[i] === "," && d === 0) {
9280
+ out.push({ text: text.slice(start, i), at: start });
9281
+ start = i + 1;
9282
+ }
9283
+ }
9284
+ out.push({ text: text.slice(start), at: start });
9285
+ return out.filter((p) => p.text.trim());
9286
+ }
9287
+ function docAbove(src, idx) {
9288
+ const lines = src.slice(0, idx).split("\n");
9289
+ lines.pop();
9290
+ const run = [];
9291
+ for (let k = lines.length - 1; k >= 0 && /^\s*--/.test(lines[k]); k--) run.unshift(lines[k].replace(/^\s*--+\s?/, "").trim());
9292
+ const text = run.filter(Boolean).join(" ");
9293
+ return text || null;
9294
+ }
9295
+ var TYPE_WORDS = [
9296
+ [/^(small|big)?serial\b|^serial\d/i, "a number, given automatically"],
9297
+ [/^(int|integer|smallint|bigint|tinyint|mediumint|numeric|decimal|real|float|double|money|number)\b|^int\d/i, "a number"],
9298
+ [/^(text|varchar|char|character|nvarchar|nchar|citext|string|clob)\b/i, "words"],
9299
+ [/^(bool|boolean|bit)\b/i, "yes or no"],
9300
+ [/^(date|time|timestamp|timestamptz|datetime|datetime2|interval)\b/i, "a date"],
9301
+ [/^uuid\b|^uniqueidentifier\b/i, "an id"],
9302
+ [/^jsonb?\b/i, "structured data"],
9303
+ [/^(bytea|blob|binary|varbinary)\b/i, "a file or bytes"]
9304
+ ];
9305
+ var typeWords = (t) => {
9306
+ for (const [re, w] of TYPE_WORDS) if (re.test(String(t).trim())) return w;
9307
+ return /\[\]$/.test(String(t).trim()) ? "a list" : null;
9308
+ };
9309
+ function sqlCondition(cond, { aliases = {}, vars = false } = {}) {
9310
+ let c = String(cond).trim().replace(/\s+/g, " ");
9311
+ while (/^\(.*\)$/.test(c) && parenEnd(mask(c), 0) === c.length - 1) c = c.slice(1, -1).trim();
9312
+ c = c.replace(/'((?:[^']|'')*)'/g, (m, v) => `"${v.replace(/''/g, "'")}"`);
9313
+ const plain = (x) => words2(vars ? String(x).replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, "") : x);
9314
+ const name = (x) => {
9315
+ const p = String(x).split(".");
9316
+ if (p.length < 2) return plain(x);
9317
+ const table = aliases[p[0].toLowerCase()] ?? p[0];
9318
+ return `the ${singular(words2(table))}'s ${words2(p[1])}`;
9319
+ };
9320
+ return c.replace(/\b(NEW|OLD)\.(\w+)/g, (m, which, col) => `the ${which === "NEW" ? "new" : "old"} ${words2(col)}`).replace(/([\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is not one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => /^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`).replace(/([\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is empty`).replace(/([\w.]+)\s+NOT\s+LIKE\s+"([^"]*)"/gi, (m, a, p) => `${name(a)} does not match "${p.replace(/%/g, "\u2026")}"`).replace(/([\w.]+)\s+I?LIKE\s+"([^"]*)"/gi, (m, a, p) => /^[^%]+%$/.test(p) ? `${name(a)} starts with "${p.slice(0, -1)}"` : /^%[^%]+%$/.test(p) ? `${name(a)} contains "${p.slice(1, -1)}"` : `${name(a)} matches "${p.replace(/%/g, "\u2026")}"`).replace(/([\w."]+)\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)/gi, (m, a, lo, hi) => `${name(a)} is from ${lo} to ${hi}`).replace(/\s*(<>|!=)\s*/g, " is not ").replace(/\s*>=\s*/g, " is at least ").replace(/\s*<=\s*/g, " is at most ").replace(/\s*>\s*/g, " is more than ").replace(/\s*<\s*/g, " is less than ").replace(/\s*=\s*/g, " is ").replace(/\bAND\b/gi, "and").replace(/\bOR\b/gi, "or").replace(/\bNOT\s+/gi, "not ").replace(/\b(?:length|char_length)\s*\(\s*([\w."]+)\s*\)/gi, (m, a) => `the length of ${name(a)}`).replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b)([a-z_][\w]*\.)?([a-z_][\w]*)\b(?![^"]*"(?:[^"]*"[^"]*")*[^"]*$)/gi, (m, t, col) => t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)).replace(/\s+/g, " ").trim();
9321
+ }
9322
+ function readSchema(src) {
9323
+ const m = mask(src);
9324
+ const lineAt2 = lineFinder(src);
9325
+ const tables = [], choices = [], rules = [];
9326
+ const docs = /* @__PURE__ */ new Map();
9327
+ for (const c of src.matchAll(/COMMENT\s+ON\s+TABLE\s+([\w."]+)\s+IS\s+'((?:[^']|'')*)'/gi)) docs.set(bare(c[1]).toLowerCase(), c[2].replace(/''/g, "'"));
9328
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."[\]`]+)\s*\(/gi)) {
9329
+ const open = t.index + t[0].length - 1;
9330
+ const close = parenEnd(m, open);
9331
+ if (close < 0) continue;
9332
+ const name = bare(src.slice(t.index, open).match(/([\w."[\]`]+)\s*$/)[1]);
9333
+ const table = { name, lines: [lineAt2(t.index), lineAt2(close)], doc: docs.get(name.toLowerCase()) ?? docAbove(src, t.index), columns: [], checks: [], uniques: [], refs: [] };
9334
+ for (const part of splitTop(src.slice(open + 1, close), m.slice(open + 1, close))) {
9335
+ const text = part.text.trim().replace(/\s+/g, " ");
9336
+ const line = lineAt2(open + 1 + part.at + (part.text.length - part.text.trimStart().length));
9337
+ let x;
9338
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"]+)\s+)?CHECK\s*\((.*)\)$/i)) {
9339
+ table.checks.push({ name: x[1] && unquote(x[1]), cond: x[2], line });
9340
+ continue;
9341
+ }
9342
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"`]+)\s+)?UNIQUE(?:\s+(?:KEY|INDEX))?(?:\s+([\w"`]+))?\s*\(([^)]*)\)/i)) {
9343
+ table.uniques.push({ name: (x[1] || x[2]) && unquote(x[1] || x[2]), cols: x[3].split(",").map((c) => unquote(c.trim())), line });
9344
+ continue;
9345
+ }
9346
+ if (x = text.match(/^(?:CONSTRAINT\s+[\w"]+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s+REFERENCES\s+([\w."]+)/i)) {
9347
+ for (const c of x[1].split(",")) table.refs.push({ col: unquote(c.trim()), to: bare(x[2]) });
9348
+ continue;
9349
+ }
9350
+ if (/^(?:CONSTRAINT\s+[\w"]+\s+)?(PRIMARY\s+KEY|INDEX|KEY|EXCLUDE)\b/i.test(text)) continue;
9351
+ const col = text.match(/^([\w"`[\]]+)\s+([\w]+(?:\s*\([^)]*\))?(?:\s+(?:varying|precision|with(?:out)?\s+time\s+zone))*(?:\[\])?)(.*)$/i);
9352
+ if (!col || /^(LIKE|PERIOD)$/i.test(col[1])) continue;
9353
+ const rest2 = col[3] || "";
9354
+ const ref = rest2.match(/\bREFERENCES\s+([\w."]+)/i);
9355
+ const def = rest2.match(/\bDEFAULT\s+('(?:[^']|'')*'|\([^)]*\)|[\w.:]+(?:\(\))?)/i);
9356
+ const column = { name: unquote(col[1]), type: col[2], line, primary: /\bPRIMARY\s+KEY\b/i.test(rest2), notNull: /\bNOT\s+NULL\b/i.test(rest2), ...def ? { default: def[1] } : {}, ...ref ? { ref: bare(ref[1]) } : {} };
9357
+ table.columns.push(column);
9358
+ const check = rest2.match(/\bCHECK\s*\((.*)\)/i);
9359
+ if (check) table.checks.push({ cond: check[1], line });
9360
+ if (/\bUNIQUE\b/i.test(rest2)) table.uniques.push({ cols: [column.name], line });
9361
+ }
9362
+ tables.push(table);
9363
+ }
9364
+ for (const e of m.matchAll(/\bCREATE\s+TYPE\s+([\w."]+)\s+AS\s+ENUM\s*\(/gi)) {
9365
+ const open = e.index + e[0].length - 1;
9366
+ const close = parenEnd(m, open);
9367
+ if (close < 0) continue;
9368
+ const values = [...src.slice(open + 1, close).matchAll(/'((?:[^']|'')*)'/g)].map((v) => v[1].replace(/''/g, "'").replace(/_/g, " "));
9369
+ choices.push({ name: bare(e[1]), lines: [lineAt2(e.index), lineAt2(close)], doc: docAbove(src, e.index), values });
9370
+ }
9371
+ for (const t of tables) {
9372
+ for (const c of t.checks) rules.push({ table: t.name, kind: "check", ...c });
9373
+ for (const u of t.uniques) rules.push({ table: t.name, kind: "unique", ...u });
9374
+ }
9375
+ return { tables, choices, rules };
9376
+ }
9377
+ var colWords = (expr) => {
9378
+ const e = expr.trim();
9379
+ const as = e.match(/\s+(?:AS\s+)?([\w"]+)$/i);
9380
+ if (as && !/^(DESC|ASC|END)$/i.test(as[1]) && /[\s)]/.test(e.slice(0, as.index + 1))) return words2(unquote(as[1]));
9381
+ const agg = e.match(/^(count|sum|avg|min|max)\s*\(\s*(distinct\s+)?([^)]*)\)$/i);
9382
+ if (agg) {
9383
+ const what = agg[3].trim() === "*" ? "rows" : words2(bare(agg[3]));
9384
+ return { count: `how many ${what === "rows" ? "rows" : what}`, sum: `the total of ${what}`, avg: `the average ${what}`, min: `the lowest ${what}`, max: `the highest ${what}` }[agg[1].toLowerCase()];
9385
+ }
9386
+ if (e === "*") return "every column";
9387
+ if (/^\w+\.\*$/.test(e)) return `every column of ${words2(e.split(".")[0])}`;
9388
+ return /^[\w."]+$/.test(e) ? words2(bare(e)) : "a worked-out value";
9389
+ };
9390
+ var listWords = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
9391
+ function selectSteps(sql, line, { give = true, vars = false } = {}) {
9392
+ const s = sql.replace(/\s+/g, " ").trim().replace(/;$/, "");
9393
+ const m = mask(s);
9394
+ const at = (kw) => {
9395
+ const r = new RegExp(`\\b${kw}\\b`, "i").exec(m);
9396
+ return r ? r.index : -1;
9397
+ };
9398
+ const clauses = ["SELECT", "FROM", "WHERE", "GROUP BY", "HAVING", "ORDER BY", "LIMIT", "OFFSET", "INTO"].map((k) => [k, at(k)]).filter(([, i]) => i >= 0).sort((a, b) => a[1] - b[1]);
9399
+ const part = (k) => {
9400
+ const i = clauses.findIndex(([n]) => n === k);
9401
+ if (i < 0) return null;
9402
+ const start = clauses[i][1] + k.length;
9403
+ const end = clauses[i + 1]?.[1] ?? s.length;
9404
+ return s.slice(start, end).trim();
9405
+ };
9406
+ const steps = [];
9407
+ const code = s;
9408
+ const from = part("FROM");
9409
+ const aliases = {};
9410
+ for (const a of (from || "").matchAll(/([\w."]+)\s+(?:AS\s+)?([a-z_]\w*)\b(?=\s*(?:,|$|\bON\b|\bJOIN\b|\bLEFT\b|\bRIGHT\b|\bINNER\b|\bFULL\b|\bCROSS\b|\bWHERE\b))/gi)) {
9411
+ if (!/^(ON|JOIN|LEFT|RIGHT|INNER|FULL|CROSS|OUTER|WHERE|AS)$/i.test(a[2])) aliases[a[2].toLowerCase()] = bare(a[1]);
9412
+ }
9413
+ const cond = (text) => sqlCondition(text, { aliases, vars });
9414
+ if (from) {
9415
+ const [first, ...joins] = from.split(/\b(?:(?:LEFT|RIGHT|INNER|FULL|CROSS)\s+(?:OUTER\s+)?)?JOIN\b/i);
9416
+ const base = bare(first.trim().split(/\s+/)[0]);
9417
+ steps.push({ kind: "call", callee: "find", says: `Finds the ${words2(base)}`, code, line });
9418
+ for (const j of joins) {
9419
+ const jt = bare(j.trim().split(/\s+/)[0]);
9420
+ const left = /\bLEFT\b/i.test(from.slice(0, from.indexOf(j)).slice(-20));
9421
+ steps.push({ kind: "call", callee: "find", says: `${left ? "Adds, when there is one," : "Adds"} the matching ${words2(singular(jt))} to each`, code, line });
9422
+ }
9423
+ }
9424
+ const where = part("WHERE");
9425
+ if (where) steps.push({ kind: "call", callee: "filter", says: `Keeps only those where ${cond(where)}`, code, line });
9426
+ const group = part("GROUP BY");
9427
+ if (group) steps.push({ kind: "set", says: `Groups them by ${listWords(splitTop(group).map((p) => words2(bare(p.text.trim()))))}`, code, line });
9428
+ const having = part("HAVING");
9429
+ if (having) steps.push({ kind: "call", callee: "filter", says: `Keeps only groups where ${cond(having.replace(/\b(count|sum|avg|min|max)\s*\(([^)]*)\)/gi, (x) => colWords(x).replace(/ /g, "_")))}`.replace(/_/g, " "), code, line });
9430
+ const order = part("ORDER BY");
9431
+ if (order) steps.push({ kind: "set", says: `Sorts them by ${listWords(splitTop(order).map((p) => {
9432
+ const t = p.text.trim();
9433
+ return `${colWords(t.replace(/\s+(ASC|DESC)(\s+NULLS\s+(FIRST|LAST))?$/i, ""))}${/\bDESC\b/i.test(t) ? ", highest first" : ""}`;
9434
+ }))}`, code, line });
9435
+ const limit = part("LIMIT");
9436
+ if (limit && /^\d+/.test(limit)) steps.push({ kind: "set", says: `Takes the first ${limit.match(/^\d+/)[0]}`, code, line });
9437
+ const cols = part("SELECT");
9438
+ if (give && cols) {
9439
+ const names = splitTop(cols.replace(/^DISTINCT\s+/i, "")).map((p) => colWords(p.text));
9440
+ steps.push({ kind: "return", says: `Returns ${listWords(names.length > 8 ? [...names.slice(0, 7), "more"] : names)}`, code, line });
9441
+ }
9442
+ return steps;
9443
+ }
9444
+ function bodyStatement(text, line) {
9445
+ const cnd = (x2) => sqlCondition(x2, { vars: true });
9446
+ const v = (x2) => words2(String(x2).replace(/^(?:p|v|l|var)_(?=\w)/i, ""));
9447
+ const t = text.replace(/\s+/g, " ").trim().replace(/;$/, "");
9448
+ const code = t;
9449
+ let x;
9450
+ if (x = t.match(/^RAISE\s+(?:EXCEPTION|ERROR)\s+'((?:[^']|'')*)'/i)) {
9451
+ const msg = x[1].replace(/''/g, "'").replace(/%/g, "\u2026");
9452
+ return { kind: "fail", says: `Fails with an error: "${msg}"`, error: "an error", message: msg, code, line };
9453
+ }
9454
+ if ((x = t.match(/^(?:RAISERROR|THROW)\s*\(?\s*(?:\d+\s*,\s*)?N?'((?:[^']|'')*)'/i)) || (x = t.match(/^SIGNAL\s+SQLSTATE\s+'\w+'\s+SET\s+MESSAGE_TEXT\s*=\s*'((?:[^']|'')*)'/i))) return { kind: "fail", says: `Fails with an error: "${x[1].replace(/''/g, "'")}"`, error: "an error", message: x[1].replace(/''/g, "'"), code, line };
9455
+ if (x = t.match(/^RETURN\s+QUERY\s+(SELECT\b.*)$/i)) return { kind: "return", says: selectSteps(x[1], line).at(-1)?.says ?? "Returns the rows a query finds", code, line, query: selectSteps(x[1], line, { give: false }) };
9456
+ if (x = t.match(/^RETURN\s+(NEW|OLD)$/i)) return { kind: "return", says: x[1].toUpperCase() === "NEW" ? "Lets the change go ahead" : "Keeps the old row", code, line };
9457
+ if (x = t.match(/^RETURN\s*(.*)$/i)) return { kind: "return", says: x[1] ? /^'(.*)'$/.test(x[1]) ? `Returns "${x[1].slice(1, -1)}"` : /^(true|false)$/i.test(x[1]) ? `Returns ${x[1].toLowerCase() === "true" ? "yes" : "no"}` : `Returns ${cnd(x[1])}` : "Stops here", code, line };
9458
+ if (x = t.match(/^INSERT\s+INTO\s+([\w."]+)(?:\s*\(([^)]*)\))?/i)) return { kind: "call", says: `Records a new ${singular(words2(bare(x[1])))}${x[2] ? ` with ${listWords(x[2].split(",").map((c) => words2(c.trim())))}` : ""}`, code, line };
9459
+ if (x = t.match(/^UPDATE\s+([\w."]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/i)) {
9460
+ const sets = splitTop(x[2]).map((p) => {
9461
+ const kv = p.text.match(/^\s*([\w."]+)\s*=\s*(.*)$/s);
9462
+ return kv ? `${words2(bare(kv[1]))} to ${/^'.*'$/.test(kv[2].trim()) ? `"${kv[2].trim().slice(1, -1)}"` : cnd(kv[2])}` : null;
9463
+ }).filter(Boolean);
9464
+ return { kind: "call", says: `Records the change in ${words2(bare(x[1]))}: sets ${listWords(sets)}${x[3] ? ` where ${cnd(x[3])}` : ""}`, code, line };
9465
+ }
9466
+ if (x = t.match(/^DELETE\s+FROM\s+([\w."]+)(?:\s+WHERE\s+(.*))?$/i)) return { kind: "call", says: `Removes ${words2(bare(x[1]))}${x[2] ? ` where ${cnd(x[2])}` : ""}`, code, line };
9467
+ if (x = t.match(/^SELECT\s+(.*?)\s+INTO\s+(?:STRICT\s+)?([\w,\s]+?)\s+FROM\s+(.*)$/i)) {
9468
+ const from = x[3].match(/^([\w."]+)(?:\s+(?:AS\s+)?\w+)?(?:\s+WHERE\s+(.*))?$/i);
9469
+ const what = listWords(x[2].split(",").map((n) => v(n.trim())));
9470
+ if (from) return { kind: "call", callee: "find", says: `Finds ${what} in the ${words2(bare(from[1]))}${from[2] ? ` where ${cnd(from[2])}` : ""}`, code, line };
9471
+ const found = selectSteps(`SELECT ${x[1]} FROM ${x[3]}`, line, { give: false, vars: true });
9472
+ return { kind: "call", callee: "find", says: `Finds ${what}: ${found.map((f) => f.says.charAt(0).toLowerCase() + f.says.slice(1)).join(", ")}`, code, line };
9473
+ }
9474
+ if (x = t.match(/^(?:PERFORM|CALL|EXEC(?:UTE)?)\s+([\w.]+)\s*\(/i)) return { kind: "call", says: `Runs ${words2(bare(x[1]))}`, code, line };
9475
+ if (x = t.match(/^(?:SET\s+)?@?([\w.]+)\s*:?=\s*(.+)$/i)) return { kind: "set", says: `Sets ${v(bare(x[1]))} to ${/^'.*'$/.test(x[2].trim()) ? `"${x[2].trim().slice(1, -1)}"` : cnd(x[2])}`, code, line };
9476
+ return { kind: "other", says: code, code, line, restates: code };
9477
+ }
9478
+ function procSteps(body, firstLine) {
9479
+ const m = mask(body);
9480
+ const stmts = [];
9481
+ let start = 0;
9482
+ const re = /;|\bTHEN\b|\bELSE\b(?!\s*IF)|\bELSIF\b|\bELSEIF\b|\bEND\s+IF\b|\bBEGIN\b|\bEND\b(?!\s+IF)/gi;
9483
+ const lineAt2 = lineFinder(body);
9484
+ let r;
9485
+ while (r = re.exec(m)) {
9486
+ const kw = r[0].toUpperCase().replace(/\s+/g, " ");
9487
+ if (kw === ";") {
9488
+ const text = body.slice(start, r.index).trim();
9489
+ if (text) stmts.push({ text, line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1 });
9490
+ start = r.index + 1;
9491
+ continue;
9492
+ }
9493
+ if (kw === "THEN") {
9494
+ stmts.push({ text: body.slice(start, r.index).trim(), line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1, then: true });
9495
+ start = r.index + r[0].length;
9496
+ continue;
9497
+ }
9498
+ const before = body.slice(start, r.index).trim();
9499
+ if (before) stmts.push({ text: before, line: firstLine + lineAt2(start) - 1 });
9500
+ stmts.push({ keyword: kw === "ELSEIF" ? "ELSIF" : kw });
9501
+ start = r.index + r[0].length;
9502
+ }
9503
+ const tail = body.slice(start).trim();
9504
+ if (tail) stmts.push({ text: tail, line: firstLine + lineAt2(start) - 1 });
9505
+ let i = 0;
9506
+ const block = (stop) => {
9507
+ const out = [];
9508
+ while (i < stmts.length) {
9509
+ const s = stmts[i];
9510
+ if (s.keyword && stop.includes(s.keyword)) return out;
9511
+ i++;
9512
+ if (s.keyword === "BEGIN" || s.keyword === "END") continue;
9513
+ if (s.then && /^(IF|ELSIF)\b/i.test(s.text)) {
9514
+ const cond = s.text.replace(/^(IF|ELSIF)\s+/i, "");
9515
+ const step = { kind: "branch", says: `If ${sqlCondition(cond, { vars: true })}`, code: s.text, line: s.line, children: block(["ELSIF", "ELSE", "END IF"]) };
9516
+ let tail2 = step;
9517
+ while (stmts[i]?.keyword === "ELSIF") {
9518
+ i++;
9519
+ const h = stmts[i++];
9520
+ const next = { kind: "branch", says: `If ${sqlCondition(h.text.replace(/^ELSIF\s+/i, ""), { vars: true })}`, code: h.text, line: h.line, children: block(["ELSIF", "ELSE", "END IF"]) };
9521
+ tail2.otherwise = [next];
9522
+ tail2 = next;
9523
+ }
9524
+ if (stmts[i]?.keyword === "ELSE") {
9525
+ i++;
9526
+ tail2.otherwise = block(["END IF"]);
9527
+ }
9528
+ if (stmts[i]?.keyword === "END IF") i++;
9529
+ out.push(step);
9530
+ continue;
9531
+ }
9532
+ if (s.text && !/^(DECLARE|LANGUAGE|AS)\b/i.test(s.text) && !/^\w+\s+[\w(),]+(\s*:=.*)?$/.test(s.text) || /:=/.test(s.text ?? "")) {
9533
+ if (s.text && !/^DECLARE\b/i.test(s.text)) out.push(bodyStatement(s.text.replace(/^DECLARE\s+/i, ""), s.line));
9534
+ }
9535
+ }
9536
+ return out;
9537
+ };
9538
+ return block([]);
9539
+ }
9540
+ function sqlItems(src) {
9541
+ const m = mask(src);
9542
+ const lineAt2 = lineFinder(src);
9543
+ const items = [];
9544
+ const push = (name, line, steps, extra = {}) => {
9545
+ const code = steps.filter((s) => s.kind === "other").length;
9546
+ items.push({
9547
+ id: `${name}:${line}`,
9548
+ name,
9549
+ label: words2(name).charAt(0).toUpperCase() + words2(name).slice(1),
9550
+ line,
9551
+ inputs: extra.inputs ?? [],
9552
+ returns: extra.returns ?? null,
9553
+ ...extra.doc ? { doc: extra.doc } : {},
9554
+ provenance: "inferred-from-code",
9555
+ kind: "function",
9556
+ status: "signature-only",
9557
+ steps,
9558
+ stepsMore: 0,
9559
+ stepsReadable: steps.length ? Math.round((steps.length - code) / steps.length * 100) / 100 : 0,
9560
+ says: extra.says ?? `${words2(name)} has ${steps.length} step${steps.length === 1 ? "" : "s"}.`,
9561
+ headline: extra.headline ?? `${words2(name)}.`,
9562
+ guards: [],
9563
+ unread: []
9564
+ });
9565
+ };
9566
+ for (const v of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)(?:\s*\([^)]*\))?\s+AS\s+/gi)) {
9567
+ const end = m.indexOf(";", v.index);
9568
+ const query = src.slice(v.index + v[0].length, end < 0 ? src.length : end);
9569
+ const name = bare(v[1]);
9570
+ push(name, lineAt2(v.index), selectSteps(query, lineAt2(v.index + v[0].length)), { doc: docAbove(src, v.index), says: `${words2(name)} is a saved query.`, headline: `${words2(name)}: a saved query.` });
9571
+ }
9572
+ for (const f of m.matchAll(/\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:DEFINER\s*=\s*\S+\s+)?(FUNCTION|PROCEDURE|PROC)\s+([\w."[\]]+)\s*\(/gi)) {
9573
+ const open = f.index + f[0].length - 1;
9574
+ const close = parenEnd(m, open);
9575
+ if (close < 0) continue;
9576
+ const name = bare(f[2]);
9577
+ const inputs = splitTop(src.slice(open + 1, close)).map((p) => {
9578
+ const pm = p.text.trim().match(/^(?:IN\s+|OUT\s+|INOUT\s+)?@?([\w"]+)\s+(.+?)(?:\s+(?:DEFAULT|=)\s+.+)?$/i);
9579
+ return pm ? { name: unquote(pm[1]).replace(/^p_|^_/, ""), type: pm[2].trim() } : null;
9580
+ }).filter(Boolean);
9581
+ const after = src.slice(close + 1);
9582
+ const ret = after.match(/^\s*RETURNS\s+(TABLE\s*\([^)]*\)|SETOF\s+[\w.]+|[\w.]+(?:\[\])?)/i);
9583
+ const dollar = after.match(/\$(\w*)\$([\s\S]*?)\$\1\$/);
9584
+ const beginAt = mask(after).search(/\bBEGIN\b/i);
9585
+ const bodyText = dollar ? dollar[2] : beginAt >= 0 ? after.slice(beginAt) : "";
9586
+ const bodyStart = close + 1 + (dollar ? dollar.index + dollar[0].indexOf(dollar[2]) : Math.max(beginAt, 0));
9587
+ const isTrigger = ret && /^trigger$/i.test(ret[1]);
9588
+ const steps = procSteps(bodyText, lineAt2(bodyStart));
9589
+ const returns = ret && !isTrigger ? typeWords(ret[1]) ?? (/^(SETOF|TABLE)\b/i.test(ret[1]) ? "rows" : words2(ret[1])) : null;
9590
+ push(name, lineAt2(f.index), steps, {
9591
+ inputs,
9592
+ returns,
9593
+ doc: docAbove(src, f.index),
9594
+ says: `${words2(name)} takes ${inputs.length ? inputs.map((p) => words2(p.name)).join(", ") : "no inputs"}${returns ? ` and returns ${returns}` : ""}.`,
9595
+ headline: `${words2(name)} takes ${inputs.length ? inputs.map((p) => words2(p.name)).join(", ") : "no inputs"}.`
9596
+ });
9597
+ }
9598
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+([\w."]+)\s+(BEFORE|AFTER|INSTEAD\s+OF)\s+([\w\s,]+?)\s+ON\s+([\w."]+)[\s\S]*?EXECUTE\s+(?:FUNCTION|PROCEDURE)\s+([\w.]+)/gi)) {
9599
+ const events = t[3].split(/\s+OR\s+/i).map((e) => ({ INSERT: "added", UPDATE: "changed", DELETE: "removed", TRUNCATE: "emptied" })[e.trim().split(/\s+/)[0].toUpperCase()] || words2(e)).filter(Boolean);
9600
+ const what = article(singular(words2(bare(t[4]))));
9601
+ const when = `${t[2].toUpperCase() === "BEFORE" ? "Before" : t[2].toUpperCase() === "AFTER" ? "After" : "Instead of when"} ${what} is ${events.join(" or ")}`;
9602
+ push(bare(t[1]), lineAt2(t.index), [{ kind: "call", says: `${when}, runs ${words2(bare(t[5]))}`, code: t[0].replace(/\s+/g, " "), line: lineAt2(t.index) }], { says: `${when}, the database runs ${words2(bare(t[5]))}.`, headline: `${when}.`, doc: docAbove(src, t.index) });
9603
+ }
9604
+ for (const r of readSchema(src).rules) {
9605
+ const table = words2(r.table);
9606
+ if (r.kind === "check") {
9607
+ const cond = sqlCondition(r.cond);
9608
+ const name = r.name || `${(r.cond.match(/[a-z_]\w*/i) || ["value"])[0]}_check`;
9609
+ push(
9610
+ name,
9611
+ r.line,
9612
+ [{ kind: "branch", says: `If not: ${cond}`, code: `CHECK (${r.cond})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "The ${singular(table)} needs ${cond.replace(/"/g, "'")}"`, error: "Refused by the database", message: `The ${singular(table)} needs ${cond.replace(/"/g, "'")}`, code: `CHECK (${r.cond})`, line: r.line }] }],
9613
+ { says: `Every ${singular(table)} must have ${cond}.`, headline: `Every ${singular(table)} must have ${cond}.` }
9614
+ );
9615
+ } else {
9616
+ const cols = listWords(r.cols.map(words2));
9617
+ push(
9618
+ r.name || `unique_${r.cols.join("_and_")}`,
9619
+ r.line,
9620
+ [{ kind: "branch", says: `If not: no other ${singular(table)} has the same ${cols}`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "Each ${cols} can be used only once"`, error: "Refused by the database", message: `Each ${cols} can be used only once`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line }] }],
9621
+ { says: `Each ${cols} can be used by only one ${singular(table)}.`, headline: `Each ${cols} can be used by only one ${singular(table)}.` }
9622
+ );
9623
+ }
9624
+ }
9625
+ items.sort((a, b) => a.line - b.line);
9626
+ return items;
9627
+ }
9628
+
9211
9629
  // src/steps.mjs
9212
9630
  var MAX_STEPS = 14;
9213
- var words2 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
9631
+ var words3 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
9214
9632
  var clip = (s, n = 70) => {
9215
9633
  const t = String(s).replace(/\s+/g, " ").trim();
9216
9634
  return t.length > n ? `${t.slice(0, n - 1)}\u2026` : t;
@@ -9226,24 +9644,24 @@ var KNOWN_CALLS = [
9226
9644
  ];
9227
9645
  var possessiveWords = (path) => {
9228
9646
  const parts = String(path).replace(/^\$/, "").replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, ".$1").split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x));
9229
- return parts.length > 1 ? `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}` : words2(parts[0] || path);
9647
+ return parts.length > 1 ? `the ${words3(parts[parts.length - 2])}'s ${words3(parts[parts.length - 1])}` : words3(parts[0] || path);
9230
9648
  };
9231
- var plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => v.length > 1 && v === v.toUpperCase() ? words2(v) : m);
9649
+ var plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => v.length > 1 && v === v.toUpperCase() ? words3(v) : m);
9232
9650
  function sayCodeCondition(cond) {
9233
9651
  let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, "").trim();
9234
9652
  while (c.startsWith("(") && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
9235
9653
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
9236
9654
  const plural2 = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
9237
- if (prop && plural2(words2(prop[3]), !!prop[4])) return `${words2(prop[2])} ${prop[1] ? "has no" : "has"} ${words2(prop[3])}`;
9655
+ if (prop && plural2(words3(prop[3]), !!prop[4])) return `${words3(prop[2])} ${prop[1] ? "has no" : "has"} ${words3(prop[3])}`;
9238
9656
  const yesNo = (w, call2) => /^(is|has|can|should|was) /.test(w) || !call2 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
9239
- if (prop && yesNo(words2(prop[3]), !!prop[4])) {
9657
+ if (prop && yesNo(words3(prop[3]), !!prop[4])) {
9240
9658
  const neg = !!prop[1];
9241
- const w = words2(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
9659
+ const w = words3(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
9242
9660
  const verb = /^(is|was) /.test(w) ? w.replace(/^(is|was) /, neg ? "$1 not " : "$1 ") : /^(has|can|should) /.test(w) ? (neg ? `does not ${w.replace(/^has /, "have ")}` : w).replace(/^does not can /, "cannot ").replace(/^does not should /, "should not ") : `is ${neg ? "not " : ""}${w}`;
9243
- return `${words2(prop[2])} ${verb}`;
9661
+ return `${words3(prop[2])} ${verb}`;
9244
9662
  }
9245
9663
  let pred;
9246
- if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words2(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words2(pred[3])}`;
9664
+ if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words3(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words3(pred[3])}`;
9247
9665
  c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`).replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
9248
9666
  c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
9249
9667
  let call;
@@ -9253,14 +9671,14 @@ function sayCodeCondition(cond) {
9253
9671
  return call[2] === "isset" || call[2] === "is_null" ? `${what} is ${call[2] === "isset" === !call[1] ? "" : "not "}set` : `${what} is ${neg ? "not " : ""}empty`;
9254
9672
  }
9255
9673
  if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
9256
- const w = words2(call[2]);
9674
+ const w = words3(call[2]);
9257
9675
  return call[1] ? `not: ${w}` : w;
9258
9676
  }
9259
- const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
9260
- if (bare && !/^(true|false|True|False|None|null|nil)$/.test(bare[2])) {
9261
- const parts = bare[2].split(".");
9262
- const what = parts.length > 1 ? `the ${words2(parts[0])}'s ${words2(parts[1])}` : words2(parts[0]);
9263
- return `${what} is ${bare[1] ? "not " : ""}set`;
9677
+ const bare2 = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
9678
+ if (bare2 && !/^(true|false|True|False|None|null|nil)$/.test(bare2[2])) {
9679
+ const parts = bare2[2].split(".");
9680
+ const what = parts.length > 1 ? `the ${words3(parts[0])}'s ${words3(parts[1])}` : words3(parts[0]);
9681
+ return `${what} is ${bare2[1] ? "not " : ""}set`;
9264
9682
  }
9265
9683
  return clip(c.replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, " is empty").replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, " is not empty").replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, " is set").replace(/\bis not None\b/g, "is set").replace(/\bis None\b/g, "is empty").replace(/\s*(===|==)\s*/g, " is ").replace(/\s*(!==|!=)\s*/g, " is not ").replace(/\s*&&\s*/g, " and ").replace(/\s*\|\|\s*/g, " or ").replace(/\s+not\s+in\s+/g, " is not in ").replace(/(?<!\bis(?: not)?)\s+in\s+(?=[\w$])/g, " is in ").replace(/\s+<=\s+/g, " is at most ").replace(/\s+>=\s+/g, " is at least ").replace(/\s+<\s+/g, " is less than ").replace(/(?<![-=])\s+>\s+/g, " is more than ").replace(/(^|[\s(])!(?=[\w(])/g, "$1not ").replace(/\s+/g, " "), 70);
9266
9684
  }
@@ -9272,11 +9690,11 @@ function matchingClose(str2, open) {
9272
9690
  }
9273
9691
  return -1;
9274
9692
  }
9275
- var lastWords = (path) => words2(String(path).split(".").pop());
9693
+ var lastWords = (path) => words3(String(path).split(".").pop());
9276
9694
  function targetWords(path) {
9277
9695
  const parts = String(path).replace(/^[@$]+/, "").replace(/#/g, "").replace(/\[.*$/, "").split(".").filter((p) => !/^(this|self)$/.test(p));
9278
- if (parts.length <= 1) return words2(parts[0] || path);
9279
- return `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}`;
9696
+ if (parts.length <= 1) return words3(parts[0] || path);
9697
+ return `the ${words3(parts[parts.length - 2])}'s ${words3(parts[parts.length - 1])}`;
9280
9698
  }
9281
9699
  function callee(text) {
9282
9700
  const m = String(text).replace(/\[[^\]]*\]/g, "").match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
@@ -9308,10 +9726,16 @@ function sayValue(expr) {
9308
9726
  if (/^new\s/.test(e)) return `a new ${c.split(".").pop()}`;
9309
9727
  return `the result of ${lastWords(c)}`;
9310
9728
  }
9311
- if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words2(e.replace(/^\$/, "").split(".").pop());
9729
+ if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words3(e.replace(/^\$/, "").split(".").pop());
9312
9730
  if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
9313
9731
  return null;
9314
9732
  }
9733
+ function sayArithmetic(expr) {
9734
+ const ar = String(expr).trim().match(/^([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)\s*([-+*/])\s*([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)$/);
9735
+ if (!ar || ar[2] === "+" && !/^\d/.test(ar[1]) && !/^\d/.test(ar[3])) return null;
9736
+ const side = (x) => /^\d/.test(x) ? x : possessiveWords(x);
9737
+ return `${side(ar[1])} ${{ "+": "plus", "-": "minus", "*": "times", "/": "divided by" }[ar[2]]} ${side(ar[3])}`;
9738
+ }
9315
9739
  var PY_SUMMARY = [
9316
9740
  { re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ""} matches` },
9317
9741
  { re: /^all$/, say: (src, cond) => `whether every item in ${src}${cond ? ` where ${cond}` : ""} matches` },
@@ -9320,7 +9744,7 @@ var PY_SUMMARY = [
9320
9744
  { re: /^max$/, say: (src) => `the largest in ${src}` },
9321
9745
  { re: /^(?:sorted)$/, say: (src) => `${src}, sorted` }
9322
9746
  ];
9323
- var lastSeg = (x) => words2(String(x).trim().replace(/\(\)$/, "").split(".").pop());
9747
+ var lastSeg = (x) => words3(String(x).trim().replace(/\(\)$/, "").split(".").pop());
9324
9748
  function sayPython(value) {
9325
9749
  const e = String(value).trim();
9326
9750
  let m = e.match(/^\[\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\]$/);
@@ -9328,7 +9752,7 @@ function sayPython(value) {
9328
9752
  const [, expr, v, src, cond] = m;
9329
9753
  const vars = v.replace(/[()]/g, "").split(/\s*,\s*/);
9330
9754
  const bareCond = cond && cond.replace(new RegExp(`\\b(?:${vars.join("|")})\\.`, "g"), "");
9331
- const condSaid = cond ? /^\w+$/.test(bareCond) ? words2(bareCond) : sayCodeCondition(bareCond) : null;
9755
+ const condSaid = cond ? /^\w+$/.test(bareCond) ? words3(bareCond) : sayCodeCondition(bareCond) : null;
9332
9756
  if (vars.includes(expr.trim())) return condSaid ? `the items in ${lastSeg(src)} where ${condSaid}` : `the items in ${lastSeg(src)}`;
9333
9757
  return `one ${lastSeg(expr.replace(/\(.*$/, ""))} for each item in ${lastSeg(src)}${condSaid ? ` where ${condSaid}` : ""}`;
9334
9758
  }
@@ -9348,9 +9772,11 @@ function sayPython(value) {
9348
9772
  function sayCommon(value) {
9349
9773
  const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, "");
9350
9774
  let m;
9351
- const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
9775
+ const side = (x) => sayValue(x) ?? sayArithmetic(x) ?? possessiveWords(x.trim());
9352
9776
  if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
9353
- if (m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
9777
+ if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) && !/^(?:if|unless)\b/.test(e)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
9778
+ const ifValue = ifAsValue(e);
9779
+ if (ifValue) return `${side(ifValue.yes)} if ${sayCodeCondition(ifValue.cond)}, otherwise ${side(ifValue.no)}`;
9354
9780
  if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
9355
9781
  if (m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/)) return `a new ${m[1]}`;
9356
9782
  if (m = e.match(/^&([A-Z]\w*)$/)) return `a new ${m[1]}`;
@@ -9373,6 +9799,20 @@ function sayCommon(value) {
9373
9799
  if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
9374
9800
  return null;
9375
9801
  }
9802
+ function ifAsValue(e) {
9803
+ let m;
9804
+ if (m = e.match(/^if\s*\(/)) {
9805
+ const close = matchingClose(e, e.indexOf("("));
9806
+ if (close < 0) return null;
9807
+ const rest2 = e.slice(close + 1).match(/^\s*(?:\{\s*([^{};]+?)\s*\}|([^{};]+?))\s+else\s+(?:\{\s*([^{};]+?)\s*\}|([^{};]+))$/);
9808
+ if (rest2) return { cond: e.slice(e.indexOf("(") + 1, close), yes: rest2[1] ?? rest2[2], no: rest2[3] ?? rest2[4] };
9809
+ return null;
9810
+ }
9811
+ if (m = e.match(/^if\s+([^{}]+?)\s*\{\s*([^{};]+?)\s*\}\s*else\s*\{\s*([^{};]+?)\s*\}$/)) return { cond: m[1], yes: m[2], no: m[3] };
9812
+ if (m = e.match(/^if\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[2], no: m[3] };
9813
+ if (m = e.match(/^unless\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[3], no: m[2] };
9814
+ return null;
9815
+ }
9376
9816
  var LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
9377
9817
  function sayWhether(expr) {
9378
9818
  const e = String(expr).trim();
@@ -9397,7 +9837,7 @@ function sayChain(value) {
9397
9837
  const m = value.match(c.re);
9398
9838
  if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c };
9399
9839
  }
9400
- return hit ? hit.c.say(words2(src.split(".").pop().replace(/^#/, ""))) : null;
9840
+ return hit ? hit.c.say(words3(src.split(".").pop().replace(/^#/, ""))) : null;
9401
9841
  }
9402
9842
  var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
9403
9843
  function httpErrorOf(head) {
@@ -9413,9 +9853,9 @@ function redirectTarget(arg) {
9413
9853
  const a = String(arg || "").trim().replace(/^(?:url|to|location|redirect_to)\s*=\s*/, "");
9414
9854
  let m;
9415
9855
  if (m = a.match(/^(?:new\s+URL\(\s*)?["'`](\/[^"'`$?#]*|https?:\/\/[^"'`$/?#]+[^"'`$?#]*)/)) return m[1];
9416
- if (m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
9417
- if (m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/)) return `the ${words2(m[1].split(/[.:]/).pop())} page`;
9418
- if (m = a.match(/^([A-Za-z_][\w.]*)$/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
9856
+ if (m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/)) return `the ${words3(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
9857
+ if (m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/)) return `the ${words3(m[1].split(/[.:]/).pop())} page`;
9858
+ if (m = a.match(/^([A-Za-z_][\w.]*)$/)) return `the ${words3(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
9419
9859
  return "another page";
9420
9860
  }
9421
9861
  function redirectOf(head) {
@@ -9426,28 +9866,82 @@ function redirectOf(head) {
9426
9866
  const to = redirectTarget(m[1]);
9427
9867
  return { kind: isReturn ? "return" : "call", says: `Sends the person to ${to}`, redirect: to };
9428
9868
  }
9869
+ function objectKeys(expr) {
9870
+ const open = expr.indexOf("{");
9871
+ if (open < 0) return [];
9872
+ let close = -1;
9873
+ for (let i = open, d = 0; i < expr.length; i++) {
9874
+ const c = expr[i];
9875
+ if (c === '"' || c === "'" || c === "`") {
9876
+ for (i++; i < expr.length && expr[i] !== c; i++) if (expr[i] === "\\") i++;
9877
+ continue;
9878
+ }
9879
+ if (c === "{") d++;
9880
+ else if (c === "}" && --d === 0) {
9881
+ close = i;
9882
+ break;
9883
+ }
9884
+ }
9885
+ if (close < 0) return [];
9886
+ const inner = expr.slice(open + 1, close);
9887
+ const keys = [];
9888
+ let depth = 0, cur = "";
9889
+ const take = (part) => {
9890
+ const m = part.trim().match(/^(?:["'](\w+)["']|(\w+))\s*(?::|$|\()/);
9891
+ if (m && !part.trim().startsWith("...")) keys.push(m[1] || m[2]);
9892
+ };
9893
+ for (const c of inner) {
9894
+ if ("([{".includes(c)) depth++;
9895
+ if (")]}".includes(c)) depth--;
9896
+ if (c === "," && depth === 0) {
9897
+ take(cur);
9898
+ cur = "";
9899
+ } else cur += c;
9900
+ }
9901
+ if (cur.trim()) take(cur);
9902
+ return keys.length > 8 ? [...keys.slice(0, 7), "more"] : keys;
9903
+ }
9904
+ var listWords2 = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
9429
9905
  function classifyStatement(raw, { inner = 0 } = {}) {
9430
9906
  const text = String(raw).trim();
9431
- const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
9907
+ let first = text.split("\n")[0].trim();
9908
+ if (/^(?:if|else\s+if|while|for|switch)\s*\($/.test(first.replace(/\s*\{$/, "")) || /^(?:if|else\s+if|while)\s*\(/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ""))) {
9909
+ const o = text.indexOf("("), c2 = matchingClose(text, o);
9910
+ if (c2 > 0 && c2 < 2e3) first = `${text.slice(0, c2 + 1)}${text.slice(c2 + 1).split("\n")[0]}`.replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
9911
+ }
9912
+ const head = first.replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1$2").replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1($2)").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
9432
9913
  const code = clip(head, 90);
9433
9914
  let m;
9434
9915
  const innerNote = inner ? ` (${inner} step${inner === 1 ? "" : "s"} inside)` : "";
9435
9916
  let inl;
9436
- if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
9917
+ if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?|[\w$.]+(?:\+\+|--);?|(?:\+\+|--)[\w$.]+;?)$/)) && balanced(inl[2])) {
9437
9918
  return { kind: "branch", says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
9438
9919
  }
9439
- if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
9920
+ if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
9440
9921
  const cond = sayCodeCondition(inl[3]);
9441
9922
  return { kind: "branch", says: inl[2] === "unless" ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === "unless", code, inline: inl[1] };
9442
9923
  }
9443
- if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words2(inl[1])} yet`, code };
9924
+ if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words3(inl[1])} yet`, code };
9444
9925
  if (inl = head.match(/^([\w$.]+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::\s*[^=]+)?=>|[\w$]+\s*=>)/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
9445
- if (m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) return { kind: "check", says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, "")) ? words2(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
9926
+ if (inl = head.match(/^([\w$.]+)\s*:?=\s*func\s*\(/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
9927
+ if (inl = head.match(/^delete\s+([\w$.]+)(?:\[\s*([^\]]+?)\s*\]|\.([\w$]+));?$/)) return { kind: "call", says: `Removes ${words3(String(inl[2] ?? inl[3]).replace(/["'`]/g, ""))} from ${targetWords(inl[1])}`, code };
9928
+ if (/^fallthrough\b/.test(head)) return { kind: "call", says: "Carries on into the next case too", code };
9929
+ if (inl = head.match(/^goto\s+case\s+(.+?);?$/)) return { kind: "call", says: `Carries on into the case for ${words3(plainEnums(inl[1]))}`, code };
9930
+ if (/^do\s*\{?$/.test(head)) {
9931
+ const dw = text.match(/\}\s*while\s*\(([\s\S]*)\)\s*;?\s*$/);
9932
+ if (dw) return { kind: "loop", says: `Runs once, then repeats while ${sayCodeCondition(dw[1].replace(/\s+/g, " "))}${innerNote}`, code };
9933
+ }
9934
+ if ((inl = head.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/)) && !/[{]\s*$/.test(head) && !/^when\s*\(/.test(head)) {
9935
+ return { kind: "check", says: armSays(inl[1]), code, caseLabel: true, ...inl[2] ? { inline: inl[2] } : {} };
9936
+ }
9937
+ if (inl = head.match(/^when\s*(?:\((.+)\))?\s*\{$/)) return { kind: "branch", says: inl[1] ? `Chooses by ${words3(clip(inl[1], 40))}${innerNote}` : `Checks these cases in order${innerNote}`, code };
9938
+ if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) && /(?:[<>]=?|[!=]==?|&&|\|\|)/.test(m[1].replace(/<-|->/g, "")) && !/^["']/.test(m[1])) return { kind: "check", says: `When ${sayCodeCondition(m[1])}`, code, caseLabel: true };
9939
+ if (m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) return { kind: "check", says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, "")) ? words3(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
9446
9940
  if (/^default\s*(?::|->)/.test(head)) return { kind: "check", says: "Otherwise", code, caseLabel: true };
9447
9941
  if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
9448
9942
  const name = m?.[1] ? m[1].split(".").pop() : null;
9449
9943
  const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
9450
- const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
9944
+ const said = name && /^[a-z]/.test(name) ? `the error made by ${words3(name)}` : name;
9451
9945
  return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
9452
9946
  }
9453
9947
  const httpFail = httpErrorOf(head);
@@ -9468,26 +9962,30 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9468
9962
  }
9469
9963
  const chain = sayChain(expr);
9470
9964
  if (chain) return { kind: "return", says: `Returns ${chain}`, code };
9471
- if (/^\(?\s*\{/.test(expr)) return { kind: "return", says: "Returns an object", code };
9965
+ if (/^\(?\s*\{/.test(expr)) {
9966
+ const keys = objectKeys(expr);
9967
+ return { kind: "return", says: keys.length ? `Returns ${listWords2(keys.map(words3))}` : "Returns an object", code, ...keys.length ? { keys } : {} };
9968
+ }
9472
9969
  if (/^\(?\s*</.test(expr)) return { kind: "return", says: "Returns what to show on screen", code };
9473
9970
  const v = sayValue(expr) || sayWhether(expr);
9474
9971
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a computed value", code, ...v ? {} : { value: clip(expr, 60) } };
9475
9972
  }
9476
9973
  if (m = head.match(/^for\b\s*\(?\s*(?:(?:var|let|const|int|long|size_t|auto|\$)\s*)?\$?(\w+)\s*:?=\s*([^;]+?)\s*;\s*([^;]*?)\s*;\s*[^)]*?\)?\s*\{?\s*$/)) {
9477
- return { kind: "loop", says: `Counts ${words2(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
9974
+ return { kind: "loop", says: `Counts ${words3(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
9478
9975
  }
9976
+ if (m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
9479
9977
  if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val)?\s*[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
9480
9978
  const src = stripTail(m[3]).replace(/\($/, "()").replace(/^Object\.entries\((.+)\)$/, "$1").replace(/\.(?:items|entries)\(\)$/, "");
9481
- return { kind: "loop", says: `For each ${words2(m[1])} and ${words2(m[2])} in ${words2(src.split(".").pop())}${innerNote}`, code };
9979
+ return { kind: "loop", says: `For each ${words3(m[1])} and ${words3(m[2])} in ${words3(src.split(".").pop())}${innerNote}`, code };
9482
9980
  }
9483
9981
  if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
9484
- return { kind: "loop", says: `For each ${words2(m[1].split(",").pop().trim())} in ${words2(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
9982
+ return { kind: "loop", says: `For each ${words3(m[1].split(",").pop().trim())} in ${words3(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
9485
9983
  }
9486
- if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words2(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
9487
- if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[1])} in ${words2(m[2].split(".").pop())}${innerNote}`, code };
9488
- if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
9489
- if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
9490
- if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words2(m[1].split(".").pop())}${innerNote}`, code };
9984
+ if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words3(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
9985
+ if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words3(m[1])} in ${words3(m[2].split(".").pop())}${innerNote}`, code };
9986
+ if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words3(m[2])} in ${words3(m[1].split(".").pop())}${innerNote}`, code };
9987
+ if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words3(m[2])} in ${words3(m[1].split(".").pop())}${innerNote}`, code };
9988
+ if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words3(m[1].split(".").pop())}${innerNote}`, code };
9491
9989
  if (m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
9492
9990
  if (m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*([\w.]+)\(.*\);\s*err\s*!=\s*nil\s*\{?\s*$/)) return { kind: "branch", says: `If ${lastWords(m[1])} fails${innerNote}`, code };
9493
9991
  if (m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/)) {
@@ -9498,20 +9996,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9498
9996
  const cond = sayCodeCondition(m[1]);
9499
9997
  return { kind: "branch", says: `If ${/^unless\b/.test(head) ? "not: " : ""}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, "$1"), code, negate: /^unless\b/.test(head) };
9500
9998
  }
9501
- if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words2(clip(m[1], 40)) || "value"}${innerNote}`, code };
9999
+ if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: "branch", says: `Checks these cases in order${innerNote}`, code };
10000
+ if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words3(clip(m[1], 40)) || "value"}${innerNote}`, code };
9502
10001
  if (/^(?:try|begin)\b/.test(head)) return { kind: "try", says: `Tries the next steps and handles any error${innerNote}`, code };
9503
10002
  if (m = head.match(/^assert\b\s*(.*?)\s*;?$/)) return { kind: "check", says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, "")) : "a condition holds"}`, code };
9504
10003
  if (m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
9505
10004
  if (m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
9506
- if (m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
9507
- const what = /^open\s*\(/.test(m[1]) ? "a file" : words2(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
9508
- return { kind: "set", says: `Opens ${what} as ${words2(m[2].replace(/[()]/g, ""))}`, code };
10005
+ if (m = head.match(/^(?:async\s+)?with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
10006
+ const what = /^open\s*\(/.test(m[1]) ? "a file" : words3(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
10007
+ return { kind: "set", says: `Opens ${what} as ${words3(m[2].replace(/[()]/g, ""))}`, code };
9509
10008
  }
9510
10009
  if (m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/)) return { kind: "set", says: `Uses ${clip(m[1], 50)}`, code };
9511
10010
  if (/^defer\b/.test(head)) return { kind: "call", says: `At the end, ${clip(head.replace(/^defer\s+/, ""), 60)}`, code };
9512
10011
  if (/^super\b/.test(head)) return { kind: "call", says: "Runs the parent version first", code };
9513
10012
  if (/^yield\b/.test(head)) return { kind: "call", says: "Hands control to the given block", code };
9514
- if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words2(m[1])}`, code };
10013
+ if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words3(m[1])}`, code };
9515
10014
  if (m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/)) return { kind: "return", says: `Returns ${m[1]}`, code };
9516
10015
  if (/^vec!?\[/.test(head)) return { kind: "return", says: "Returns a list", code };
9517
10016
  if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
@@ -9519,21 +10018,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9519
10018
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a value", code };
9520
10019
  }
9521
10020
  if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: "set", says: `${/\+\+/.test(head) ? "Adds one to" : "Subtracts one from"} ${targetWords(m[1].replace(/#/g, ""))}`, code };
9522
- if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words2(m[1])}`, code };
9523
- if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
9524
- if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
10021
+ if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words3(m[1])}`, code };
10022
+ if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words3(m[1])}`, code };
10023
+ if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words3(m[1])}`, code };
9525
10024
  if (m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/)) {
9526
- const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words2);
10025
+ const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words3);
9527
10026
  const value = stripTail(m[3]);
9528
10027
  const c2 = callee(value);
9529
- const from = c2 ? lastWords(c2) : sayValue(value) || words2(value.split(".").pop());
10028
+ const from = c2 ? lastWords(c2) : sayValue(value) || words3(value.split(".").pop());
9530
10029
  return { kind: "set", says: `Takes ${names.slice(0, 4).join(", ")}${names.length > 4 ? ", \u2026" : ""} from ${from}`, code };
9531
10030
  }
9532
10031
  if (m = head.match(/^(?:var|const)\s*\($/)) return { kind: "set", says: "Declares some values", code };
9533
- if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words2).join(", ")}`, code };
10032
+ if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words3).join(", ")}`, code };
9534
10033
  if (m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/)) {
9535
10034
  const value = stripTail(m[3]);
9536
- const target = words2(m[2]);
10035
+ const target = words3(m[2]);
9537
10036
  const c2 = value ? callee(value) : null;
9538
10037
  const everyday = value ? sayPython(value) || sayCommon(value) : null;
9539
10038
  if (everyday) return { kind: "set", says: `Sets ${target} to ${everyday}`, code };
@@ -9549,14 +10048,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9549
10048
  if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, "").match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
9550
10049
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== "_").map(targetWords).join(", ") || targetWords(m[1]);
9551
10050
  const value = stripTail(m[3]);
9552
- if (m[2] === "=" && !/[(?]/.test(value.replace(/^\(|\)$/g, "")) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, ".")) && !/=>/.test(value)) return { kind: "set", says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
9553
- if (m[2] === "=" && /^[A-Za-z_]\w*$/.test(value) && m[1].split(".").pop() === value && /^(self|this)\./.test(m[1])) return { kind: "set", says: `Keeps the ${words2(value)} it is given`, code };
10051
+ if (m[2] === "=" && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, "")) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, ".")) && !/=>/.test(value)) return { kind: "set", says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
10052
+ if (m[2] === "=" && /^[A-Za-z_]\w*$/.test(value) && m[1].split(".").pop() === value && /^(self|this)\./.test(m[1])) return { kind: "set", says: `Keeps the ${words3(value)} it is given`, code };
9554
10053
  const chain = value ? sayPython(value) || sayChain(value) : null;
9555
10054
  if (chain) return { kind: "set", says: `Works out ${target}: ${chain}`, code };
9556
10055
  const common = value ? sayCommon(m[3].trim().replace(/;$/, "")) || sayCommon(value) : null;
9557
10056
  if (common) return { kind: "set", says: `Sets ${target} to ${common}`, code };
9558
10057
  const keyed = m[2] === "=" && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
9559
- if (keyed) return { kind: "set", says: `Records ${words2(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
10058
+ if (keyed) return { kind: "set", says: `Records ${words3(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
9560
10059
  const c2 = callee(value);
9561
10060
  if (c2) {
9562
10061
  const known = sayCall(c2, firstArgs(value));
@@ -9566,7 +10065,7 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9566
10065
  }
9567
10066
  if (!value) return { kind: "set", says: `Works out ${target}`, code };
9568
10067
  if (m[2] === "+=" || m[2] === "-=") {
9569
- const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words2).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
10068
+ const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words3).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
9570
10069
  return { kind: "set", says: what ? `${m[2] === "+=" ? "Adds" : "Subtracts"} ${what}${m[2] === "+=" ? "to" : "from"} ${target}` : `${m[2] === "+=" ? "Adds to" : "Subtracts from"} ${target}`, code };
9571
10070
  }
9572
10071
  const v = sayValue(value);
@@ -9575,14 +10074,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9575
10074
  if (m = head.match(/^([\w$.]+)\.(?:set|Set|put|setdefault|Add)\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,/)) return { kind: "call", says: `Sets "${m[2]}" on ${lastSeg(m[1])}`, code, callee: `${m[1]}.set` };
9576
10075
  if ((m = head.match(/^([\w$.]+)\.(?:remove|Remove|discard|delete|pop)\(\s*([\w$]+)\s*\)/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
9577
10076
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
9578
- const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
9579
- return { kind: "call", says: `Removes ${words2(m[2])} from ${where}`, code, callee: m[1] };
10077
+ const where = owner.length > 1 ? `${words3(owner[owner.length - 2])}'s ${words3(owner[owner.length - 1])}` : words3(owner[0] || m[1]);
10078
+ return { kind: "call", says: `Removes ${words3(m[2])} from ${where}`, code, callee: m[1] };
9580
10079
  }
9581
10080
  if ((m = head.match(/^([\w$.]+)\.(?:append|push|add|Add|insert|appendleft|extend)\(\s*([\w$.]*)\s*\)?/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
9582
10081
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
9583
- const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
10082
+ const where = owner.length > 1 ? `${words3(owner[owner.length - 2])}'s ${words3(owner[owner.length - 1])}` : words3(owner[0] || m[1]);
9584
10083
  const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf("(") + 1))?.[1];
9585
- return { kind: "call", says: added ? `Adds a new ${words2(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words2(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
10084
+ return { kind: "call", says: added ? `Adds a new ${words3(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words3(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
9586
10085
  }
9587
10086
  const c = callee(head);
9588
10087
  if (c) {
@@ -9593,12 +10092,20 @@ function classifyStatement(raw, { inner = 0 } = {}) {
9593
10092
  if (/^assert/.test(m[1])) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
9594
10093
  const known = sayCall(m[1], m[2]);
9595
10094
  const named = /^[:'"]([\w ]+)['"]?/.exec(m[2].trim())?.[1];
9596
- return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words2(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
10095
+ return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words3(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
9597
10096
  }
9598
10097
  return { kind: "other", says: clip(head, 70), code };
9599
10098
  }
9600
10099
  var spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...s.start != null && s.end != null ? { start: s.start, end: s.end } : {} });
9601
10100
  var BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
10101
+ var bracketsClosed = (x) => {
10102
+ let d = 0;
10103
+ for (const ch of x) {
10104
+ if ("([{".includes(ch)) d++;
10105
+ else if (")]}".includes(ch)) d--;
10106
+ }
10107
+ return d === 0;
10108
+ };
9602
10109
  var balanced = (x) => {
9603
10110
  let d = 0;
9604
10111
  for (const ch of x) {
@@ -9635,12 +10142,195 @@ function attachClause(step, clause) {
9635
10142
  step.always = { line: clause.line, steps: kids2 };
9636
10143
  }
9637
10144
  }
10145
+ function orList(names) {
10146
+ const n = [...new Set(names)];
10147
+ if (n.length <= 3) return n.length > 1 ? `${n.slice(0, -1).join(", ")} or ${n[n.length - 1]}` : n[0] || "";
10148
+ return `${n.slice(0, 3).join(", ")} or ${n.length - 3} other value${n.length - 3 === 1 ? "" : "s"}`;
10149
+ }
10150
+ function depsOf(after) {
10151
+ const a = String(after || "");
10152
+ if (/^\s*\)/.test(a)) return null;
10153
+ const m = a.match(/^\s*,\s*\[([^\]]*)\]/);
10154
+ if (!m) return "unknown";
10155
+ return m[1].split(",").map((x) => x.trim().replace(/\?\./g, ".").replace(/\(\)$/, "")).filter(Boolean).map((x) => words3(x.split(".").pop()));
10156
+ }
10157
+ var changesWords = (deps) => `${orList(deps)} ${deps.length > 3 ? "change" : "changes"}`;
10158
+ function effectSays(deps) {
10159
+ if (deps === null) return "Every time this is drawn on screen";
10160
+ if (deps === "unknown") return "When this first shows on screen, and whenever what it watches changes";
10161
+ if (!deps.length) return "When this first shows on screen";
10162
+ return `When this first shows on screen, and whenever ${changesWords(deps)}`;
10163
+ }
10164
+ var HOOK = /^(?:(?:const|let|var)\s+([\w$]+)(?:\s*:[^=]+?)?\s*=\s*)?(?:React\.)?(use[A-Z]\w*)\s*(?:<[^(]*?>)?\(/;
10165
+ var TRAILING_LAMBDA = /^(?:(?:val|var)\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*)?([a-z_$][\w$]*(?:\??\.[\w$]+)*)\s*(\([^{}]*\))?\s*\{\s*(?:\(?[\w$, ]+\)?\s*->)?\s*$/;
10166
+ var RUBY_DO = /^(?:[@$]?[\w]+\s*=\s*)?([a-z_][\w.?!]*)(?:\(.*\)|\s+[^|]*?)?\s+do\s*(?:\|[^|]*\|)?\s*$/;
10167
+ var NOT_A_CALL = /^(?:if|else|for|while|when|return|object|init|companion|class|interface|fun|try|catch|finally|do|loop|unsafe|match|switch|select|synchronized|lock|using|get|set)$/;
10168
+ function thenSays(text) {
10169
+ const m = String(text).match(/^(?:await\s+)?([^{};\n]*?)\.(then|catch)\(\s*(?:async\s+)?(?:function\b|\(|[\w$]+\s*=>)/);
10170
+ if (!m) return null;
10171
+ const recvText = m[1].trim().replace(/^\(\s*([\w$.]+)\s+as\s+[^()]*\)$/, "$1");
10172
+ const recv = recvText.match(/^([\w$.]+)\(.*\)$/s) || recvText.match(/^([\w$.]+)$/);
10173
+ const what = recv ? lastWords(recv[1]) : "that";
10174
+ return m[2] === "then" ? `When ${what} is done` : `If ${what} goes wrong`;
10175
+ }
10176
+ function nestedStep(s, base) {
10177
+ const text = String(s.text || "").trim();
10178
+ const head = text.split("\n")[0].trim();
10179
+ const kids2 = () => stepsFrom(s.children || []).steps;
10180
+ const own = (step, children) => children.length ? { ...step, children, nested: true } : step;
10181
+ let m;
10182
+ if (s.fn && s.fn.depth === 1 && (m = text.match(HOOK))) {
10183
+ const [, name, hook] = m;
10184
+ const deps = depsOf(s.fn.after);
10185
+ if (/^use\w*Effect$/.test(hook)) {
10186
+ for (const c of s.children || []) if (c.fn && /^return\b/.test(c.text.trim())) c.cleanup = deps && deps !== "unknown" && !deps.length ? "When this is taken off the screen, cleans up" : "Cleans up before it runs again, and when this is taken off the screen";
10187
+ return own({ kind: "call", says: effectSays(deps), code: base.code, callee: hook }, kids2());
10188
+ }
10189
+ if (hook === "useMemo" && name) {
10190
+ let children = kids2();
10191
+ if (s.fn.expr && children.length === 1) {
10192
+ const v = classifyStatement(`return ${s.children[0].text}`);
10193
+ children = [{ ...children[0], kind: v.kind, says: v.says }];
10194
+ }
10195
+ const says = deps === null ? `Works out ${words3(name)}` : Array.isArray(deps) && !deps.length ? `Works out ${words3(name)} once and remembers it` : Array.isArray(deps) ? `Works out ${words3(name)} and remembers it until ${changesWords(deps)}` : `Works out ${words3(name)} and remembers it until what it watches changes`;
10196
+ return own({ kind: "set", says, code: base.code, callee: hook }, children);
10197
+ }
10198
+ if (/^use\w*Callback$/.test(hook) && name) return own({ kind: "set", says: `Defines how ${words3(name)} works`, code: base.code, callee: hook }, kids2());
10199
+ }
10200
+ if (s.cleanup) return own({ kind: "call", says: s.cleanup, code: base.code }, kids2());
10201
+ if (s.fn && !s.fn.expr) {
10202
+ if (s.fn.depth === 0 && /^go\s+func\b/.test(head)) return own({ kind: "call", says: "Starts these steps running alongside, without waiting for them", code: base.code }, kids2());
10203
+ if (s.fn.depth === 0 && /^defer\s+func\b/.test(head)) return own({ kind: "call", says: "At the end, runs these steps", code: base.code }, kids2());
10204
+ if (/^return\b/.test(head) || base.kind === "return" || base.kind === "other" || base.kind === "branch" || base.kind === "fail") return null;
10205
+ if (base.kind === "loop") return null;
10206
+ let said = base.says;
10207
+ if (base.kind !== "call") {
10208
+ } else if (m = text.match(/^(?:window\.|globalThis\.)?(setTimeout|setInterval)\(/)) {
10209
+ const ms = (s.fn.after.match(/^\s*,\s*(\d+)\s*\)/) || [])[1];
10210
+ said = m[1] === "setTimeout" ? ms ? `After ${ms} milliseconds` : "After a wait" : ms ? `Every ${ms} milliseconds` : "Again and again, with a wait in between";
10211
+ } else if (m = text.match(/\.(addEventListener|on|once)\(\s*['"`]([\w:.-]+)['"`]\s*,/)) {
10212
+ said = m[1] === "once" ? `The first time "${m[2]}" happens` : `Whenever "${m[2]}" happens`;
10213
+ } else if (thenSays(text)) {
10214
+ said = thenSays(text);
10215
+ } else if (/^Calls [\w ]+$/.test(said)) said = `${said} with these steps`;
10216
+ return own({ ...base, kind: base.kind === "set" ? "set" : "call", says: said }, kids2());
10217
+ }
10218
+ if (!s.children?.length) return null;
10219
+ const raw = String(s.text || "").split("\n")[0].trim();
10220
+ if (!s.fn && !BLOCK_HEAD.test(raw) && (m = raw.match(TRAILING_LAMBDA)) && !NOT_A_CALL.test(m[1])) {
10221
+ const safe = m[1].match(/^(.+?)\?\.(?:let|also|run|apply)$/);
10222
+ if (safe) return own({ kind: "branch", says: `If ${words3(safe[1].split(/\??\./).pop())} is set`, code: clip(raw, 90) }, kids2());
10223
+ if (m = raw.match(/^repeat\s*\(\s*(.+?)\s*\)\s*\{/)) return own({ kind: "loop", says: `Repeats ${/^\d+$/.test(m[1]) ? m[1] : words3(m[1])} times`, code: base.code }, kids2());
10224
+ if (base.kind === "loop") return null;
10225
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says} with these steps` }, kids2());
10226
+ if (base.kind === "set" || base.kind === "call") return own(base, kids2());
10227
+ return null;
10228
+ }
10229
+ if ((m = raw.match(RUBY_DO)) && base.kind !== "loop" && !/^(?:if|unless|while|until|for|case|begin)\b/.test(raw)) {
10230
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says.replace(/: .*$/, "")} with these steps` }, kids2());
10231
+ if (base.kind === "call" || base.kind === "set") return own(base, kids2());
10232
+ }
10233
+ return null;
10234
+ }
10235
+ function valueChoice(s) {
10236
+ const head = headLine(s.text || "");
10237
+ let m = head.match(/^(?:(?:const|let|var|val|my)\s+(?:mut\s+)?)?([@$]?[\w$.]+)(?:\s*:\s*[^=]+?)?\s*=\s*((?:if|unless|match|when|case)\b.*|[\w.]+\s+switch\s*\{\s*)$/);
10238
+ if (m && !/^(?:if|for|while|return)$/.test(m[1])) return { target: targetWords(m[1]), rest: m[2] };
10239
+ if (m = head.match(/^return\s+((?:if|match|when)\b.*|[\w.]+\s+switch\s*\{\s*)$/)) return { target: null, rest: m[1] };
10240
+ return null;
10241
+ }
10242
+ function armsSubject(rest2) {
10243
+ const r = rest2.replace(/\{\s*$/, "").trim();
10244
+ const m = r.match(/^match\s*\((.+)\)$/) || r.match(/^match\s+(.+)$/) || r.match(/^when\s*\((.+)\)$/) || r.match(/^([\w.]+)\s+switch$/);
10245
+ return m ? m[1].trim() : null;
10246
+ }
10247
+ function armSays(pattern) {
10248
+ let p = String(pattern).trim();
10249
+ if (/^(?:_|else|default)$/.test(p)) return "Otherwise";
10250
+ let guard = null;
10251
+ const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
10252
+ if (g) {
10253
+ p = g[1];
10254
+ guard = g[2];
10255
+ }
10256
+ if (LOGIC.test(p) && !/^(?:!?in|!?is)\s/.test(p) && !/\.\./.test(p) && !/\|/.test(p.replace(/\|\|/g, ""))) return `When ${sayCodeCondition(p)}`;
10257
+ const parts = [];
10258
+ let depth = 0, from = 0;
10259
+ for (let i = 0; i <= p.length; i++) {
10260
+ const c = p[i];
10261
+ if (c === "(" || c === "[" || c === "{") depth++;
10262
+ else if (c === ")" || c === "]" || c === "}") depth--;
10263
+ if (i === p.length || depth === 0 && (c === "|" && p[i + 1] !== "|" && p[i - 1] !== "|" || c === ",")) {
10264
+ parts.push(p.slice(from, i).trim());
10265
+ from = i + 1;
10266
+ }
10267
+ }
10268
+ const one = (x) => {
10269
+ let m;
10270
+ if ((m = x.match(/^(!?)in\s+(.+?)\.\.(=?)(.+)$/)) || (m = x.match(/^()(-?[\w.]+)\.\.(=)(-?[\w.]+)$/))) return `${m[1] ? "not " : ""}from ${m[2].trim()} to ${m[4].trim()}`;
10271
+ if (m = x.match(/^(!?)is\s+([\w.<>?]+)$/)) return `${m[1] ? "not " : ""}a ${m[2].split(".").pop()}`;
10272
+ if (m = x.match(/^(?:[A-Z]\w*(?:::|\.))+([A-Z]\w*)$/)) return words3(m[1]);
10273
+ if (/^[A-Z][A-Z0-9_]+$/.test(x)) return words3(x);
10274
+ return x;
10275
+ };
10276
+ return `When it is ${orList(parts.filter(Boolean).map(one))}${guard ? `, and ${sayCodeCondition(guard)}` : ""}`;
10277
+ }
10278
+ function giveValue(list, target) {
10279
+ if (!list?.length) return;
10280
+ if (list.some((x) => x.caseLabel)) {
10281
+ for (const x of list) if (x.caseLabel) giveValue(x.children, target);
10282
+ return;
10283
+ }
10284
+ const i = list.length - 1;
10285
+ const last = list[i];
10286
+ if (last.kind === "branch" && !Object.hasOwn(last, "valueOf")) {
10287
+ giveValue(last.children, target);
10288
+ giveValue(last.otherwise, target);
10289
+ return;
10290
+ }
10291
+ if (last.kind === "fail" || /^(?:return|break|continue|throw|raise)\b/.test(last.code || "")) return;
10292
+ const v = classifyStatement(`return ${String(last.code || "").replace(/,$/, "")}`);
10293
+ if (v.kind !== "return") return;
10294
+ const said = v.says.replace(/^Returns /, "");
10295
+ list[i] = target ? { ...last, kind: "set", says: v.value ? `Sets ${target} to a computed value` : `Sets ${target} to ${said}` } : { ...last, kind: "return", says: v.says };
10296
+ delete list[i].callee;
10297
+ if (list[i].says && restates(list[i])) list[i].restates = true;
10298
+ else delete list[i].restates;
10299
+ }
10300
+ function selectCaseSays(code) {
10301
+ const c = String(code).trim();
10302
+ if (/^default\s*:/.test(c)) return "If none is ready yet";
10303
+ let m = c.match(/^case\s+(?:([\w$]+)(?:\s*,\s*([\w$]+))?\s*:?=\s*)?<-\s*(.+?)\s*:\s*$/);
10304
+ if (m) {
10305
+ const [, name, ok, ch] = m;
10306
+ let d;
10307
+ if (/\.Done\(\)$/.test(ch)) return `When ${lastWords(ch.replace(/\.Done\(\)$/, ""))} is cancelled or times out`;
10308
+ if (d = ch.match(/^time\.After\((.+)\)$/)) {
10309
+ const t = d[1].trim();
10310
+ const u = t.match(/^(\d+)\s*\*\s*time\.(Millisecond|Second|Minute|Hour)$/) || t.match(/^time\.(Millisecond|Second|Minute|Hour)$/);
10311
+ const dur = u ? u.length === 3 ? `${u[1]} ${u[2].toLowerCase()}${u[1] === "1" ? "" : "s"}` : `1 ${u[1].toLowerCase()}` : words3(t.split(".").pop());
10312
+ return `When ${dur} ${/s$/.test(dur) && !/^1 /.test(dur) ? "have" : "has"} passed`;
10313
+ }
10314
+ if (/\.C$/.test(ch)) return `When ${lastWords(ch.replace(/\.C$/, ""))} ticks`;
10315
+ const from = lastWords(ch.replace(/\(\)$/, ""));
10316
+ return name && name !== "_" ? `When ${words3(name)} arrives from ${from}${ok ? ` (or ${from} is closed)` : ""}` : `When something arrives from ${from}`;
10317
+ }
10318
+ if (m = c.match(/^case\s+(.+?)\s*<-\s*(.+?)\s*:\s*$/)) return `When ${words3(m[2].split(".").pop())} can be sent to ${lastWords(m[1])}`;
10319
+ return null;
10320
+ }
9638
10321
  function stepsFrom(statements) {
9639
10322
  const steps = [];
9640
10323
  const skipped = [];
9641
10324
  let into = null, intoAlways = false;
9642
10325
  for (const s of statements) {
9643
10326
  const t0 = (s.text || "").trim();
10327
+ if (s.arm != null) {
10328
+ const arm = { kind: "check", says: armSays(s.arm), code: clip(t0.split("\n")[0].trim(), 90), caseLabel: true, line: s.line, span: spanOf(s) };
10329
+ const kids2 = stepsFrom(s.children || []).steps;
10330
+ if (kids2.length) arm.children = kids2;
10331
+ steps.push(arm);
10332
+ continue;
10333
+ }
9644
10334
  if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
9645
10335
  const st = stepsFrom([s]).steps;
9646
10336
  into.push(...st);
@@ -9658,7 +10348,9 @@ function stepsFrom(statements) {
9658
10348
  if (prev2 && (prev2.kind === "branch" || prev2.kind === "try")) {
9659
10349
  const prev3 = prev2;
9660
10350
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? "elif" : /^else\b/.test(t0) ? "else" : /^(?:finally|ensure)\b/.test(t0) ? "finally" : "catch";
9661
- attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: s.children || [] });
10351
+ const inlineElse = kw === "else" && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
10352
+ const clauseKids = inlineElse ? [{ text: inlineElse[1], line: s.line, endLine: s.line }, ...s.children || []] : s.children || [];
10353
+ attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: clauseKids });
9662
10354
  intoAlways = kw === "finally";
9663
10355
  into = s.children?.length ? null : kw === "catch" ? prev3.handlers?.[prev3.handlers.length - 1]?.steps ?? null : kw === "finally" ? prev3.always?.steps ?? null : null;
9664
10356
  prev3.span = { ...prev3.span, endLine: Math.max(prev3.span.endLine, s.endLine ?? s.line) };
@@ -9667,7 +10359,7 @@ function stepsFrom(statements) {
9667
10359
  skipped.push(spanOf(s));
9668
10360
  continue;
9669
10361
  }
9670
- if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) {
10362
+ if (!t0 || /^(?:end\b|\}|pass$|break;?$|continue;?$|#)/.test(t0)) {
9671
10363
  if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s));
9672
10364
  continue;
9673
10365
  }
@@ -9679,16 +10371,54 @@ function stepsFrom(statements) {
9679
10371
  skipped.push(spanOf(s));
9680
10372
  continue;
9681
10373
  }
9682
- const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
10374
+ const head0 = headLine(s.text);
10375
+ if (/^\{/.test(t0) && s.children?.length) {
10376
+ steps.push(...stepsFrom(s.children).steps);
10377
+ continue;
10378
+ }
10379
+ const choice = s.children?.length || s.clauses || s.arms ? valueChoice(s) : null;
10380
+ if (s.arms) {
10381
+ const subject = armsSubject(choice ? choice.rest : head0);
10382
+ const kids2 = stepsFrom(s.children || []).steps;
10383
+ const chooser = { kind: "branch", says: subject ? `Chooses by ${words3(clip(subject, 40))}` : "Checks these cases in order", code: clip(head0, 90), line: s.line, span: spanOf(s), ...kids2.length ? { children: kids2 } : {}, ...choice ? { valueOf: choice.target } : {} };
10384
+ steps.push(chooser);
10385
+ continue;
10386
+ }
10387
+ let step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
10388
+ if (choice && /^(?:if|unless|case)\b/.test(choice.rest) && (s.endLine ?? s.line) > s.line) {
10389
+ step = { ...classifyStatement(choice.rest, { inner: s.inner || 0 }), code: step.code, line: s.line, span: spanOf(s), valueOf: choice.target };
10390
+ } else {
10391
+ const nest = nestedStep(s, step);
10392
+ if (!nest && step.kind === "return" && s.fn && !s.fn.expr && s.fn.depth >= 1 && s.children?.length) {
10393
+ const kids2 = stepsFrom(s.children).steps;
10394
+ if (kids2.length) {
10395
+ let m;
10396
+ const body = s.text.trim().replace(/^return\s+/, "");
10397
+ const said = (m = body.match(/^new\s+([A-Z]\w*)/)) ? `Makes a new ${m[1]} with these steps` : thenSays(body) ? thenSays(body) : callee(body) ? `Calls ${lastWords(callee(body))} with these steps` : null;
10398
+ if (said) steps.push({ kind: "call", says: said, code: step.code, line: s.line, span: spanOf(s), children: kids2, nested: true });
10399
+ }
10400
+ }
10401
+ if (nest) {
10402
+ step = { ...nest, line: s.line, span: spanOf(s) };
10403
+ for (const c of s.clauses || []) attachClause(step, c);
10404
+ steps.push(step);
10405
+ continue;
10406
+ }
10407
+ }
9683
10408
  if (step.inline && !/^\{/.test(step.inline.trim())) {
9684
10409
  const kid = classifyStatement(step.inline);
9685
10410
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
9686
10411
  delete step.inline;
9687
- } else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
10412
+ } else if (s.children?.length && (["branch", "loop", "try"].includes(step.kind) || step.kind === "check" && step.caseLabel || /^(?:Defines a helper|Defines how|Opens |Uses )/.test(step.says))) {
9688
10413
  const kids2 = stepsFrom(s.children).steps;
9689
10414
  if (kids2.length) {
9690
10415
  step.children = kids2;
9691
10416
  step.says = step.says.replace(/ \(\d+ steps? inside\)$/, "");
10417
+ if (/^Defines/.test(step.says)) step.nested = true;
10418
+ }
10419
+ if (/^select\s*\{/.test(head0) && step.children) {
10420
+ for (const k of step.children) if (k.caseLabel) k.says = selectCaseSays(k.code) ?? k.says;
10421
+ step.says = step.children.some((k) => /^default\b/.test(k.code || "")) ? "Checks which of these is ready, without waiting" : "Waits for whichever of these is ready first";
9692
10422
  }
9693
10423
  }
9694
10424
  if (step.inline && !step.children) {
@@ -9696,10 +10426,16 @@ function stepsFrom(statements) {
9696
10426
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
9697
10427
  delete step.inline;
9698
10428
  } else delete step.inline;
9699
- for (const c of s.clauses || []) attachClause(step, c);
10429
+ if (step.kind === "branch" || step.kind === "try") for (const c of s.clauses || []) attachClause(step, c);
9700
10430
  steps.push(step);
9701
10431
  }
9702
10432
  for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
10433
+ for (const st of steps) if (Object.hasOwn(st, "valueOf")) {
10434
+ const t = st.valueOf;
10435
+ delete st.valueOf;
10436
+ giveValue(st.children, t);
10437
+ giveValue(st.otherwise, t);
10438
+ }
9703
10439
  const more = Math.max(0, steps.length - MAX_STEPS);
9704
10440
  for (const st of steps) if (restates(st)) st.restates = true;
9705
10441
  return { steps, more, skipped, readable: readableShare(steps) };
@@ -9708,7 +10444,7 @@ var GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec|m
9708
10444
  function restates(st) {
9709
10445
  const s = st.says || "";
9710
10446
  if (st.kind === "other") return false;
9711
- if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
10447
+ if (/^Works out [^:]+$/.test(s) && !/ from | remembers it/.test(s)) return true;
9712
10448
  const same = s.match(/^Works out (.+) from (.+)$/);
9713
10449
  if (same && same[1].trim() === same[2].trim()) return true;
9714
10450
  if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
@@ -9730,22 +10466,225 @@ var blockEnd = (text, open) => {
9730
10466
  }
9731
10467
  return -1;
9732
10468
  };
10469
+ var headLine = (text) => String(text).trim().replace(/^([^\n]*?=)[ \t]*\r?\n\s*/, "$1 ").split("\n")[0].trim();
10470
+ var skipQuoted = (text, i) => {
10471
+ const q = text[i];
10472
+ for (i++; i < text.length && text[i] !== q; i++) if (text[i] === "\\") i++;
10473
+ return i;
10474
+ };
10475
+ var BLOCK_HEAD = /^(?:if|else|for|foreach|while|until|switch|try|catch|finally|do|match|loop|unsafe|select|using|lock|synchronized|when|case|default|elif|with|class|struct|interface|enum|impl|fn|fun|func|def)\b/;
10476
+ function fnLiteral(text) {
10477
+ let depth = 0;
10478
+ const bodyAt = (j, d) => {
10479
+ while (j < text.length && /\s/.test(text[j])) j++;
10480
+ if (text[j] !== "{") return null;
10481
+ const close = blockEnd(text, j);
10482
+ return close < 0 ? null : { open: j, close, depth: d };
10483
+ };
10484
+ for (let i = 0; i < text.length; i++) {
10485
+ const c = text[i];
10486
+ if (c === '"' || c === "'" || c === "`") {
10487
+ i = skipQuoted(text, i);
10488
+ continue;
10489
+ }
10490
+ if (c === "(" || c === "[") {
10491
+ depth++;
10492
+ continue;
10493
+ }
10494
+ if (c === ")" || c === "]") {
10495
+ depth--;
10496
+ continue;
10497
+ }
10498
+ if (c === "{") {
10499
+ const e = blockEnd(text, i);
10500
+ if (e < 0) return null;
10501
+ i = e;
10502
+ continue;
10503
+ }
10504
+ if (c === "=" && text[i + 1] === ">") {
10505
+ const before = text.slice(Math.max(0, i - 80), i).trimEnd();
10506
+ if (!/(?:\)|[A-Za-z_$][\w$]*)(?:\s*:\s*[^=()]+)?$/.test(before) || /["']$/.test(before)) {
10507
+ i++;
10508
+ continue;
10509
+ }
10510
+ const body = bodyAt(i + 2, depth);
10511
+ if (body) return body;
10512
+ if (depth < 1) {
10513
+ i++;
10514
+ continue;
10515
+ }
10516
+ let j = i + 2, d = 0;
10517
+ for (; j < text.length; j++) {
10518
+ const ch = text[j];
10519
+ if (ch === '"' || ch === "'" || ch === "`") {
10520
+ j = skipQuoted(text, j);
10521
+ continue;
10522
+ }
10523
+ if (ch === "(" || ch === "[" || ch === "{") d++;
10524
+ else if (ch === ")" || ch === "]" || ch === "}") {
10525
+ if (--d < 0) break;
10526
+ } else if (ch === "," && d === 0) break;
10527
+ }
10528
+ return { expr: [i + 2, j], depth };
10529
+ }
10530
+ if (c === "-" && text[i + 1] === ">" && depth >= 1) {
10531
+ const body = bodyAt(i + 2, depth);
10532
+ if (body) return body;
10533
+ i++;
10534
+ continue;
10535
+ }
10536
+ if (c === "f" && /\b(?:function|func)\b/y.test(text.slice(i, i + 9)) && !/[\w$.]/.test(text[i - 1] || "")) {
10537
+ const m = text.slice(i, i + 120).match(/^(?:function\s*\*?\s*[\w$]*|func)\s*\(/);
10538
+ if (!m) continue;
10539
+ let p = i + m[0].length - 1, pd = 0;
10540
+ for (; p < text.length; p++) {
10541
+ if (text[p] === "(") pd++;
10542
+ else if (text[p] === ")" && --pd === 0) break;
10543
+ }
10544
+ let j = p + 1;
10545
+ const use = text.slice(j, j + 24).match(/^\s*use\s*\(/);
10546
+ if (use) {
10547
+ j += use[0].length - 1;
10548
+ for (let ud = 0; j < text.length; j++) {
10549
+ if (text[j] === "(") ud++;
10550
+ else if (text[j] === ")" && --ud === 0) {
10551
+ j++;
10552
+ break;
10553
+ }
10554
+ }
10555
+ }
10556
+ for (; j < text.length && j < p + 200; j++) {
10557
+ if (text[j] === "{") {
10558
+ if (/(?:interface|struct)\s*$/.test(text.slice(Math.max(0, j - 12), j))) {
10559
+ j = blockEnd(text, j);
10560
+ continue;
10561
+ }
10562
+ break;
10563
+ }
10564
+ if (text[j] === "\n" && /^\s*$/.test(text.slice(p + 1, j))) break;
10565
+ }
10566
+ const body = text[j] === "{" ? bodyAt(j, depth) : null;
10567
+ if (body) return body;
10568
+ continue;
10569
+ }
10570
+ if (c === "|" && depth >= 1 && /[(,]\s*(?:move\s+)?$/.test(text.slice(Math.max(0, i - 8), i))) {
10571
+ const m = text.slice(i, i + 200).match(/^\|[^|]*\|\s*(?:->\s*[\w<>&' ]+?\s*)?(?=\{)/);
10572
+ if (m) {
10573
+ const body = bodyAt(i + m[0].length, depth);
10574
+ if (body) return body;
10575
+ }
10576
+ }
10577
+ }
10578
+ return null;
10579
+ }
10580
+ var LAMBDA_PARAMS = /^\s*(?:\(?[\w$]+(?:\s*:\s*[\w<>?.]+)?(?:\s*,\s*[\w$]+(?:\s*:\s*[\w<>?.]+)?)*\)?|_)\s*->(?![^\n]*->)/;
10581
+ function armsOf(body) {
10582
+ const arms = [];
10583
+ let i = 0;
10584
+ while (i < body.length) {
10585
+ while (i < body.length && /[\s,;]/.test(body[i])) i++;
10586
+ if (i >= body.length) break;
10587
+ const at = i;
10588
+ let depth = 0, arrow = -1, end = -1;
10589
+ for (; i < body.length; i++) {
10590
+ const c = body[i];
10591
+ if (c === '"' || c === "'" || c === "`") {
10592
+ i = skipQuoted(body, i);
10593
+ continue;
10594
+ }
10595
+ if (c === "(" || c === "[" || c === "{") {
10596
+ depth++;
10597
+ continue;
10598
+ }
10599
+ if (c === ")" || c === "]" || c === "}") {
10600
+ depth--;
10601
+ if (depth === 0 && c === "}" && arrow >= 0 && /^\{/.test(body.slice(arrow + 2).trimStart())) {
10602
+ i++;
10603
+ end = i;
10604
+ break;
10605
+ }
10606
+ continue;
10607
+ }
10608
+ if (depth !== 0) continue;
10609
+ if (arrow < 0 && (c === "=" || c === "-") && body[i + 1] === ">") {
10610
+ arrow = i;
10611
+ i++;
10612
+ continue;
10613
+ }
10614
+ if (arrow >= 0 && (c === "," || c === ";")) {
10615
+ end = i;
10616
+ break;
10617
+ }
10618
+ if (arrow >= 0 && c === "\n") {
10619
+ const before = body.slice(arrow + 2, i).trim();
10620
+ let j = i + 1;
10621
+ while (j < body.length && /\s/.test(body[j])) j++;
10622
+ const after = body.slice(j, j + 12);
10623
+ if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}+\-*/%&|^=<>?:,]/.test(after) && !/^else\b(?!\s*->)/.test(after)) {
10624
+ end = i;
10625
+ break;
10626
+ }
10627
+ }
10628
+ }
10629
+ if (end < 0) end = i;
10630
+ if (arrow < 0) return null;
10631
+ const pattern = body.slice(at, arrow).trim();
10632
+ let bodyAt = arrow + 2;
10633
+ while (bodyAt < end && /\s/.test(body[bodyAt])) bodyAt++;
10634
+ if (!pattern) return null;
10635
+ arms.push({ pattern, at, end, bodyAt, body: body.slice(bodyAt, end).trim() });
10636
+ i = end + 1;
10637
+ }
10638
+ return arms.length ? arms : null;
10639
+ }
10640
+ var ARMS_HEAD = /(?:^|=\s*|return\s+)(?:[\w.]+\s+(?=switch))?(?:match\b\s*[^{\s][^{]*|when\s*(?:\([^{]*\))?|switch)\s*\{\s*$/;
9733
10641
  function braceStatements(stmts, split = null) {
9734
10642
  return stmts.map((s) => {
9735
10643
  const text = s.text;
9736
- const open = text.indexOf("{");
10644
+ const head0 = headLine(text);
10645
+ const lit2 = BLOCK_HEAD.test(head0) && !/^func\s*\(/.test(head0) ? null : fnLiteral(text);
10646
+ let open = lit2?.open ?? text.indexOf("{");
9737
10647
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
9738
10648
  const read = (o, e) => {
9739
- const body = e > o ? text.slice(o + 1, e) : "";
9740
- const base = s.start != null ? s.start + o + 1 : null;
10649
+ let from = o + 1;
10650
+ const params = text.slice(from, e).match(LAMBDA_PARAMS);
10651
+ if (params && !ARMS_HEAD.test(head0)) from += params[0].length;
10652
+ const body = e > from ? text.slice(from, e) : "";
10653
+ const base = s.start != null ? s.start + from : null;
9741
10654
  if (!body || !split) return [];
9742
- const kids2 = split(body, lineAtPos(o + 1)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
10655
+ const kids2 = split(body, lineAtPos(from)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
9743
10656
  return braceStatements(kids2, split);
9744
10657
  };
10658
+ const readArms = (o, e) => {
10659
+ const body = e > o ? text.slice(o + 1, e) : "";
10660
+ const arms = body ? armsOf(body) : null;
10661
+ if (!arms || !split) return null;
10662
+ return arms.map((a) => {
10663
+ const at = o + 1 + a.at, bodyAt = o + 1 + a.bodyAt, end = o + 1 + a.end;
10664
+ const pos = (p) => s.start != null ? { start: s.start + p } : {};
10665
+ let kids2 = [];
10666
+ if (a.body.startsWith("{")) kids2 = read(bodyAt, blockEnd(text, bodyAt));
10667
+ else if (a.body) kids2 = braceStatements([{ text: a.body.replace(/,$/, ""), line: lineAtPos(bodyAt), endLine: lineAtPos(Math.max(bodyAt, end - 1)), ...s.start != null ? { start: s.start + bodyAt, end: s.start + bodyAt + a.body.replace(/,$/, "").length } : {} }], split);
10668
+ return { text: text.slice(at, end).trim(), arm: a.pattern, line: lineAtPos(at), endLine: lineAtPos(Math.max(at, end - 1)), ...pos(at), ...s.start != null ? { end: s.start + end } : {}, inner: kids2.length, children: kids2 };
10669
+ });
10670
+ };
9745
10671
  let children = [], inner = 0;
9746
10672
  const clauses = [];
10673
+ if (lit2?.expr) {
10674
+ const [f, t] = lit2.expr;
10675
+ const raw = text.slice(f, t);
10676
+ const lead = raw.length - raw.trimStart().length;
10677
+ const expr = raw.trim();
10678
+ if (expr) children = braceStatements([{ text: expr, line: lineAtPos(f + lead), endLine: lineAtPos(f + lead + expr.length - 1), ...s.start != null ? { start: s.start + f + lead, end: s.start + f + lead + expr.length } : {} }], split);
10679
+ inner = children.length;
10680
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, fn: { depth: lit2.depth, expr: true, after: text.slice(t) } };
10681
+ }
9747
10682
  if (open >= 0) {
9748
10683
  const end = blockEnd(text, open);
10684
+ if (!lit2 && ARMS_HEAD.test(head0)) {
10685
+ const arms = readArms(open, end);
10686
+ if (arms) return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner: arms.length, children: arms, arms: true };
10687
+ }
9749
10688
  const body = end > open ? text.slice(open + 1, end) : "";
9750
10689
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
9751
10690
  children = read(open, end);
@@ -9764,7 +10703,7 @@ function braceStatements(stmts, split = null) {
9764
10703
  pos = e + 1;
9765
10704
  }
9766
10705
  }
9767
- return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {} };
10706
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {}, ...lit2 ? { fn: { depth: lit2.depth, after: text.slice(lit2.close + 1) } } : {} };
9768
10707
  });
9769
10708
  }
9770
10709
  function indentStatements(body, { depthKey = "indent" } = {}) {
@@ -9808,11 +10747,12 @@ function indentStatements(body, { depthKey = "indent" } = {}) {
9808
10747
 
9809
10748
  // src/read.mjs
9810
10749
  var READ_SCHEMA = "thunder-reading-v1";
9811
- var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby"];
9812
- var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
10750
+ var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby", "sql"];
10751
+ var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "synchronized", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
9813
10752
  function detectLanguage(source, file = "") {
9814
10753
  if (file) return languageForFile(file);
9815
10754
  const s = String(source);
10755
+ if (/^\s*(?:--[^\n]*\n\s*)*(?:CREATE|ALTER|INSERT\s+INTO|SELECT|WITH)\b/i.test(s) && /\b(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:TABLE|VIEW|FUNCTION|PROCEDURE|TRIGGER|TYPE|INDEX)|SELECT\b[\s\S]*\bFROM)\b/i.test(s)) return "sql";
9816
10756
  if (/^\s*<\?php\b/.test(s) || /\bfunction\s+\w+\s*\([^)]*\$\w+/.test(s)) return "php";
9817
10757
  if (/\bfun\s+(<[^>]*>\s*)?[\w.]*\w+\s*\(/.test(s)) return "kotlin";
9818
10758
  if (/^\s*def\s+[\w.?!]+(\s*\(.*\))?\s*$/m.test(s) && /^\s*end\s*$/m.test(s)) return "ruby";
@@ -10362,7 +11302,7 @@ function kotlinTerminate(body) {
10362
11302
  else if (")]}".includes(c)) depth--;
10363
11303
  else if (c === "\n" && depth === 0) {
10364
11304
  const line = src.slice(src.lastIndexOf("\n", i - 1) + 1, i);
10365
- const next = src.slice(i + 1);
11305
+ const next = src.slice(i + 1, i + 400);
10366
11306
  if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
10367
11307
  out += src.slice(last, i) + ";";
10368
11308
  last = i;
@@ -10499,7 +11439,7 @@ function lex(text) {
10499
11439
  }
10500
11440
  return out;
10501
11441
  }
10502
- var unquote = (t) => t.slice(1, -1);
11442
+ var unquote2 = (t) => t.slice(1, -1);
10503
11443
  function toThunderCondition(text, inputs = []) {
10504
11444
  const toks = lex(text);
10505
11445
  if (!toks || !toks.length) return null;
@@ -10545,7 +11485,7 @@ function toThunderCondition(text, inputs = []) {
10545
11485
  }
10546
11486
  if (/^["']/.test(t)) {
10547
11487
  if (t[0] === '"' && /#\{|\$\{|\$[A-Za-z_]/.test(t)) return null;
10548
- out.push(JSON.stringify(unquote(t)));
11488
+ out.push(JSON.stringify(unquote2(t)));
10549
11489
  continue;
10550
11490
  }
10551
11491
  if (/^\d/.test(t)) {
@@ -10647,7 +11587,7 @@ function toThunderOutcome(text) {
10647
11587
  }
10648
11588
  var lastSeg2 = (s) => String(s).split(/\.|::/).pop();
10649
11589
  var firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
10650
- function splitTop(str2, delim) {
11590
+ function splitTop2(str2, delim) {
10651
11591
  const out = [];
10652
11592
  let depth = 0, cur = "";
10653
11593
  for (let i = 0; i < str2.length; i++) {
@@ -10692,7 +11632,7 @@ function terminatorEffect(stmt, language) {
10692
11632
  if (!(m = s.match(/^return\s+([\s\S]+)$/))) return null;
10693
11633
  const v = m[1].trim();
10694
11634
  if (language === "go") {
10695
- const parts = splitTop(v, ",").map((x) => x.trim());
11635
+ const parts = splitTop2(v, ",").map((x) => x.trim());
10696
11636
  const last = parts[parts.length - 1];
10697
11637
  if (last === "err" || /^fmt\.Errorf\([^)]*%w/.test(last)) return { kind: "passes-error" };
10698
11638
  if (m = last.match(/^(?:errors\.New|fmt\.Errorf)\(\s*"([^"]*)"/)) return { kind: "fails", name: "error", detail: m[1] };
@@ -10724,7 +11664,7 @@ function sayGuard(effect, condText) {
10724
11664
  }
10725
11665
  }
10726
11666
  function makeGuard(cond, branch, language, inputs, line) {
10727
- const stmts = splitTop(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
11667
+ const stmts = splitTop2(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
10728
11668
  if (stmts.length !== 1 || /\n\s*\S[\s\S]*\n/.test(stmts[0]) && !/^(throw|raise|return)/.test(stmts[0])) return null;
10729
11669
  const effect = terminatorEffect(stmts[0], language);
10730
11670
  if (!effect) return null;
@@ -10770,7 +11710,7 @@ function patternCondition(pattern, subject, inputs, language) {
10770
11710
  const v2 = toThunderOutcome(m[1]);
10771
11711
  return v2 ? `${subject} != ${/^[A-Za-z_]/.test(v2) && !/^(true|false)$/.test(v2) ? v2 : v2}` : null;
10772
11712
  }
10773
- const parts = splitTop(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
11713
+ const parts = splitTop2(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
10774
11714
  if (parts.length > 1) {
10775
11715
  const each = parts.map((x) => patternCondition(x, subject, inputs, language));
10776
11716
  return each.every(Boolean) ? each.map((c) => /\s(and|or)\s/.test(c) ? `(${c})` : c).join(" or ") : null;
@@ -10976,8 +11916,9 @@ function splitStatements(body, baseLine) {
10976
11916
  }
10977
11917
  i = close;
10978
11918
  if (depth === 0) {
10979
- const rest2 = src.slice(i + 1).match(/^\s*else\b/);
10980
- if (!rest2) {
11919
+ const next = src.slice(i + 1, i + 40);
11920
+ const goes = /^\s*else\b/.test(next) || /^do\b/.test(prefix) && /^\s*while\b/.test(next) || /^\(/.test(next) && /^(?:go\s+|defer\s+)?func\s*\(/.test(prefix);
11921
+ if (!goes) {
10981
11922
  i++;
10982
11923
  break;
10983
11924
  }
@@ -10991,6 +11932,10 @@ function splitStatements(body, baseLine) {
10991
11932
  let j = i + 1;
10992
11933
  while (j < src.length && (src[j] === " " || src[j] === " " || src[j] === "\n" || src[j] === "\r")) j++;
10993
11934
  const after = src.slice(j, j + 24);
11935
+ if (/^(?:case\b[^\n]*|default\s*):$/.test(before)) {
11936
+ i++;
11937
+ break;
11938
+ }
10994
11939
  if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) {
10995
11940
  i++;
10996
11941
  break;
@@ -11125,7 +12070,7 @@ function readBraceStatements(stmts, language, inputs) {
11125
12070
  continue;
11126
12071
  }
11127
12072
  if (language === "php" && (m = t.match(/^abort_(if|unless)\s*\(([\s\S]*)\)\s*;?$/))) {
11128
- const args = splitTop(m[2], ",").map((x) => x.trim());
12073
+ const args = splitTop2(m[2], ",").map((x) => x.trim());
11129
12074
  if (args.length >= 2 && /^\d{3}$/.test(args[1])) {
11130
12075
  const cond = m[1] === "if" ? args[0] : `!(${args[0]})`;
11131
12076
  const when = toThunderCondition(cond, inputs);
@@ -11413,8 +12358,8 @@ function findRubyFunctions(src) {
11413
12358
  var RB_PREDICATE_NOT_FIELD = /^(nil|empty|zero|blank|present|any|none|all|include|key|is_a|kind_of|respond_to|start_with|end_with|between|positive|negative|even|odd)$/;
11414
12359
  function rbExpr(text) {
11415
12360
  let bad = false;
11416
- const bare = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
11417
- if (/===/.test(bare) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare)) return null;
12361
+ const bare2 = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
12362
+ if (/===/.test(bare2) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare2.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare2)) return null;
11418
12363
  const out = mapCode(String(text), (code) => code.replace(/@(?=[A-Za-z_])/g, "").replace(/(^|[\s(,=!<>[])::?([A-Za-z_]\w*)\b(?!:)/g, (all, pre, name) => all.includes("::") ? all : `${pre}"${name}"`).replace(/\.(\w+)\?/g, (all, name) => {
11419
12364
  if (RB_PREDICATE_NOT_FIELD.test(name)) bad = true;
11420
12365
  return `.${name}`;
@@ -11714,9 +12659,10 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
11714
12659
  function readCode(source, { language, file = "" } = {}) {
11715
12660
  const src = String(source ?? "");
11716
12661
  if (src.length > 4e5) throw new Error("Source is larger than 400 KB. Read one file or module at a time.");
11717
- const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, "typescript").replace(/^js$/, "javascript").replace(/^py$/, "python").replace(/^(cs|c#)$/, "csharp").replace(/^rs$/, "rust").replace(/^golang$/, "go").replace(/^kts?$/, "kotlin").replace(/^rb$/, "ruby");
12662
+ const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, "typescript").replace(/^js$/, "javascript").replace(/^py$/, "python").replace(/^(cs|c#)$/, "csharp").replace(/^rs$/, "rust").replace(/^golang$/, "go").replace(/^kts?$/, "kotlin").replace(/^rb$/, "ruby").replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, "sql");
11718
12663
  if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(", ")}. Got "${lang}".`);
11719
12664
  READING_RUST = lang === "rust";
12665
+ if (lang === "sql") return sqlReading(src);
11720
12666
  const code = lang === "php" ? normalizePhp(src) : src;
11721
12667
  const items = [];
11722
12668
  const srcLines = src.split("\n");
@@ -11815,6 +12761,22 @@ function searchReading(reading, { query = "", kinds = [], status = [] } = {}) {
11815
12761
  return terms.every((t) => hay.includes(t));
11816
12762
  });
11817
12763
  }
12764
+ function sqlReading(src) {
12765
+ const items = sqlItems(src);
12766
+ for (const it of items) it.completeness = completenessOf(it);
12767
+ const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
12768
+ return {
12769
+ schema: READ_SCHEMA,
12770
+ language: "sql",
12771
+ detected: false,
12772
+ items,
12773
+ counts,
12774
+ limitations: [
12775
+ "Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.",
12776
+ "Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps."
12777
+ ]
12778
+ };
12779
+ }
11818
12780
 
11819
12781
  // src/read-repo.mjs
11820
12782
  var READ_REPO_SCHEMA = "thunder-repo-reading-v1";
@@ -11830,7 +12792,8 @@ var EXT_LANG = [
11830
12792
  [/\.java$/i, "java"],
11831
12793
  [/\.kts?$/i, "kotlin"],
11832
12794
  [/\.php$/i, "php"],
11833
- [/\.rb$/i, "ruby"]
12795
+ [/\.rb$/i, "ruby"],
12796
+ [/\.sql$/i, "sql"]
11834
12797
  ];
11835
12798
  var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
11836
12799
  "node_modules",
@@ -11961,6 +12924,10 @@ function groupByFile(items) {
11961
12924
  }
11962
12925
  return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
11963
12926
  }
12927
+ function readingOf(f, language = readableLanguage(f.path)) {
12928
+ if (f.readError) throw new Error(f.readError);
12929
+ return f.reading ?? readCode(f.source, { language, file: f.path });
12930
+ }
11964
12931
 
11965
12932
  // src/promote.mjs
11966
12933
  var PROMOTE_SCHEMA = "thunder-promotion-v1";
@@ -12396,11 +13363,11 @@ function compileHumanContract(source) {
12396
13363
  }
12397
13364
  return out.join("\n") + "\n";
12398
13365
  }
12399
- var words3 = (s) => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, " ");
13366
+ var words4 = (s) => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, " ");
12400
13367
  var operators = { ">=": "is at least", "<=": "is at most", ">": "is greater than", "<": "is less than", "==": "equals", "=": "equals", "!=": "does not equal", "&&": "and", "||": "or", "!": "not" };
12401
13368
  function readCondition(expression) {
12402
13369
  try {
12403
- return tokenize(expression).map((t) => t.t === "str" ? JSON.stringify(t.v) : t.t === "id" ? words3(t.v) : operators[t.v] ?? String(t.v)).join(" ");
13370
+ return tokenize(expression).map((t) => t.t === "str" ? JSON.stringify(t.v) : t.t === "id" ? words4(t.v) : operators[t.v] ?? String(t.v)).join(" ");
12404
13371
  } catch {
12405
13372
  return expression;
12406
13373
  }
@@ -12810,7 +13777,7 @@ var GUARD_SCHEMA = "intent-guard-v1";
12810
13777
  var SECRET_TYPES3 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jwt", "token", "apikey", "api_key", "privatekey", "private_key", "credential", "cvv"]);
12811
13778
  var SENSITIVE_NAME = /^(.*[._-])?(pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card(number)?|cvc)([._-].*)?$/i;
12812
13779
  var DENY_RE = /^(deny|denied|block|blocked|refuse|refused|reject|rejected|forbid|forbidden|escalate|escalated|review|needsreview|no)$/i;
12813
- function buildGuard(ast, { denyResults, mask = "[redacted]" } = {}) {
13780
+ function buildGuard(ast, { denyResults, mask: mask2 = "[redacted]" } = {}) {
12814
13781
  const secretFields = /* @__PURE__ */ new Set();
12815
13782
  const consider = (f) => {
12816
13783
  if (!f || !f.name) return;
@@ -12837,7 +13804,7 @@ function buildGuard(ast, { denyResults, mask = "[redacted]" } = {}) {
12837
13804
  if (seen.has(value)) return value;
12838
13805
  seen.add(value);
12839
13806
  const out = {};
12840
- for (const [k, v] of Object.entries(value)) out[k] = isSecretKey(k) ? mask : redact(v, seen, depth + 1);
13807
+ for (const [k, v] of Object.entries(value)) out[k] = isSecretKey(k) ? mask2 : redact(v, seen, depth + 1);
12841
13808
  return out;
12842
13809
  }
12843
13810
  return value;
@@ -13542,7 +14509,7 @@ var LANGUAGES = {
13542
14509
  kotlin: { name: "Kotlin", status: "available", action: "Spring annotations", decision: "a fun with when or if returning fixed answers", doc: "/** KDoc */", "data-shape": "data class, enum class (planned)" },
13543
14510
  php: { name: "PHP", status: "available", action: "#[Route] (Symfony)", decision: "a function that returns fixed answers", doc: "/** PHPDoc */", "data-shape": "class, enum (planned)" },
13544
14511
  ruby: { name: "Ruby", status: "available", action: "Sinatra get/post blocks (Rails routes.rb planned)", decision: "a def that returns fixed answers", doc: "# comment above the def", "data-shape": "class, Struct (planned)" },
13545
- sql: { name: "SQL", status: "planned", action: "(none: SQL is reached through the app)", decision: "CHECK constraints, CASE expressions, IF in procedures", doc: "-- comment above, COMMENT ON", "data-shape": "CREATE TABLE / VIEW", event: "CREATE TRIGGER", steps: "SELECT / INSERT / UPDATE / DELETE: which data, filtered by which conditions, changed how" }
14512
+ sql: { name: "SQL", status: "available", action: "(none: SQL is reached through the app)", decision: "CHECK and UNIQUE constraints; IF in functions and procedures", doc: "-- comment above, COMMENT ON", "data-shape": "CREATE TABLE / VIEW", event: "CREATE TRIGGER", steps: "SELECT / INSERT / UPDATE / DELETE: which data, filtered by which conditions, changed how" }
13546
14513
  };
13547
14514
  var RULES = [
13548
14515
  "Show the picture first, Thunder Text second, and the original code one click away.",
@@ -13554,7 +14521,7 @@ var RULES = [
13554
14521
  "Say the action that is really possible: Propose rule change until a change is written back and checked; never Update code.",
13555
14522
  "Use the reader's words: plain names, no syntax. A step that would only restate the code shows the code instead."
13556
14523
  ];
13557
- var words4 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
14524
+ var words5 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
13558
14525
  function visualFor(item2) {
13559
14526
  if (!item2 || typeof item2 !== "object") throw new Error("visualFor needs a reader item.");
13560
14527
  const base = { provenance: item2.provenance === "confirmed" ? "confirmed" : "from-code", ...item2.doc ? { doc: { text: item2.doc, provenance: "authors-note" } } : {} };
@@ -13563,11 +14530,11 @@ function visualFor(item2) {
13563
14530
  const badge = item2.route ? { kind: "route", text: `${item2.route.method} ${item2.route.path}`.trim() } : void 0;
13564
14531
  if (item2.kind === "decision") {
13565
14532
  const card = safePlain(item2);
13566
- return { element: "decision", shape: "card", line: item2.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words4(item2.name)} decides`, ...badge ? { badge } : {}, ...item2.status === "partial" ? { note: "Partly read" } : {}, ...base };
14533
+ return { element: "decision", shape: "card", line: item2.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words5(item2.name)} decides`, ...badge ? { badge } : {}, ...item2.status === "partial" ? { note: "Partly read" } : {}, ...base };
13567
14534
  }
13568
14535
  const readable = (item2.stepsReadable ?? 0) >= 0.5 && item2.steps?.length;
13569
- if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words4(item2.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
13570
- return { element: item2.route ? "action" : "function", shape: "steps-card", line: "solid", title: item2.route ? `When someone calls ${badge.text}` : `What ${words4(item2.name)} does`, ...badge ? { badge } : {}, ...base };
14536
+ if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words5(item2.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
14537
+ return { element: item2.route ? "action" : "function", shape: "steps-card", line: "solid", title: item2.route ? `When someone calls ${badge.text}` : `What ${words5(item2.name)} does`, ...badge ? { badge } : {}, ...base };
13571
14538
  }
13572
14539
  function visualForStep(step) {
13573
14540
  const key = step?.restates ? "restates" : STEP_MARKS[step?.kind] ? step.kind : "other";
@@ -13594,7 +14561,7 @@ function thunderText(item2) {
13594
14561
  }
13595
14562
  const out = [v.title];
13596
14563
  if (item2.doc) out.push(` Author's note: "${item2.doc}"`);
13597
- if (item2.inputs?.length) out.push(` Takes ${item2.inputs.map((p) => words4(p.name)).join(", ")}`);
14564
+ if (item2.inputs?.length) out.push(` Takes ${item2.inputs.map((p) => words5(p.name)).join(", ")}`);
13598
14565
  const steps = item2.steps || [];
13599
14566
  const lines = (list, depth) => {
13600
14567
  for (const st of list) {
@@ -13663,8 +14630,7 @@ var THUNDER_VISUAL = { schema: VISUAL_SCHEMA, principle: PRINCIPLE, forms: FORMS
13663
14630
  var THUNDERIZE_SCHEMA = "thunderize-v1";
13664
14631
  var THUNDER_TEXT_EXT = ".thunder-text";
13665
14632
  var LANGUAGE_NAMES = { typescript: "TypeScript", javascript: "JavaScript", python: "Python", go: "Go", rust: "Rust", csharp: "C#", java: "Java", kotlin: "Kotlin", php: "PHP", ruby: "Ruby" };
13666
- function thunderizeFile(path, source, language = readableLanguage(path)) {
13667
- const reading = readCode(source, { language, file: path });
14633
+ function thunderizeFile(path, source, language = readableLanguage(path), reading = readCode(source, { language, file: path })) {
13668
14634
  const main = reading.items.filter((i) => i.kind === "decision" || i.kind === "function");
13669
14635
  const failures = [...new Set(reading.items.filter((i) => i.kind === "error").map((i) => i.name))];
13670
14636
  const counts = { actions: 0, rules: 0, functions: 0, notReadYet: 0, failures: failures.length };
@@ -13705,7 +14671,7 @@ function thunderizeFiles(files, { name = "app" } = {}) {
13705
14671
  continue;
13706
14672
  }
13707
14673
  try {
13708
- out.push(thunderizeFile(f.path, f.source, language));
14674
+ out.push(thunderizeFile(f.path, f.source, language, readingOf(f, language)));
13709
14675
  } catch (e) {
13710
14676
  skipped.push({ path: f.path, reason: `could not be read: ${e.message}` });
13711
14677
  }
@@ -13758,7 +14724,7 @@ function readAll(files) {
13758
14724
  if (!language || !f.source) continue;
13759
14725
  let reading;
13760
14726
  try {
13761
- reading = readCode(f.source, { language, file: f.path });
14727
+ reading = readingOf(f, language);
13762
14728
  } catch (e) {
13763
14729
  unreadable.push({ path: f.path, reason: e.message });
13764
14730
  continue;
@@ -14113,7 +15079,7 @@ function changedCases(before, after) {
14113
15079
  return { checked: a.all.length, changed, note: `Checked ${a.all.length} boundary input${a.all.length === 1 ? "" : "s"}; ${changed.length} now get${changed.length === 1 ? "s" : ""} a different answer. These are the values on each side of every limit, not every possible input.` };
14114
15080
  }
14115
15081
  var CMP_WORDS = { "<=": "at most", "<": "less than", ">=": "at least", ">": "more than", "==": "is", "!=": "is not" };
14116
- var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words5]) => ({ op, words: words5 }));
15082
+ var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words6]) => ({ op, words: words6 }));
14117
15083
  function ruleParts(when) {
14118
15084
  return tokenize(when).map((t) => {
14119
15085
  if (t.t === "num") return { kind: "number", value: t.v };