@skillstech/thunderlang 0.5.9 → 0.5.10

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