@skillstech/thunderlang 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/dist/core.cjs +2568 -462
  3. package/dist/index.cjs +7562 -5084
  4. package/dist/learn.cjs +1963 -315
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/mcp.mjs +23 -0
  33. package/src/meaning.mjs +45 -6
  34. package/src/model.d.mts +7 -3
  35. package/src/model.mjs +19 -6
  36. package/src/money.d.mts +18 -0
  37. package/src/money.mjs +124 -0
  38. package/src/plain-contract.mjs +18 -2
  39. package/src/read.d.mts +11 -0
  40. package/src/read.mjs +40 -6
  41. package/src/review-comment.d.mts +16 -0
  42. package/src/review-comment.mjs +145 -0
  43. package/src/say-less.mjs +1432 -0
  44. package/src/system.mjs +153 -44
  45. package/src/target-cs.mjs +39 -34
  46. package/src/target-elixir.mjs +40 -30
  47. package/src/target-go.mjs +41 -36
  48. package/src/target-java.mjs +34 -27
  49. package/src/target-kotlin.mjs +43 -35
  50. package/src/target-py.mjs +57 -55
  51. package/src/target-result.d.mts +48 -0
  52. package/src/target-result.mjs +112 -0
  53. package/src/target-rust.mjs +42 -38
  54. package/src/target-scala.mjs +45 -35
  55. package/src/target-ts.mjs +37 -45
  56. package/src/target-types.mjs +41 -5
  57. package/src/target-util.mjs +55 -2
  58. package/src/trace-cli.mjs +58 -0
  59. package/src/trace-fs.mjs +76 -0
  60. package/src/trace.mjs +261 -0
  61. package/src/translate.d.mts +3 -0
  62. package/src/translate.mjs +62 -32
  63. package/src/why-cli.mjs +31 -0
  64. package/src/why.d.mts +28 -0
  65. package/src/why.mjs +532 -0
  66. package/src/write-steps.mjs +22 -5
package/dist/learn.cjs CHANGED
@@ -775,6 +775,10 @@ var Parser = class {
775
775
  this.next();
776
776
  return { kind: "spread", value: this.expr(15), form: "&" };
777
777
  }
778
+ if ((t.v === "*" || t.v === "&") && (this.lang === "c" || this.lang === "cpp")) {
779
+ this.next();
780
+ return { kind: "unary", op: t.v, value: this.expr(17) };
781
+ }
778
782
  if ((t.v === "*" || t.v === "&" || t.v === "<-") && (fam === "go" || fam === "rs")) {
779
783
  this.next();
780
784
  if (t.v === "&" && fam === "rs" && this.isId("mut")) {
@@ -1136,6 +1140,13 @@ var Parser = class {
1136
1140
  node = { kind: "member", object: node, property: p.v };
1137
1141
  continue;
1138
1142
  }
1143
+ if (t.v === "->" && (lang === "c" || lang === "cpp")) {
1144
+ this.next();
1145
+ const p = this.next();
1146
+ if (p.t !== "id") fail("expected a name after ->");
1147
+ node = { kind: "member", object: node, property: p.v, arrow: true };
1148
+ continue;
1149
+ }
1139
1150
  if (t.v === "&." && fam === "rb") {
1140
1151
  this.next();
1141
1152
  const pn = this.next();
@@ -1192,7 +1203,7 @@ var Parser = class {
1192
1203
  node = { kind: "unary", op: t.v, value: node, postfix: true };
1193
1204
  continue;
1194
1205
  }
1195
- if (t.v === "<" && (lang === "typescript" || lang === "csharp" || lang === "java" || lang === "kotlin") && !t.sp && this.looksLikeTypeArgs()) {
1206
+ if (t.v === "<" && (lang === "typescript" || lang === "csharp" || lang === "java" || lang === "kotlin" || lang === "cpp") && !t.sp && this.looksLikeTypeArgs()) {
1196
1207
  node = { ...node, typeArgs: this.typeArgs() };
1197
1208
  continue;
1198
1209
  }
@@ -1256,7 +1267,7 @@ var Parser = class {
1256
1267
  const nx = this.peek(o + 1);
1257
1268
  return nx.t === "op" && (nx.v === "(" || nx.v === "{" && this.lang === "csharp");
1258
1269
  }
1259
- } else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v)) return false;
1270
+ } else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v) && !(this.lang === "cpp" && /^(?:::|\*|&&)$/.test(t.v))) return false;
1260
1271
  } else if (t.t !== "id" && t.t !== "str" && t.t !== "num") return false;
1261
1272
  }
1262
1273
  return false;
@@ -1353,6 +1364,10 @@ var Parser = class {
1353
1364
  return { kind: "object", entries, form: "hash", bare: true };
1354
1365
  }
1355
1366
  paren() {
1367
+ if (this.lang === "c" || this.lang === "cpp") {
1368
+ const c = this.cCast();
1369
+ if (c) return c;
1370
+ }
1356
1371
  if (this.fam === "c" && (isJs(this.lang) || this.lang === "csharp" || this.lang === "java")) {
1357
1372
  if (isJs(this.lang) && /^\(\s*</.test(this.L.src.slice(this.peek().s, this.peek().s + 400))) return this.plainParen();
1358
1373
  const k0 = this.k;
@@ -1365,6 +1380,22 @@ var Parser = class {
1365
1380
  }
1366
1381
  return this.plainParen();
1367
1382
  }
1383
+ cCast() {
1384
+ const src = this.L.src, open = this.peek().s;
1385
+ const close = src.indexOf(")", open);
1386
+ if (close < 0) return null;
1387
+ const inner = src.slice(open + 1, close);
1388
+ const m = /^\s*((?:(?:const|volatile|struct|enum|union|unsigned|signed|long|short)\s+)*)([A-Za-z_][\w:]*)(\s*<[^()]*>)?((?:\s*(?:const\s*)?[*&])*)\s*$/.exec(inner);
1389
+ if (!m) return null;
1390
+ const clearlyType = /\*|&/.test(m[4]) || !!m[1] || /^(?:int|char|long|short|float|double|void|bool|size_t|ssize_t|unsigned|signed|u?int\d+_t|uintptr_t|intptr_t|ptrdiff_t|time_t|off_t|wchar_t|char\d+_t|uint|uchar|BOOL|DWORD|HANDLE)$/.test(m[2]) || /_t$/.test(m[2]);
1391
+ if (!clearlyType) return null;
1392
+ const after = src.slice(close + 1).trimStart();
1393
+ if (!/^[A-Za-z_\d("'*&!~-]/.test(after)) return null;
1394
+ while (this.peek().t !== "eof" && this.peek().s < close) this.next();
1395
+ if (!this.isOp(")")) return null;
1396
+ this.next();
1397
+ return { kind: "cast", type: inner.trim(), value: this.expr(16), form: "c" };
1398
+ }
1368
1399
  arrowOrParen() {
1369
1400
  let depth = 0, o = 0;
1370
1401
  for (; ; o++) {
@@ -2351,6 +2382,12 @@ function statement(p) {
2351
2382
  p.next();
2352
2383
  return p.peek().t === "eof" ? { kind: "case", default: true } : { kind: "case", default: true, inline: true };
2353
2384
  }
2385
+ if (v === "try" && lang === "swift" && !p.isOp("{", 1)) {
2386
+ p.next();
2387
+ if (p.isOp("?") || p.isOp("!")) p.next();
2388
+ if (p.isId("await")) p.next();
2389
+ return statement(p);
2390
+ }
2354
2391
  if (v === "try" || v === "begin") {
2355
2392
  p.next();
2356
2393
  return { kind: "try" };
@@ -2429,6 +2466,7 @@ function statement(p) {
2429
2466
  return endStatement(p, { kind: "pass" });
2430
2467
  }
2431
2468
  if (v === "def" || v === "function" && p.peek(1).t === "id" || v === "func" && p.peek(1).t === "id" || v === "fn" && fam === "rs" || v === "fun" && lang === "kotlin" || v === "async" && isJs(lang) && p.isId("function", 1) && p.peek(2).t === "id") return functionHeader(p);
2469
+ if ((lang === "c" || lang === "cpp") && /^(?:const|static|struct|enum|union|constexpr|unsigned|signed|long|short|register|extern|volatile|inline|mutable)$/.test(v) && typedDeclAhead(p)) return typedDeclaration(p);
2432
2470
  if (/^(?:class|struct|interface|enum|impl|trait|object|record|module|type|namespace|import|export|from|package|use|using|lock|synchronized|unsafe|goto|static|public|private|protected|internal|abstract|override|virtual|final|readonly|global|nonlocal|extern|template|typedef|label)$/.test(v) && !(p.isOp("(", 1) && !/^(?:using|lock|synchronized)$/.test(v)) && !p.isOp(".", 1) && !(p.peek(1).t === "op" && (ASSIGN_OPS.has(p.peek(1).v) || p.peek(1).v === "," || p.peek(1).v === "["))) {
2433
2471
  if (v === "export" && (p.isId("const", 1) || p.isId("let", 1) || p.isId("function", 1))) {
2434
2472
  p.next();
@@ -2735,16 +2773,17 @@ function methodHeader(p) {
2735
2773
  }
2736
2774
  function typedDeclAhead(p, method = false) {
2737
2775
  let o = 0;
2738
- while (p.peek(o).t === "id" && /^(?:final|static|readonly|const|volatile|var|unsigned|signed)$/.test(p.peek(o).v) && p.peek(o + 1).t === "id") o++;
2776
+ const cLike = p.lang === "c" || p.lang === "cpp";
2777
+ while (p.peek(o).t === "id" && (/^(?:final|static|readonly|const|volatile|var|unsigned|signed)$/.test(p.peek(o).v) || cLike && /^(?:struct|enum|union|constexpr|long|short|register|extern|inline|mutable|thread_local)$/.test(p.peek(o).v)) && p.peek(o + 1).t === "id") o++;
2739
2778
  if (p.peek(o).t !== "id") return false;
2740
2779
  if (/^(?:return|throw|new|await|yield|case|goto|else|in|is|as|out|ref|params|this|base|super)$/.test(p.peek(o).v)) return false;
2741
2780
  o++;
2742
2781
  let depth = 0;
2743
2782
  for (let guard = 0; guard < 40; guard++) {
2744
2783
  const t = p.peek(o);
2745
- if (t.t === "op" && (t.v === "." || t.v === "?" || t.v === "*" || t.v === "&") && depth === 0) {
2784
+ if (t.t === "op" && (t.v === "." || t.v === "?" || t.v === "*" || t.v === "&" || cLike && (t.v === "::" || t.v === "&&")) && depth === 0) {
2746
2785
  o++;
2747
- if (p.peek(o).t === "id" && t.v === ".") o++;
2786
+ if (p.peek(o).t === "id" && (t.v === "." || t.v === "::")) o++;
2748
2787
  continue;
2749
2788
  }
2750
2789
  if (t.t === "op" && t.v === "<") {
@@ -2771,7 +2810,7 @@ function typedDeclAhead(p, method = false) {
2771
2810
  if (depth !== 0 || p.peek(o).t !== "id") return false;
2772
2811
  const after = p.peek(o + 1);
2773
2812
  if (method) return after.t === "op" && after.v === "(" ? o : false;
2774
- return after.t === "eof" || after.t === "op" && (after.v === "=" || after.v === ";" || after.v === ",") ? o : false;
2813
+ return after.t === "eof" || after.t === "op" && (after.v === "=" || after.v === ";" || after.v === "," || cLike && after.v === "[") ? o : false;
2775
2814
  }
2776
2815
  function typedDeclaration(p, inner = false) {
2777
2816
  const a = p.k;
@@ -2782,6 +2821,27 @@ function typedDeclaration(p, inner = false) {
2782
2821
  const items = [];
2783
2822
  for (; ; ) {
2784
2823
  const name = p.next().v;
2824
+ let dims = "";
2825
+ while ((p.lang === "c" || p.lang === "cpp") && p.isOp("[")) {
2826
+ const d0 = p.k;
2827
+ let depth = 0;
2828
+ do {
2829
+ const x = p.next();
2830
+ if (x.t === "eof") fail("array size");
2831
+ if (x.v === "[") depth++;
2832
+ else if (x.v === "]") depth--;
2833
+ } while (depth > 0);
2834
+ dims += p.text(d0, p.k);
2835
+ }
2836
+ if (dims) {
2837
+ if (p.isOp("=")) fail("array initializer");
2838
+ items.push({ kind: "declare", declare: "typed", type: `${type}${dims}`, names: [name] });
2839
+ if (p.isOp(",")) {
2840
+ p.next();
2841
+ continue;
2842
+ }
2843
+ break;
2844
+ }
2785
2845
  if (p.isOp("=")) {
2786
2846
  p.next();
2787
2847
  items.push({ kind: "assign", op: "=", declare: "typed", type, target: { kind: "name", name }, value: p.isOp("{") ? p.objectLit() : p.expr(0.6) });
@@ -2918,11 +2978,14 @@ function forHeader(p) {
2918
2978
  }
2919
2979
  let declare = null;
2920
2980
  if (p.peek().t === "id" && /^(?:const|let|var|val|final|auto)$/.test(p.peek().v) && (p.peek(1).t === "id" || p.isOp("[", 1) || p.isOp("{", 1) || p.isOp("(", 1))) declare = p.next().v;
2981
+ if (declare === "auto" && (lang === "cpp" || lang === "c")) while (p.isOp("&") || p.isOp("*") || p.isOp("&&")) p.next();
2982
+ if (declare === "const" && (lang === "cpp" || lang === "c")) declare = null;
2921
2983
  let type = null;
2922
2984
  if (p.peek().t === "id" && !declare) {
2923
2985
  const k0 = p.k;
2924
2986
  let o = 0;
2925
- while (p.peek(o).t === "id" || p.peek(o).t === "op" && /^(?:\.|<|>|\[|\]|,|\?)$/.test(p.peek(o).v)) {
2987
+ const cLike = lang === "c" || lang === "cpp";
2988
+ while (p.peek(o).t === "id" || p.peek(o).t === "op" && (/^(?:\.|<|>|\[|\]|,|\?)$/.test(p.peek(o).v) || cLike && /^(?:&|\*|&&|::)$/.test(p.peek(o).v))) {
2926
2989
  if (p.peek(o).t === "id" && /^(?:of|in)$/.test(p.peek(o).v)) break;
2927
2990
  if (p.isOp(":", o)) break;
2928
2991
  o++;
@@ -3290,6 +3353,9 @@ function detailParts(step) {
3290
3353
  return parts;
3291
3354
  }
3292
3355
 
3356
+ // src/form-words.mjs
3357
+ var FORM_WORDS = new Set("abort about above acc accepted access account accountsfor across act action actions active actives actor ad add added adding address adds admin administrator after afterall aftereach again against agrees ahead aks alias alignas alignof all allowed allows allsteps alone along alongside also alter always amazon amount an analytics and andor andorsteps annotateroutes annotation annotations announces another ansible answer answers any anything anywhere api app appending applies apply approves appservice are arg args argsat argsof argument arguments argv arith arithsays arithwords arm armexpr arms armsays armssubject around arr array arraylist arrives arrow arrowparam arrowre as ascall ascodewords asg aside asking asks asm assert assign assigned assignedto assignment assigns assignsteps assignwords associatedtype async asyncsession at atom attachclause attaches attr attribute attributes auth author auto available average await away aws az azure ba back background backs backticks backup bad badgateway badge badrequest balance balanced balancedreturnhead balancedtext balancer band bang bar bare base based baseline basync bb bbetween bc bdo be become becomes before beforeall beforebare beforeeach begin being belong below belse belseif bench berrors besides best between bfor bhandler bif big bigint bin binds bis bits blank blankcalls blanked blankpreprocessor blankstrings blet blk blob block blockat blocked blockend blocks bmethod bnot bo bodies bodiless body bodyrange bodystart book books bool boolean bor both bottom brace braces bracetextwithvalues bracewords bracket brackets bracketsclosed branch branches break brings bthen bucket build building builds built builtin bulk bus buse but bwhere by byname byte cache calculation call callable callargs callback called callee caller calling callnoun callof calls callverb can cancellationtoken cancelled cancels cannot cannotfail cap capital captures card carries carry case casebreaks caselabel cases cast cat catch catchall catches categories caught caused ccontainer cd cdecl cdeclaration cerr cfg ch chain chained change changed changes changing channel char character characters charat chars chart charts chead check checked checknotnull checkpoint checkpoints checks children choice choices choose chooser chooses choosing chr claim class classes classifystatement classifywords classname clause clausehead clausekids clauses clean cleancheader cleandoc cleans cleansteps clears cli click client clip clog close closed closein closeof closes closing closure closurehead closures cloud cloudformation cloudfront cloudwatch cls cluster cmd cmdlets cmds cmp cnormalize co code codeexpr codeof col collapsed collect collection colon column columns come comes command commandcalledas commands comment comments commit commits committed common compare compares comparison comparisons compile compiled completely completenessof compose compound computed cond condition conditions condjs condsaid condt condwords config configureawait confirm confirms conflict conn connected connection connects const consteval constexpr constinit constructor cont contain container containers content contents context continuation continuations continue continues control controller convenience conversion convert copies copy cosmos could count countable counted counting counts cout cpp crate create created createdataction createdatroute creates creturntype csays cstyle csuffixok csv ct ctor ctrl ctx ctype cur curl current cursor da daemon dashed data database date datetime db dbcc dbcontext dbl deallocate debounce debugging debugprint debugs decimal decision decisionof declaration declarations declare declared declares declspec decltype decodes decorator decorators def default defer defined definefunction defineproperty defines definething definition definitions deinit delete deletes delim delivery deliveryfee deny depends deploying deployment deploys deprecate deprecated deps depth desc descending describe detached detaches detail detailed details dev dfr di dialect dialects dict dictionary did didset dies differ different diouxxeeffggaacspn dir directory disconnects display displaylabel diusc divided divides dividing do doas doc docabove docker dockerfile docline docstring docstrings does dollar done double doubled down downloads dprintf dq drawn draws drop drops due dur dw dyn dynamic dynamodb ea each early easy eb ec echo ecr ecs ed edits ee eennbbxx effect eks elif eligible elixir else elseat elseif elsif elvis email empties empty enabled encodes end endline ends endswith enforces english ensure enters entries entry enum enumerable enumerated enums env environment eo err error errorf errors esc escapes eval even event eventhubs every everyday everything ex exact exactly example examples excel except excepted exchange exec execute executed exist existing exists exit exitcode expands expect explained explains explicit export exported exports expr express expression exprsteps extension extern extof extra exts fa fact fail failcode failed failnow fails failure faithfulness fakes fallback fallbackwords fallsthrough fallthrough false family far fastify fastifyreply fastifyrequest fatal fatalf fb fd fdescribe fee fetch ffddmmll field fields file fileprivate files fills filter final finally find findcfunctions findindex finds findswiftfunctions finish finished finishes first firstargs firstblock firststring firsttext fits fix fixed fixedof fixes flags flat flatmap float fmt fmtat fn fname fnidx fnline fnre fns fnsteps fnvalue folder folders follows foo fooled for forbidden force forceinline foreach forgets form format formats forms formula forward forwardref found fprintf fputs frame framework frees friend from front full fully fun func function functions fv gate gated gateway gc generic get getopts gets getter gg gi gim git give given gives givevalue giving glob global globals globby gm go goes going gone google got goto gradle grant grants graph grep group groupcases grouped grouping groupop groups grows gt guard had halt handle handler handlers handles handling hands happens has hash hashset hashtable hasown hastext have having head header headerdoc headers headline headof hello helm helper helptext here hh hides highest history hit hold holds home hour how hs htmlresponse http httpcontext httperrorof httpfail httprequest httpresponse httpservletrequest hubs iam id identity idioms idx if ifchain ifsteps ignores ignoring ilnow ilogger im image images impl implemented implicitreturn import imports in iname inat include included includes inclusive indentedjson index indexedwords indexof inferred init initialize initializer inl inline inlineelse inlinekid inner innere innernote inners input inputs inputsof insert insertcode inserted insertgetid insertname inside inspects installed installing installs instanceof int integer interesting interface internal internalservererror interrupt intest into intoalways invisible ioexception ip is isarray iscode iscodewords isdef isdevnull isglob isid isinstance islast isop isp isplumbing isset isspace istest isvar isw it item items iter iterable its itself iw java javascript jmp job jobs join joincontinued joined joinedtext joins joinword jscontext jsmorefunctions json jsonify jsonresponse jump jumps just kb keep keepat keeping keeps kept key keyboard keys keyvault keyword kid kids kill kind kinds kindwords know known knows knowsfrom koa kotlin kotlinexprend kotlinpattern kotlinterminate kotlinwhenarms kt kubectl kubernetes kv kw label labels lambda lang language languages lapply large larger largest last lastcmd lastexitcode lastindex lastindexof lastn lastop lastseg laststeps lastval lastwords late later latest lead leadingdoc least leave leaves left len length less let lets letter letters letting level lex lexsql lgl lhs lib library librarystep licence like limits line lineat linedoc linefinder lines link linked links list listargs listed lists listwords lit literal literalpath literals live ll load loads local location lock locks lodash log logger logging logic logical login logs long longer looking looks lookup loop loopofapply lower lowest ls lv machine macro macros made make makereader makes makestepper makestype managed management manager many map mapcode mapping mapply mark marked marks maskcode masked match matchall matchclose matched matches matching matchingclose matchparen math matters maven max may meaning measures media member memberranges memo memoize memory memset mentions merge merges merging message messageof messages method methodnotallowed methods methodsfrom microsoft mid middle middleware millisecond min minute missing mistake mistakes mjs mls model modify module modulemember modules monitor more most mounts move moved moves msg multiplies must mut mutable mutating my mysql na name nameat named names namespace namespaces nametok native nc nee needed needs neg negate negation negations nest nested nestedstep net network never new newer next nextfunction nextkind nextrequest nexttok nil nk nl nm no nocontent node nodecond nodes nodesteps noexcept noglob nohup none nonisolated nonnull noreturn norm normalizephp not note noteerrors notes notfound nothing notimplemented notnull noun nsg nslog null nullptr num number numbers numeric nx obj objclose object objectkeys objects objopen of off offsets og ok old older on once one oneline onevalue online only onshelf op open opened openers opens openssl operator operators ops opt optimizes option options opts or order ordered original orjsonresponse other others otherwise otherwiseline out outer outes output outputs outputwords outside over overdue override own owner pa package packages packs page paid pair paired panic para paragraph param parameter parameters params paramsclose paramsof paramsopen paramtext paren parent parentheses parentof parse parseexpr parseparams parsestatement part partly parts partsof pass passedto passes password past pat patch path pats pattern patterns pauses payload payloadtoolarge payloadwords payment paymentrequired pclose pending per perror person pester pg pgsql php phphashcomments pick picks pieces pings pipe pipeline pipelines pipelinesteps pl place placeholder plain plainenums plainname plaintextresponse plan playbook plumber plumbing plural pode pointer points pop popd popen port pos position positional positions possessivewords post postgresql power powershell powershellreading pre pred prefix prefixof prepared prepares preprocessor prev previous principal print printed printf printftext println prints prisma private procedures process processes prog program programs progress project prompt prop properties props protected protects protocol prototype ps pscommandpath psitem psscriptroot psthings ptr public publishes punc punct purges purrr push pushd put puts pv pw pwd py pybalanced pydocstring pyheader python qualifier query question questions queue quick quietly quote quoted quotedbody quotes raise raiserror raises random range ranges rangewords rare rasg rather raw rawt rawv rds re react read readable readableshare reader reading readinglanguage readkotlinif readonly reads ready real rearranges reason reasons receives recognize recognizes reconfigure record records redirect redirectof redirecttarget redirs redirwords redis redo redoes reduce references regexp register registers registration registry release releases reloads relying remainder remembering remembers remote remove removed removes renames renews repairs repeat repeated repeating repeats repl replace replaced replaces replays replof reply reports repositories repository representation req request requestidioms requests require required requirement requirenamespace requirenotnull requires res rescue resets reshapes resizes resource resources resp responds response responseentity responseof responsewriter rest restarts restate restated restates restore restores result results resumes ret retention retry return returned returns returnstep reverse revoke revokes rg rhs right ro role rollback rolling rolls rotates round roup route routefor router routeres routes routine row rows rq rr rreading rruu rscript rthings rtype ruby rule rules run running runs rust rv rw rwords safe safely said same sametype sapply save saved saves saving say sayarithmetic sayatom sayatomwords saycall saychain sayclibrary saycodecondition saycommand saycommon sayexactly saylibrarycall saylogic saynativeshape saynode saypython says sayvalue saywhether sayword scala scalar scale scales scaling scheduled scoped scopes scrambled scrambles screen script scriptparams scriptpath search searches second secret secrets sections security see seed seeing sees seg select selectcasesays selector self semi semicolons send sending sends sent sentence sentstep separate seq sequelize server serverrequest service servicebus services serviceunavailable servlet session set setclass setgeneric setmethod setopt setotherwise setpair setrefclass sets setting settings setup setvalidity several sh shape shapes share shares shebang shelf shell shellcheck shellreading shellwordsof shift short shortcut should show showing shown shows side sig sign signal signals signature signed signing signs sigs sil simple simplesays simplesaysinner single size sizeof skip skipbalanced skipparens skipped skips skipstring slash slice slots sm small smallest sn snprintf sns so some something sort sorts source sp space spaces span spanof special specify spelled spells splat splice split splitcomma splitlogic splits splitshift splitstatements splittop splittopargs spread sql sqlcondition sqllogicname sqltextwords sqs src ss ssh st stack stage standard start startat starting startline starts startswith startvalue state stateful statement statementexpr statements static status statusof stay stays std stderr step steps stepsfrom stepsin stepsofbody still stmts stmtstart stop stopf stopifnot stopped stops storage stored stores str strcasecmp strcmp strictmode string stringify strings stringtext strip stripe stripquotedtext striprubystrings striptail strlen strtext struct structs structure style sub subj subject subjectnames submits submodules subscript subscription subshell subtracts success such sudo suffix sui suite summary sums super supports suppress suppressmessages sv swaps swift swiftcondition swifthead swifttextwithvalues switch switches switchstep symbol synchronized syncs syntax system systems table tables tag tags tail taken takes tal target targetwords task teardown tee tells template templates term terminal terms ternary terraform test tests testthat testwords text textof texts than that the their theirs them then thenpart thensays thento thentoks there these they thing things this those thread throttle throw throws thunder tied time timeout timeoutexception times tnr to today together tok token tokens toks tokscode told tolowercase too tool tools toomanyrequests top toplevel toplevelindex topsteps tostderr total tothundercondition tothunderoutcome touppercase tr traces trail trailing transaction trap traps treats tree tried tries triggers trim triple true truncate try trycatch trystep ts tsql tuple turn turned turns tv tx txt ty type typealias typed typedef typeof types typescript typeset ui un unauthorized unavailable unblocks unchanged unchecked undefined under underneath understood undoes undone uninstalls union unique unknowncommand unless unlocks unmarks unmounts unpacks unprocessable unprocessableentity unprotects unq unquote unquoted unread unregisters unsafe unsaved unset unsetopt unshift unsigned unsupported until unused up update updates upgrades uploads upper url usage use usecallback used useeffectevent useevent usememo user users uses using usual uullff val valid vals value valuechoice valued valuelogic valueof valueofblock values valuewords vapor vapply var variable variables vars varwords vault vec vector ver verb verbstep version versions very via view views vim virtual visible visit vnet void volatile volume vt vtoks wait waitfor waiting waits walk walking wantfail warning warns was watches way weak web webrequest well wget wh what when whenever where whereof wherever whether which whichever while whitespace who whole wholecallargs wholevaluecall whose whosefrom widths willset with withcallinghandlers withinwindow without withoutsinglequoted word words wordsplain work worked workflow workloads works workspace would wrapped wraps write writes written wrong ws wur xdescribe xml xs xtest xx yaml yes yesno yet yield yields you za zero zeros zsh".split(" "));
3358
+
3293
3359
  // src/faithful.mjs
3294
3360
  var stripQuoted = (s) => String(s).replace(/(["'`])(?:\\.|(?!\1)[^\\\n])*\1/g, "Q");
3295
3361
  function skipQuote(s, i) {
@@ -3424,6 +3490,1462 @@ var asCodeWords = (code3, n = 120) => {
3424
3490
  };
3425
3491
  var isCodeWords = (said) => /^`[^]*`$/.test(String(said).trim());
3426
3492
 
3493
+ // src/say-less.mjs
3494
+ var NODES = /* @__PURE__ */ new WeakMap();
3495
+ function nodesOf2(tree) {
3496
+ if (!tree || typeof tree !== "object") return [];
3497
+ let out = NODES.get(tree);
3498
+ if (out) return out;
3499
+ out = [];
3500
+ const stack = [tree];
3501
+ while (stack.length) {
3502
+ const n = stack.pop();
3503
+ if (!n || typeof n !== "object") continue;
3504
+ if (Array.isArray(n)) {
3505
+ for (let i = n.length - 1; i >= 0; i--) stack.push(n[i]);
3506
+ continue;
3507
+ }
3508
+ if (n.kind) out.push(n);
3509
+ const keys = Object.keys(n);
3510
+ for (let i = keys.length - 1; i >= 0; i--) {
3511
+ const v = n[keys[i]];
3512
+ if (v && typeof v === "object") stack.push(v);
3513
+ }
3514
+ }
3515
+ NODES.set(tree, out);
3516
+ return out;
3517
+ }
3518
+ var WHY = {
3519
+ form: "the reader did not recognize this form",
3520
+ words: "the words could not be checked against the code",
3521
+ value: "a value in the words is not in the code",
3522
+ meaning: "the words leave out an operator or a negation in the code",
3523
+ ambiguous: "two names in the code read the same in words",
3524
+ unparsed: "the reader could not parse this statement",
3525
+ structure: "block structure uncertain",
3526
+ ending: "not a recognized return, throw, or exit",
3527
+ build: "one of several alternatives chosen when the code is compiled"
3528
+ };
3529
+ var DEBUG = typeof process !== "undefined" && !!process.env?.SAYLESS_DEBUG;
3530
+ var lastTag = null;
3531
+ var M = (tag) => {
3532
+ lastTag = tag;
3533
+ return WHY.meaning;
3534
+ };
3535
+ var WORDS_CACHE = /* @__PURE__ */ new Map();
3536
+ function splitWordsRaw(s) {
3537
+ return String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
3538
+ }
3539
+ var splitWords = (s) => {
3540
+ const t = String(s);
3541
+ if (t.length > 64) return splitWordsRaw(t);
3542
+ let w = WORDS_CACHE.get(t);
3543
+ if (!w) {
3544
+ if (WORDS_CACHE.size > 2e4) WORDS_CACHE.clear();
3545
+ w = splitWordsRaw(t);
3546
+ WORDS_CACHE.set(t, w);
3547
+ }
3548
+ return w;
3549
+ };
3550
+ var claimTextRaw = (says) => String(says).replace(/\((?:the loop )?only in builds where[^()]*(?:\([^()]*\)[^()]*)*\)/g, " ").replace(/`[^`]*`/g, " ").replace(/"(?:\\.|[^"\\])*"/g, " ").replace(/«[^»]*»/g, " ").replace(/(?<=\w)'s\b/g, "");
3551
+ var CLAIM_CACHE = /* @__PURE__ */ new Map();
3552
+ var CLAIM_WORDS = /* @__PURE__ */ new Map();
3553
+ var claimWords = (says) => {
3554
+ const k = String(says);
3555
+ let v = CLAIM_WORDS.get(k);
3556
+ if (v === void 0) {
3557
+ if (CLAIM_WORDS.size > 2e4) CLAIM_WORDS.clear();
3558
+ v = splitWordsRaw(claimText(k));
3559
+ CLAIM_WORDS.set(k, v);
3560
+ }
3561
+ return v;
3562
+ };
3563
+ var claimText = (says) => {
3564
+ const k = String(says);
3565
+ let v = CLAIM_CACHE.get(k);
3566
+ if (v === void 0) {
3567
+ if (CLAIM_CACHE.size > 2e4) CLAIM_CACHE.clear();
3568
+ v = claimTextRaw(k);
3569
+ CLAIM_CACHE.set(k, v);
3570
+ }
3571
+ return v;
3572
+ };
3573
+ var GLUE = new Set(`
3574
+ the a an of to from is are be was it its in on at by with as and or not no if otherwise when while each for one that this these those here then into than
3575
+ returns return gives giving back calls sets works out result value values stops fails steps step next whether checks check stores under adds defines how helper
3576
+ declares creates new keeps given repeats leaves loop skips chooses choice case cases tries handles any error errors goes wrong after takes starts yet counts nothing
3577
+ jumps part named below always end caught still caller passes again same made inside until something both all set empty more less least most true false null
3578
+ yes what time computed does do does makes function which order so also only there their them they has have itself own first last other else
3579
+ longest shortest instead
3580
+ `.trim().split(/\s+/));
3581
+ var IDIOM = [
3582
+ [/^(?:log|logs|message|messages|prints|warns|warning)$/, /print|log|echo|write|puts|warn|info|debug|error|trace|fmt\.|console|cat\b|say|message|Write-|out|stdout|stderr|emit|notice|fatal|panic|<<|Host|cli_|inform|signal|message|alert/i],
3583
+ [/^json$/, /json/i],
3584
+ [/^(?:matches|match|matching)$/, /%%|##|\$\{[^}]*[#%/]|\)\s*$|\[\[|!=|find|filter|first|where|select|any\b|all\b|some|every|grep|match|reject|detect|includes|contains|index|search|test|=~|-like|Where-Object|keep|take|drop|skip|case|when|switch|guard|is\b|in\b|\bfor\b|Regex|regex|re\.|\?|startswith|endswith|startsWith|endsWith|glob|fnmatch|==|-eq/i],
3585
+ [/^(?:entry|entries)$/, /get|\[|fetch|lookup|at\b|entry|Get|find|::|\$|\./i],
3586
+ [/^(?:table|lookup)$/, /map|dict|hash|table|\{|object|Object|list|@\{/i],
3587
+ [/^many$/, /\$\{#|len|length|count|size|\$#|nrow|NROW|Count|Length|Size|n\(\)|sizeof|nchar/i],
3588
+ [/^(?:copy|copies)$/, /\bcp\b|copy|clone|dup|Copy|Clone|\.\.\.|strcpy|memcpy|strdup|Copy-Item/i],
3589
+ [/^(?:removes|deletes|frees|unsets)$/, /\brm\b|remove|delete|del\b|unset|pop|splice|free|drop|Remove|Delete|clear|discard|erase|-=|\[\]|NULL/i],
3590
+ [/^(?:empties|zeros)$/, /=\s*(?:;|$|""|''|\(\)|\[\]|0\b)|clear|truncate|memset|fill|zero|reset|bzero/i],
3591
+ [/^(?:folder|folders|directory)$/, /^\s*\(\s*(?:\n|$)|cd\b|dir|folder|path|mkdir|pushd|Path|-d\b|Item|Location/i],
3592
+ [/^(?:illegal|exception)$/, /require|check|Illegal|assert|Exception|throw|raise/],
3593
+ [/^(?:valid)$/, /valid|check|assert|stopifnot|verify/i],
3594
+ [/^(?:parent)$/, /super|base\b|parent|Parent|Base|mkdir|\.\./i],
3595
+ [/^(?:pattern|patterns|regex)$/, /match|=~|-like|grep|case|regex|Regex|re\.|\*|glob|sed|awk|\/.*\/|~|\[\[|split|-split|-replace|gsub|sub\(/i],
3596
+ [/^(?:plus|minus|times|divided|multiplied|remainder|shifted)$/, /[-+*/%<>^&|~]|\btimes\b|range|repeat|\.\./],
3597
+ [/^(?:exists|exist)$/, /exist|Exist|-[edfLhrswx]\b|Test-Path|isfile|isdir|file\.|stat|access|has|contains|in\b|key/i],
3598
+ [/^(?:setting|settings|environment)$/, /kubectl|helm|apply|env|ENV|environ|getenv|Environment|config|setting|option|\$[A-Z_]{2,}|\bget\b|\bset\s+-[a-z]*u/i],
3599
+ [/^(?:second|third|fourth|fifth)$/, /\$[2-9]|\$\{[2-9]|\[[1-9]\]|second|third|nth|at\(|\.\.\.|args/i],
3600
+ [/^(?:alongside|background)$/, /await|go\b|async|&\s*$|spawn|thread|Task|later|Start-Job|launch|coroutine/i],
3601
+ [/^(?:passed|seconds|milliseconds|minutes|hours|timer)$/, /time\.|After|setTimeout|setInterval|sleep|delay|Timer|timeout|Duration|interval|schedule|every|after/i],
3602
+ [/^(?:uploads|upload|pushes)$/, /push|upload|put|send|publish/i],
3603
+ [/^(?:latest|newest|oldest)$/, /latest|tail|sort|max|last|head|newest|oldest|-1\b|describe/i],
3604
+ [/^(?:redirect|redirects)$/, /redirect|Redirect|location|Location|30[1278]/],
3605
+ [/^(?:database|insert|inserts)$/, /db|database|save|query|sql|select|insert|update|session|repo|commit|execute|Insert|Save|create|objects|models|prisma|knex|orm/i],
3606
+ [/^(?:forbidden|unauthorized|conflict|unprocessable|unavailable|gateway|teapot)$/, /[45]\d\d|status|abort|HTTP|Http|Forbidden|Unauthorized|Conflict/],
3607
+ [/^(?:sum|total|average|mean)$/, /sum|total|reduce|\+|mean|avg|average|Sum|Measure-Object|aggregate|summari/i],
3608
+ [/^(?:sorted|sorts|sort|highest|lowest)$/, /sort|order|Sort|Order|arrange|desc|asc/i],
3609
+ [/^(?:upper|lower|uppercase|lowercase)$/, /upper|lower|Upper|Lower|toupper|tolower|capitaliz|case/i],
3610
+ [/^(?:reversed|reverse)$/, /rev|Reverse|reverse/i]
3611
+ ];
3612
+ var FORM_NEGATIONS = /\bno [\w ]{1,40}? yet\b|\bwhen that has no value\b|\bwhen it has no value\b|\bif nothing is there yet\b|\bif it has no value yet\b|\ban error is not caught here\b|\bdid not leave\b|\bnot explained\b|\bnothing\b|\bwhen it is not set\b/g;
3613
+ function codeWordSet(code3) {
3614
+ const out = /* @__PURE__ */ new Set();
3615
+ for (const id of String(code3).match(/[A-Za-z0-9]+/g) || []) {
3616
+ for (const w of splitWords(id)) out.add(w);
3617
+ if (/[A-Z]{2}/.test(id)) {
3618
+ for (const w of id.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(" ")) if (w) out.add(w);
3619
+ }
3620
+ }
3621
+ if (/\b1\b/.test(code3)) out.add("one");
3622
+ if (/\b0\b/.test(code3)) out.add("zero");
3623
+ return out;
3624
+ }
3625
+ var IDIOM_OF = /* @__PURE__ */ new Map();
3626
+ function unsourcedWord(says, code3) {
3627
+ let have = null;
3628
+ const inCode = (w) => {
3629
+ have ??= codeWordSet(code3);
3630
+ return have.has(w) || have.has(w.replace(/(?:es|s|ed|d|ing)$/, "")) || have.has(`${w}s`) || have.has(w.replace(/ies$/, "y"));
3631
+ };
3632
+ for (const w of claimWords(says)) {
3633
+ if (/^\d+$/.test(w)) continue;
3634
+ let idiom = IDIOM_OF.get(w);
3635
+ if (idiom === void 0) {
3636
+ idiom = IDIOM.find(([re]) => re.test(w)) ?? null;
3637
+ IDIOM_OF.set(w, idiom);
3638
+ }
3639
+ if (idiom) {
3640
+ if (idiom[1].test(code3) || inCode(w)) continue;
3641
+ return w;
3642
+ }
3643
+ if (GLUE.has(w) || FORM_WORDS.has(w)) continue;
3644
+ if (/ing$/.test(w)) {
3645
+ const st = w.slice(0, -3);
3646
+ if ([`${st}s`, `${st}es`, `${st}e`, `${st.slice(0, -1)}s`].some((x) => FORM_WORDS.has(x))) continue;
3647
+ }
3648
+ if (inCode(w)) continue;
3649
+ return w;
3650
+ }
3651
+ return null;
3652
+ }
3653
+ var SIGIL_LANGS = /* @__PURE__ */ new Set(["php", "shell", "powershell", "ruby", "perl", "r", "sql"]);
3654
+ var currentLang = "";
3655
+ var LIBRARY_STEP = false;
3656
+ function ambiguousName(says, code3) {
3657
+ const sw = claimWords(says);
3658
+ if (new Set(sw).size === sw.length) return null;
3659
+ const byWords = /* @__PURE__ */ new Map();
3660
+ const inserted = [...String(code3).matchAll(/\$\{([^}]*)\}|#\{([^}]*)\}|\$\(([^)]*)\)|\$([A-Za-z_]\w*)/g)].map((m) => m[1] ?? m[2] ?? m[3] ?? m[4]).join(" ");
3661
+ for (const id of `${stripQuoted(code3)} ${inserted}`.match(/[A-Za-z_$@][\w$]*/g) || []) {
3662
+ const bare2 = SIGIL_LANGS.has(currentLang) ? id.replace(/^[$@]+/, "") : id;
3663
+ const w = splitWords(bare2).join(" ");
3664
+ if (!w) continue;
3665
+ if (!byWords.has(w)) byWords.set(w, /* @__PURE__ */ new Set());
3666
+ byWords.get(w).add(bare2);
3667
+ }
3668
+ const raw = String(says).replace(/`[^`]*`/g, " ");
3669
+ const said = ` ${splitWords(claimText(says.replace(/'s /g, " possx "))).join(" ")} `;
3670
+ for (const [w, spellings] of byWords) {
3671
+ if (spellings.size < 2) continue;
3672
+ let open = [...spellings].filter((x) => !(/[A-Z]/.test(x) && new RegExp(`(?<![\\w$])${x.replace(/[$]/g, "\\$&")}(?![\\w$])`).test(raw)));
3673
+ open = [...new Set(open.map((x) => x[0].toLowerCase() + x.slice(1)))];
3674
+ if (open.length < 2) continue;
3675
+ const all = said.split(` ${w} `).length - 1;
3676
+ const plain = all - (said.split(` possx ${w} `).length - 1);
3677
+ if (plain >= 2) return w;
3678
+ }
3679
+ return null;
3680
+ }
3681
+ function bracketsClosed(text2) {
3682
+ let d = 0;
3683
+ const t = String(text2).replace(/'[^'\s]{1,4}'|`[^`]*`/g, "Q");
3684
+ for (const ch of t) {
3685
+ if (ch === "(" || ch === "[" || ch === "{") d++;
3686
+ else if (ch === ")" || ch === "]" || ch === "}") {
3687
+ if (--d < 0) return false;
3688
+ }
3689
+ }
3690
+ return d === 0;
3691
+ }
3692
+ function inventedValue(says, code3) {
3693
+ const said = String(says).replace(/`[^`]*`/g, " ").replace(/\(\d+ steps? inside\)/g, "").replace(/\(\d+ lines?\)/g, "").replace(/\bor \d+ other values?\b/g, "").replace(/\b(?:a list of|a table of|and) \d+ (?:items?|more|entries|values|names|keys)\b/g, " ").replace(/\b\d+ more\b/g, " ");
3694
+ const text2 = String(code3);
3695
+ for (const num3 of said.replace(/"(?:\\.|[^"\\])*"/g, " ").match(/(?<![\w.«])-?\d+(?:\.\d+)?(?![\w.»])/g) || []) {
3696
+ const n = num3.replace(/^-/, "");
3697
+ if (!text2.includes(n) && !/^[01]$/.test(n) && !statusNamed(n, text2) && !text2.includes(`..<${Number(n) + 1}`) && !new RegExp(`\\.\\.<\\s*${Number(n) + 1}\\b`).test(text2)) return num3;
3698
+ }
3699
+ for (const q of String(says).replace(/^(?:If (?:not: )?|Repeats: |Fails with )?`[^]*`$/, "").match(/"(?:\\.|[^"\\])*"/g) || []) {
3700
+ if (!exactText(q.slice(1, -1), text2)) return q;
3701
+ }
3702
+ return null;
3703
+ }
3704
+ function textSkeleton(t, words10 = false, open = false) {
3705
+ const s = String(t);
3706
+ let out = "";
3707
+ for (let i = 0; i < s.length; i++) {
3708
+ const c = s[i], n = s[i + 1];
3709
+ if (words10 && c === "\xAB") {
3710
+ const e = s.indexOf("\xBB", i);
3711
+ if (e > i) {
3712
+ out += "";
3713
+ i = e;
3714
+ continue;
3715
+ }
3716
+ }
3717
+ if (open && c === "$" && n === "(") {
3718
+ out += "";
3719
+ i++;
3720
+ continue;
3721
+ }
3722
+ if (c === "$" && (n === "{" || n === "(") || c === "#" && n === "{" || c === "\\" && n === "(") {
3723
+ const open2 = n, close = open2 === "{" ? "}" : ")";
3724
+ let d = 0, j = i + 1;
3725
+ for (; j < s.length; j++) {
3726
+ if (s[j] === open2) d++;
3727
+ else if (s[j] === close && --d === 0) break;
3728
+ }
3729
+ out += "";
3730
+ i = j;
3731
+ continue;
3732
+ }
3733
+ if (c === "{" && /[\w$.}:]/.test(n ?? "")) {
3734
+ let d = 0, j = i;
3735
+ for (; j < s.length && j - i < 120; j++) {
3736
+ if (s[j] === "{") d++;
3737
+ else if (s[j] === "}" && --d === 0) break;
3738
+ }
3739
+ if (j < s.length && s[j] === "}") {
3740
+ out += "";
3741
+ i = j;
3742
+ continue;
3743
+ }
3744
+ }
3745
+ if (c === "$" && /[A-Za-z_]/.test(n ?? "")) {
3746
+ let j = i + 1;
3747
+ while (j < s.length && /\w/.test(s[j])) j++;
3748
+ out += "";
3749
+ i = j - 1;
3750
+ continue;
3751
+ }
3752
+ if (c === "$" && /[0-9*@#?!$-]/.test(n ?? "")) {
3753
+ out += "";
3754
+ i++;
3755
+ continue;
3756
+ }
3757
+ if (c === "%" && /[-+ #0-9.]*[sdifgxXoucpqvT]/.test(s.slice(i + 1, i + 6))) {
3758
+ const m = /^[-+ #0-9.]*[a-zA-Z]/.exec(s.slice(i + 1));
3759
+ out += "";
3760
+ i += m[0].length;
3761
+ continue;
3762
+ }
3763
+ if (c === "\\" && /["'`\\]/.test(n ?? "")) {
3764
+ out += n;
3765
+ i++;
3766
+ continue;
3767
+ }
3768
+ out += c;
3769
+ }
3770
+ return out.replace(/\s+/g, " ");
3771
+ }
3772
+ var SKELETON_CACHE = /* @__PURE__ */ new Map();
3773
+ var FRAG_RE = /* @__PURE__ */ new Map();
3774
+ function exactText(inner, code3) {
3775
+ return exactIn(inner, code3, false) || exactIn(inner, code3, true);
3776
+ }
3777
+ function exactIn(inner, code3, open) {
3778
+ if (!/«|…/.test(inner) && inner.length && [`'${inner}'`, `"${inner}"`, `\`${inner}\``].some((q) => String(code3).includes(q))) return true;
3779
+ if (!/«|…/.test(inner) && inner.trim().length) {
3780
+ const esc = inner.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3781
+ if (new RegExp(`(?:^|[\\s#%/:+=(\\-{"'])${esc}(?=$|[\\s}/)"';|])`).test(String(code3))) return true;
3782
+ }
3783
+ const cut = /…$/.test(inner);
3784
+ const w = textSkeleton(inner.replace(/…$/, ""), true);
3785
+ const key = `${open ? 1 : 0}${code3}`;
3786
+ let c = SKELETON_CACHE.get(key);
3787
+ if (c === void 0) {
3788
+ if (SKELETON_CACHE.size > 5e3) SKELETON_CACHE.clear();
3789
+ c = `${textSkeleton(code3, false, open)}`;
3790
+ SKELETON_CACHE.set(key, c);
3791
+ }
3792
+ const parts = w.split("");
3793
+ const B = "[\"'`\\s=(,;:\\[|]", E = "[\"'`\\s),;:\\]|]";
3794
+ for (let i = 0; i < parts.length; i++) {
3795
+ const f = parts[i].trim();
3796
+ if (!f) continue;
3797
+ const esc = f.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3798
+ const lead = i === 0 ? B : "[\"'`\\s,|]";
3799
+ const tail = i === parts.length - 1 ? cut ? "" : E : "[\"'`\\s,]";
3800
+ const src = `${lead}${esc}${tail ? `(?=${tail})` : ""}`;
3801
+ let re = FRAG_RE.get(src);
3802
+ if (!re) {
3803
+ if (FRAG_RE.size > 5e3) FRAG_RE.clear();
3804
+ re = new RegExp(src);
3805
+ FRAG_RE.set(src, re);
3806
+ }
3807
+ if (!re.test(c) && !(f.length > 12 && c.includes(f))) return false;
3808
+ }
3809
+ return true;
3810
+ }
3811
+ var STATUS_NAMES = { 400: "badrequest", 401: "unauthorized", 402: "paymentrequired", 403: "forbidden", 404: "notfound", 405: "methodnotallowed", 409: "conflict", 410: "gone", 413: "payloadtoolarge", 415: "unsupportedmediatype", 422: "unprocessable", 429: "toomanyrequests", 500: "internalservererror", 501: "notimplemented", 502: "badgateway", 503: "serviceunavailable" };
3812
+ var statusNamed = (n, text2) => !!STATUS_NAMES[n] && String(text2).toLowerCase().replace(/[^a-z]/g, "").includes(STATUS_NAMES[n]);
3813
+ var ORDER_WORDS = { ">": /\b(?:more|greater|longer|later|bigger|larger) than\b|\bafter\b/g, ">=": /\bat least\b/g, "<": /\b(?:less|fewer|shorter|earlier|smaller) than\b|\bbefore\b/g, "<=": /\bat most\b/g };
3814
+ function orderCounts(tree) {
3815
+ const c = { ">": 0, ">=": 0, "<": 0, "<=": 0 };
3816
+ for (const n of nodesOf2(tree)) {
3817
+ if (n.kind === "compare" && c[n.op] != null) c[n.op]++;
3818
+ else if (n.kind === "chain") {
3819
+ for (const op of n.ops) if (c[op] != null) c[op]++;
3820
+ }
3821
+ }
3822
+ return c;
3823
+ }
3824
+ function orderWords(said) {
3825
+ const c = {};
3826
+ for (const [op, re] of Object.entries(ORDER_WORDS)) c[op] = (said.match(re) || []).length;
3827
+ return c;
3828
+ }
3829
+ function orderingKept(tree, said) {
3830
+ const t = orderCounts(tree), w = orderWords(claimText(said));
3831
+ const total = (o) => o[">"] + o[">="] + o["<"] + o["<="];
3832
+ if (total(t) !== total(w)) return false;
3833
+ return t[">"] + t["<"] === w[">"] + w["<"] && t[">="] + t["<="] === w[">="] + w["<="];
3834
+ }
3835
+ var NEG_TOKEN = /^(?:not|no|non|never|cannot|nt)$/;
3836
+ var saidNegations = (said) => splitWords(claimText(said).replace(FORM_NEGATIONS, " ").replace(/n't\b/g, " nt")).filter((w) => NEG_TOKEN.test(w)).length;
3837
+ var NULL_NAME = /^(?:NULL|nullptr|nil|None|null|undefined|Nothing)$/;
3838
+ var isNullish = (x) => x && (x.kind === "literal" && x.type === "null" || x.kind === "name" && NULL_NAME.test(x.name));
3839
+ var isCmpCall = (x) => x?.kind === "call" && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(x.callee?.name ?? "");
3840
+ var isZero = (x) => x?.kind === "literal" && String(x.value) === "0";
3841
+ function treeNegations(tree, skipArgs = false) {
3842
+ let neg = 0;
3843
+ const names = [];
3844
+ const walk = (n) => {
3845
+ if (!n || typeof n !== "object") return;
3846
+ if (Array.isArray(n)) {
3847
+ n.forEach(walk);
3848
+ return;
3849
+ }
3850
+ if (n.kind === "not" && !isCmpCall(n.value)) neg++;
3851
+ else if (n.kind === "call" && /^(?:reject|reject!|delete_if|filterNot|filterNotNull|exclude|without|dropWhile|drop_while)$/.test(n.callee?.property ?? n.callee?.name ?? "") && n.args?.some((a) => a.kind === "lambda")) neg++;
3852
+ else if (n.kind === "compare" && /^(?:!=|!==|<>|is not|not in|!is|!in|-ne)$/.test(n.op) && !(isCmpCall(n.left) && isZero(n.right)) && !(n.op !== "!==" && [n.left, n.right].some(isNullish))) neg++;
3853
+ else if (n.kind === "if" && n.negate) neg++;
3854
+ if (n.kind === "name") names.push(n.name);
3855
+ else if (n.kind === "member") names.push(n.property);
3856
+ if (n.kind === "lambda") return;
3857
+ for (const k of Object.keys(n)) {
3858
+ if (skipArgs && n.kind === "call" && k === "args") continue;
3859
+ const v = n[k];
3860
+ if (v && typeof v === "object") walk(v);
3861
+ }
3862
+ };
3863
+ walk(tree);
3864
+ for (const x of names) for (const w of splitWords(x)) if (/^(?:not|no|non|never|cannot)$/.test(w)) neg++;
3865
+ return neg;
3866
+ }
3867
+ function newThing(v, says) {
3868
+ const m = / a new ([\w ]+?)(?: as [\w ]+)?(?:,|$)/.exec(says);
3869
+ if (!m) return false;
3870
+ let c = coreOf(v);
3871
+ if (c?.kind === "unary" && c.op === "&") c = coreOf(c.value);
3872
+ const type = c?.kind === "object" ? c.type : c?.kind === "call" ? c.callee.kind === "name" ? c.callee.name : c.callee.kind === "member" ? /^(?:new|New)$/.test(c.callee.property) ? c.callee.object.name ?? c.callee.object.property : c.callee.property : null : null;
3873
+ return !!type && sameWords(String(type).replace(/<.*$/, "").split(/::|\./).pop(), m[1]);
3874
+ }
3875
+ var ARITH = /* @__PURE__ */ new Set(["+", "-", "*", "/", "%", "**", "//", "<<", ">>", ">>>", "&", "|", "^", "&^"]);
3876
+ var arithCount = (tree) => {
3877
+ let n = 0;
3878
+ for (const x of nodesOf2(tree)) if (x.kind === "binary" && ARITH.has(x.op)) n++;
3879
+ return n;
3880
+ };
3881
+ var castCount = (tree) => {
3882
+ let n = 0;
3883
+ for (const x of nodesOf2(tree)) if (x.kind === "cast" && x.form !== "nonnull" && !(x.form === "c" && /\*\s*$/.test(String(x.type)))) n++;
3884
+ return n;
3885
+ };
3886
+ var SAID_AS = {
3887
+ process: / setting /,
3888
+ env: / setting | environment /,
3889
+ environ: / setting /,
3890
+ os: / setting /,
3891
+ getenv: / setting /,
3892
+ ENV: / setting /,
3893
+ headers: / header /,
3894
+ header: / header /,
3895
+ req: / header | request | parameter | query | body | cookie /,
3896
+ request: / header | request | parameter | query | body | cookie /,
3897
+ params: / parameter | request /,
3898
+ query: / query | parameter | request /,
3899
+ body: / body | request /,
3900
+ cookies: / cookie /,
3901
+ str: / text /,
3902
+ string: / text /,
3903
+ bytes: / text | bytes /,
3904
+ basestring: / text /,
3905
+ unicode: / text /,
3906
+ "string type": / text /,
3907
+ int: / number | whole /,
3908
+ float: / number /,
3909
+ number: / number /,
3910
+ numeric: / number /,
3911
+ integer: / number /,
3912
+ list: / list /,
3913
+ array: / list | array /,
3914
+ tuple: / list | tuple /,
3915
+ dict: / table | lookup | dictionary /,
3916
+ map: / table | lookup | map /,
3917
+ hash: / table | lookup | hash /,
3918
+ "to s": / text /,
3919
+ "to string": / text /,
3920
+ "to str": / text /,
3921
+ "to i": / number /,
3922
+ "to f": / number /,
3923
+ "to int": / number /,
3924
+ "to sym": / symbol /,
3925
+ "to a": / list /,
3926
+ "to h": / table | lookup /,
3927
+ dup: / copy /,
3928
+ clone: / copy /,
3929
+ copy: / copy /,
3930
+ deepcopy: / copy /,
3931
+ bool: / yes | true | false /,
3932
+ boolean: / yes | true | false /,
3933
+ null: / set | nothing | null | missing /,
3934
+ none: / set | nothing | none | missing /
3935
+ };
3936
+ function namesKept(tree, said) {
3937
+ const norm2 = (t) => t.replace(/ have /g, " has ").replace(/ are /g, " is ").replace(/ does /g, " ");
3938
+ const base2 = ` ${splitWords(claimText(said)).join(" ")} ${splitWords(said).join(" ")} `;
3939
+ const sw = norm2(`${base2} ${base2.replace(/ (?:not|no|does not|doesn t) /g, " ")} `);
3940
+ const has2 = (x) => {
3941
+ const w = splitWords(x).join(" ");
3942
+ if (!w || /^(?:self|this|it|super)$/.test(w) || sw.includes(` ${w} `) || sw.includes(` ${w.replace(/s$/, "")} `) || sw.includes(` ${w}s `)) return true;
3943
+ const say = SAID_AS[w];
3944
+ if (say && say.test(sw)) return true;
3945
+ const isX = /^is (.+)$/.exec(w);
3946
+ if (isX) {
3947
+ const t = isX[1];
3948
+ const as = SAID_AS[t];
3949
+ return new RegExp(` is (?:not )?(?:an? )?${t} `).test(sw) || !!as && / is /.test(sw) && as.test(sw);
3950
+ }
3951
+ return false;
3952
+ };
3953
+ const rawSaid = String(said);
3954
+ const howMany = / how many | length | size | count | number of /.test(sw);
3955
+ const isA = / is | are /.test(sw);
3956
+ const setWords2 = / set | empty | nothing | missing | null | nil | none | undefined | given | there | exists? /.test(sw);
3957
+ const ok = (n) => {
3958
+ if (!n || typeof n !== "object") return true;
3959
+ if (Array.isArray(n)) return n.every(ok);
3960
+ switch (n.kind) {
3961
+ case "name":
3962
+ return n.type === true || (NULL_NAME.test(n.name) ? setWords2 : has2(n.name));
3963
+ case "literal":
3964
+ if (n.type === "text") return rawSaid.includes(String(n.value)) || String(n.value).length === 0 || rawSaid.includes(String(n.raw ?? "").slice(1, -1)) || n.interpolated || /\\\(|\$\{|#\{|\{\w/.test(String(n.raw ?? n.value)) || (SAID_AS[String(n.value).toLowerCase()]?.test(sw) ?? false);
3965
+ return n.type === "null" ? setWords2 : n.type === "bool" ? true : n.type === "number" ? sw.includes(` ${String(n.raw ?? n.value).replace(/[^\w]+/g, " ").trim().toLowerCase()} `) || has2(String(n.value)) || /^[01]$/.test(String(n.value)) : true;
3966
+ case "member": {
3967
+ if (/^(?:length|size|count|len|Length|Count|Size)$/.test(n.property) && howMany) return ok(n.object);
3968
+ const obj = n.object;
3969
+ if (n.static || obj?.kind === "name" && /^[A-Z]/.test(obj.name) || obj?.kind === "member" && /^[A-Z]/.test(obj.property)) return has2(n.property);
3970
+ return has2(n.property) && ok(obj);
3971
+ }
3972
+ case "call": {
3973
+ const c = n.callee;
3974
+ const name = c?.kind === "member" ? c.property : c?.kind === "name" ? c.name : null;
3975
+ const own = c?.kind === "member" && !(c.object?.kind === "name" && /^[A-Z]/.test(c.object.name)) ? c.object : null;
3976
+ if (name && /^(?:enumerate|iter|iter_mut|into_iter|items|entries|values|stream|ToList|toList|AsEnumerable|toArray|asList|each_with_index|with_index|indices|withIndex|Values|Keys|keys)$/.test(name)) return ok(own) && ok(n.args);
3977
+ if (name && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(name) && / is /.test(sw)) return ok(n.args);
3978
+ if (name && /^(?:get|Get|fetch|at|get_or_default|getOrDefault|GetValueOrDefault|TryGetValue|getOrNull|Item)$/.test(name) && / entry | entries /.test(sw)) return ok(c.kind === "member" ? c.object : null) && ok(n.args);
3979
+ if (name && has2(name) && sw.includes(` result of ${splitWords(name).join(" ")} `)) return true;
3980
+ if (name && /^(?:new|New|create|of|from|make)$/.test(name) && / new /.test(sw) && c.kind === "member") return ok(c.object);
3981
+ if (name && /^(?:any|some|all|every|none|find|first|filter|where|select|detect|find_index|findIndex|includes|include\?|contains|Contains|any\?|all\?|none\?|exists|Any|All|Exists|in_array|has|hasOwnProperty|has_key|key\?|containsKey|ContainsKey|startswith|endswith|startsWith|endsWith|StartsWith|EndsWith|start_with\?|end_with\?)$/.test(name) && / (?:any|every|all|no|first|matches|match|in|has|contains|starts|ends|one of) /.test(sw)) return ok(own) && n.args.every((a) => a.kind === "lambda" || ok(a));
3982
+ if (name && /^(?:len|length|size|count|nrow|NROW|Count|sizeof|strlen|wcslen|mb_strlen|nchar|str_length|lengths|Length)$/.test(name) && howMany) return ok(c.kind === "member" ? c.object : null) && ok(n.args);
3983
+ if (name && /^(?:isinstance|is_a\??|kind_of\??|instance_of\??|inherits|is)$/.test(name) && isA) return ok(c.kind === "member" ? c.object : null) && ok(n.args);
3984
+ if (name && /^(?:is\.null|is_null|isNull|is\.na|isset|empty|is_none|isNone|isNil|is_nil|nil\?|null\?|blank\?|present\?|empty\?|isEmpty|IsNullOrEmpty|IsNullOrWhiteSpace|isBlank|isNotEmpty|isNotBlank|any\?|none\?)$/.test(name) && setWords2) return ok(c.kind === "member" ? c.object : null) && ok(n.args);
3985
+ return (name == null || has2(name)) && (c?.kind !== "member" || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? "")) && ok(n.args);
3986
+ }
3987
+ case "cast":
3988
+ return ok(n.value);
3989
+ case "pattern":
3990
+ return (n.names || []).every(has2);
3991
+ case "lambda":
3992
+ return true;
3993
+ case "comprehension":
3994
+ return n.clauses.every((c) => ok(c.iter));
3995
+ case "binary":
3996
+ if (/ built from its parts /.test(sw) && /^(?:\+|\.|\.\.|<>|\|\|)$/.test(n.op)) return true;
3997
+ return ok(n.left) && ok(n.right);
3998
+ case "template":
3999
+ return n.parts.every((x) => typeof x === "string" || ok(x.expr));
4000
+ default:
4001
+ for (const k of Object.keys(n)) {
4002
+ const v = n[k];
4003
+ if (v && typeof v === "object" && !ok(v)) return false;
4004
+ }
4005
+ return true;
4006
+ }
4007
+ };
4008
+ return ok(tree);
4009
+ }
4010
+ var KEYWORD_CALLEE = /^(?:use|unsafe|using|foreach|for|type|return|pub|public|private|protected|internal|static|final|var|let|const|val|if|while|switch|match|case|new|await|async|yield|throw|raise|def|fn|func|function|class|struct|enum|interface|impl|do|else|try|catch|lock|fixed|checked|unchecked|goto|typedef|template|typename|constexpr|sizeof|defer|go|select|when|loop|override|virtual|abstract|sealed|readonly|extern|inline|volatile|register|auto|signed|unsigned|operator|delegate|event|where|from|import|export|package|module|namespace|begin|end|unless|until|elsif|then|ensure|rescue|lambda|proc|mut|ref|out|in|is|as|not|and|or)$/;
4011
+ var coreOf = (e) => {
4012
+ let c = e;
4013
+ while (c && (c.kind === "unary" && (c.op === "await" || c.op === "?" || c.op === "!!") || c.kind === "cast" && c.form === "nonnull")) c = c.value;
4014
+ return c;
4015
+ };
4016
+ function chainCallees(e) {
4017
+ const out = [];
4018
+ let c = coreOf(e);
4019
+ while (c) {
4020
+ if (c.kind === "call") {
4021
+ const cal = c.callee;
4022
+ if (cal.kind === "member") {
4023
+ out.push(cal.property);
4024
+ c = coreOf(cal.object);
4025
+ continue;
4026
+ }
4027
+ if (cal.kind === "name") out.push(cal.name);
4028
+ if (cal.kind === "index" && cal.object?.kind === "name") out.push(cal.object.name);
4029
+ if (cal.kind === "index" && cal.object?.kind === "member") {
4030
+ out.push(cal.object.property);
4031
+ c = coreOf(cal.object.object);
4032
+ continue;
4033
+ }
4034
+ break;
4035
+ }
4036
+ if (c.kind === "logic" && c.op === "or" || c.kind === "binary" && (c.op === "??" || c.op === "?:")) {
4037
+ for (const x of c.operands ?? [c.left, c.right]) out.push(...chainCallees(x));
4038
+ }
4039
+ if (c.kind === "member" || c.kind === "index") {
4040
+ c = coreOf(c.object);
4041
+ continue;
4042
+ }
4043
+ break;
4044
+ }
4045
+ return out;
4046
+ }
4047
+ var sameWords = (a, b) => splitWords(a).join("") === splitWords(b).join("");
4048
+ var leadingWord = (code3) => (String(code3).trim().match(/^[A-Za-z_]+/) || [""])[0];
4049
+ var ENDING_CODE = /(?:^|[;&|]\s*)(?:exit|return|exec)\b|^\s*(?:return\b|yield\b|throw\b|raise\b|exit\b|die\b|abort\b|panic!?|halt\b|fail\b|Exit\b|exit\(|_exit\(|os\.Exit\(|sys\.exit\(|process\.exit\(|System\.exit\(|stop\(|Throw-|throw\(|break\b|Write-Error\b.*-ErrorAction\s+Stop|quit\(|q\()/i;
4050
+ var IMPLICIT_RETURN_LANGS = /* @__PURE__ */ new Set(["ruby", "rust", "kotlin", "scala", "swift", "r", "elixir", "typescript", "javascript", "csharp", "java", "powershell", "shell", "python", "go", "php", "cpp", "c", "sql"]);
4051
+ function checkStep(step, ctx) {
4052
+ const says = String(step.says ?? "");
4053
+ const code3 = String(step.code ?? "");
4054
+ currentLang = ctx.lang;
4055
+ let full = `${sourceOf(step, ctx)}${ctx.valueTarget ? `
4056
+ ${ctx.valueTarget}` : ""}`;
4057
+ if (ctx.lang === "shell" && step.kind === "fail" && ctx.lines) {
4058
+ const callee2 = (/^\s*([\w-]+)/.exec(code3) || [])[1];
4059
+ const def = callee2 && ctx.helperExits?.get(callee2);
4060
+ if (def) full += `
4061
+ exit ${def}`;
4062
+ }
4063
+ const e = step.expr;
4064
+ const lang = ctx.lang;
4065
+ const tree = e && e.kind !== "code" ? e : null;
4066
+ const hasTreeLang = !["shell", "powershell", "r", "sql"].includes(lang);
4067
+ if (hasTreeLang && (!e || e.kind === "code") && step.kind !== "try" && step.kind !== "check" && !/^(?:Otherwise|Leaves the|Skips to the next|Stops here$|Tries |Runs the next steps|If anything goes wrong)/.test(says)) {
4068
+ const why = safeForm(step, says, /…$/.test(code3) ? full.replace(/\s*\n\s*/g, " ") : code3, lang);
4069
+ if (why) return why;
4070
+ var safeOk = true;
4071
+ }
4072
+ LIBRARY_STEP = !!step.library;
4073
+ if (step.library && ctx.ownFunctions) {
4074
+ const callee2 = (/^\s*(?:return\s+)?(?:await\s+)?(?:(?:this|self)\s*\.\s*)?([A-Za-z_]\w*)\s*\(/.exec(code3) || [])[1];
4075
+ if (callee2 && ctx.ownFunctions.has(callee2)) return WHY.form;
4076
+ }
4077
+ if (inventedValue(says, full)) return WHY.value;
4078
+ const u = unsourcedWord(says, full);
4079
+ if (u) return `${WHY.words} ("${u}" has no source in the code)`;
4080
+ if (ambiguousName(says, full)) return WHY.ambiguous;
4081
+ const said0 = claimText(says);
4082
+ if (lang === "shell" && /<<</.test(`${code3}
4083
+ ${full}`)) return WHY.form;
4084
+ if (/(?:^|\s)(?:--|\?)(?:\s|$)/.test(claimText(says).replace(/\s+\?$/, ""))) return WHY.words;
4085
+ if (lang === "shell") {
4086
+ if (/\{[^{}\s"'$]*,[^{}\s"']*\}/.test(stripQuoted(full).replace(/\$\{[^}]*\}/g, ""))) return WHY.form;
4087
+ if (/"-"/.test(says) && /(?:^|\s)-(?:\s|$)/.test(full)) return WHY.form;
4088
+ }
4089
+ if (lang === "powershell" && /files and folders/.test(says) && /-(?:File|Directory)\b/i.test(full)) return WHY.meaning;
4090
+ if (lang === "powershell" && step.kind !== "branch" && step.kind !== "loop") {
4091
+ const said2 = ` ${splitWords(says).join(" ")} `;
4092
+ const cmdletParts = stripQuoted(code3).split("|").filter((p) => /^\s*(?:\$[\w:]+\s*=\s*)?(?:&\s*)?[A-Z][a-z]+-[A-Z]\w*/.test(p)).join(" | ");
4093
+ for (const m of `${cmdletParts} `.matchAll(/(?:^|\s)-([A-Za-z][A-Za-z]+)(?=\s+-|\s*$|\s*[|;)}])/g)) {
4094
+ const sw = m[1];
4095
+ if (/^(?:Force|ErrorAction|WarningAction|InformationAction|Verbose|Debug|Confirm|WhatIf|NoNewline|ForegroundColor|BackgroundColor|OutVariable|ErrorVariable|Scope|Global|Script|Not|Contains|NotContains|Match|NotMatch|Like|NotLike|And|Or|Eq|Ne|Gt|Lt|Ge|Le|Is|IsNot|In|NotIn|Replace|Split|Join|F|As|Band|Bor|PassThru|Mandatory|Online|NoElement|NoTypeInformation)$/i.test(sw)) continue;
4096
+ const map = { recurse: / everything | all | recursive| and every /, raw: / whole | as one | raw /, unique: / unique | once | duplicate /, file: / files? /, directory: / folders? /, leaf: / last part | leaf /, parent: / parent | folder /, descending: / descending | highest | largest | last /, first: / first /, last: / last /, sum: / total | sum /, count: / how many | count /, resolve: / full /, literalpath: / path /, encoding: / encoding /, append: / adds? | append /, nonewline: / /, quiet: / quiet /, simplematch: / plain text | as text /, casesensitive: / case /, asplaintext: / plain /, aspath: / path /, include: / including /, exclude: / except | excluding | without /, skip: / skip /, wait: / wait /, nowait: / without waiting /, nologo: / /, noprofile: / without the profile /, hidden: / hidden /, wrap: / wrap /, autosize: / size /, expandproperty: / /, property: / /, typename: / type /, list: / list /, all: / all /, tail: / last /, totalcount: / first /, delimiter: / separated /, header: / header /, noclobber: / not overwrite | replace nothing /, depth: / deep | depth /, compress: / compact | compress /, asjob: / background /, isvalid: / valid /, pathtype: / folder | file /, erroraction: / / };
4097
+ const key = sw.toLowerCase();
4098
+ if (said2.includes(` ${splitWords(sw).join(" ")} `) || map[key] && map[key].test(said2)) continue;
4099
+ return WHY.meaning;
4100
+ }
4101
+ }
4102
+ if (tree && /when (?:that|it) has no value/.test(says) && [...nodesOf2(tree)].some((n) => n.kind === "logic" && n.op === "or") && !/^(?:javascript|typescript|python|ruby|r|shell|powershell|perl|lua)$/.test(lang)) return WHY.meaning;
4103
+ if (tree && ctx.ownNames && /\b(?:this|self)\b/.test(code3) && [...nodesOf2(tree)].some((n) => n.kind === "member" && n.object?.kind === "name" && /^(?:this|self)$/.test(n.object.name) && ctx.ownNames.has(n.property)) && !/\b(?:this|self|its own|it is given)\b/.test(says)) return WHY.ambiguous;
4104
+ if (tree && /\bwhether\b/.test(says)) {
4105
+ const v = coreOf(tree.kind === "assign" ? tree.value : tree.kind === "return" ? tree.value : tree);
4106
+ const yn = (n) => n && (n.kind === "compare" || n.kind === "chain" || n.kind === "not" || n.kind === "logic" && n.operands.every(yn) || n.kind === "literal" && n.type === "bool" || n.kind === "call" && /^(?:is|has|can|should|does|contains|includes|exists|matches|match|fnmatch|equals|starts|ends|any|all|every|some|isinstance|[a-z_]+\?)/i.test(String(n.callee?.property ?? n.callee?.name ?? "")) || n.kind === "name" && /^(?:is|has|can|should)[A-Z_]/.test(n.name) || n.kind === "member" && /^(?:is|has|can|should)[A-Z_]/.test(n.property));
4107
+ if (v && !yn(v)) return M("whether-not-yes-no");
4108
+ }
4109
+ if (lang === "java" && tree && [...nodesOf2(tree)].some((n) => n.kind === "compare" && /^[!=]=$/.test(n.op) && [n.left, n.right].some((x) => x?.kind === "literal" && x.type === "text"))) return WHY.meaning;
4110
+ if (tree && /when (?:that|it) has no value/.test(says) && [...nodesOf2(tree)].some((n) => n.kind === "logic" && n.op === "or") && ![...nodesOf2(tree)].some((n) => n.kind === "binary" && (n.op === "??" || n.op === "?:"))) return WHY.meaning;
4111
+ if (tree && [...nodesOf2(tree)].some((n) => n.kind === "call" && /^(?:setdefault|putIfAbsent|computeIfAbsent|getOrPut|get_or_insert|get_or_insert_with|or_insert|or_insert_with|TryAdd|GetOrAdd)$/.test(n.callee?.property ?? n.callee?.name ?? "")) && !/\b(?:if|unless|yet|missing|not there|nothing)\b/.test(said0)) return WHY.meaning;
4112
+ if (claimWords(says).some((w) => w.length === 1)) for (const id of String(full).match(/\b[A-Za-z][a-z]*[A-Z][A-Za-z]*\b/g) || []) {
4113
+ if (id.length > 4) continue;
4114
+ const parts = splitWords(id);
4115
+ if (parts.some((p) => p.length === 1) && ` ${claimWords(says).join(" ")} `.includes(` ${parts.join(" ")} `) && !String(says).includes(id)) return WHY.words;
4116
+ }
4117
+ if ((lang === "c" || lang === "cpp") && /^\s*(?:const\s+)?static\b/.test(code3) && /^Sets |^Works out /.test(says)) return WHY.form;
4118
+ if (tree && /\bthe items in\b.*\b(?:that|where)\b|\bonly those where\b/.test(says)) {
4119
+ const calls = [...nodesOf2(tree)].filter((n) => n.kind === "call");
4120
+ if (calls.length && !calls.some((c) => (c.args || []).some((a) => a.kind === "lambda" || a.kind === "name" || a.kind === "member"))) return WHY.meaning;
4121
+ }
4122
+ if (lang !== "ruby" && /given block/.test(says)) return WHY.form;
4123
+ if (/\[[^\]]*\b(?:how many|the|is|of|whether)\b[^\]]*\]/.test(claimText(says))) return WHY.words;
4124
+ if (!bracketsClosed(claimText(says))) return WHY.words;
4125
+ const self = /^Sets (.+?) to (.+?)$/.exec(says);
4126
+ if (self && sameWords(self[1], self[2]) && self[1] !== self[2] && /^[a-z]/.test(self[2].replace(/^the /, "")) && !/^\s*(?:[\w.]+)\s*=\s*\1\s*;?$/.test(code3)) return WHY.ambiguous;
4127
+ if (self && self[1] === self[2] && !new RegExp(`^\\s*(?:\\S+\\s+)?([\\w.$]+)\\s*=\\s*\\$?\\{?\\1\\}?\\s*;?$`).test(code3)) return WHY.ambiguous;
4128
+ if (safeOk) return null;
4129
+ const said = claimText(says);
4130
+ switch (step.kind) {
4131
+ case "branch": {
4132
+ if (/^(?:Chooses by|Checks these cases)/.test(says)) {
4133
+ if (tree && tree.kind === "switch" && tree.subject && !namesKept(tree.subject, says)) return M("L285");
4134
+ return null;
4135
+ }
4136
+ if (/^(?:Waits for whichever of these is ready first|Checks which of these is ready, without waiting)/.test(says)) return /^\s*select\b/.test(code3) ? null : WHY.form;
4137
+ const letM = /^\s*([\w.]+)\?\.(?:let|also|run|apply)\s*\{/.exec(code3);
4138
+ if (letM) {
4139
+ const w = /^If (.+?) is set(?: \(\d+ steps? inside\))?$/.exec(says);
4140
+ return w && sameWords(w[1].replace(/^the (?:[\w ]+'s )?/, ""), letM[1].split(".").pop()) ? null : WHY.form;
4141
+ }
4142
+ if (!/^If\b/.test(says)) return /^(?:When|Unless)\b/.test(says) ? null : WHY.form;
4143
+ return conditionKept(step, tree, says, code3, lang);
4144
+ }
4145
+ case "loop":
4146
+ ctx_full = full;
4147
+ return loopKept(step, tree, says, code3, lang);
4148
+ case "check": {
4149
+ if (/^(?:Otherwise|Default|If none)/.test(says)) return null;
4150
+ if (/^\s*case\b.*<-/.test(code3) && /^When /.test(says)) return null;
4151
+ if (tree && tree.kind === "case" && tree.patterns && !tree.patterns.every((p) => namesKept(p, says))) return M("L294");
4152
+ if (tree && tree.kind === "case" && /\bis (?:set|not|empty)\b|\b(?:more|less) than\b|\bat (?:least|most)\b/.test(said) && !tree.patterns?.some((p) => [...nodesOf2(p)].some((n) => n.kind === "compare" || n.kind === "not" || isNullish(n)))) return M("case-claim");
4153
+ if (tree && tree.kind === "call" && /^Checks that /.test(says)) return conditionCore(tree.args?.[0] ?? tree, says, code3, lang);
4154
+ return null;
4155
+ }
4156
+ case "return": {
4157
+ const response = /^\s*(?:return\s+)?(?:res|reply|response|ctx|c)\s*\.\s*(?:status\([^)]*\)\s*\.\s*)?(?:json|send|end|render|redirect|sendStatus|sendFile|JSON|String|HTML)\s*\(/.test(code3) || /^\s*next\s*\(/.test(code3) && ctx.last;
4158
+ if (!response && !ENDING_CODE.test(code3) && !implicitReturnOk(step, ctx, code3)) return WHY.ending;
4159
+ if (/^Stops here\b/.test(says)) return tree && tree.kind === "return" && tree.value || !/^\s*(?:return|exit|exit\s+0)?\s*;?\s*$/.test(code3.replace(/^\s*return\b/, "")) ? M("stops-not-bare") : null;
4160
+ if (/^Returns whether |^Gives back whether /.test(says)) return conditionCore(tree?.kind === "return" ? tree.value : tree, says.replace(/^\w+ (?:back )?whether /, ""), code3, lang);
4161
+ return valueKept(tree?.kind === "return" ? tree.value : tree, says, code3, lang);
4162
+ }
4163
+ case "fail": {
4164
+ if (!ENDING_CODE.test(code3) && !/^\s*(?:Write-Error|errors\.New|Err\(|return\s+Err|abort|die|bail!|ensure!|stop\(|rlang::abort|cli::cli_abort|assert)/.test(code3)) {
4165
+ const callee2 = (/^\s*([A-Za-z_][\w.:-]*)/.exec(code3) || [])[1] ?? "";
4166
+ const response = /\b(?:res|reply|response|ctx|c|w|resp)\s*\.\s*(?:status|code|sendStatus|WriteHeader|JSON|String|AbortWithStatus\w*)\s*\(\s*(?:[45]\d\d|http\.Status\w+)|\babort\(\s*[45]\d\d|HTTPException\(|Http\w*Exception|ResponseStatusException|halt\b|error\(\s*[45]\d\d/.test(code3);
4167
+ if (!response) {
4168
+ if (!/(?:^|[._:-])(?:fail|fatal|fatalf|fatalln|panic|panicf|abort|die|exit|exiterr|error|raise|throw|bail|stop|halt|err|reject|crash|terminate|quit)\w*$/i.test(callee2)) return WHY.ending;
4169
+ }
4170
+ }
4171
+ if (tree && saidNegations(says) > treeNegations(tree) + 1) return M("L309");
4172
+ return null;
4173
+ }
4174
+ case "try":
4175
+ return /^\s*(?:try\b|begin\b|do\s*\{|do$|\$\{?|tryCatch|withCallingHandlers|catch\b|rescue\b)/.test(code3) || /^(?:Tries|Runs the next steps)/.test(says) ? null : WHY.form;
4176
+ default:
4177
+ break;
4178
+ }
4179
+ if (tree) {
4180
+ const core = coreOf(tree.kind === "return" ? tree.value : tree);
4181
+ if (core?.kind === "call") {
4182
+ const w = ` ${splitWords(says).join(" ")} `;
4183
+ for (const a of core.args || []) {
4184
+ if (a.kind !== "index" && !(a.kind === "member" && a.object?.kind === "index")) continue;
4185
+ let root = a;
4186
+ while (root && (root.kind === "index" || root.kind === "member")) root = root.object;
4187
+ const rn = root?.kind === "name" ? root.name : root?.kind === "member" ? root.property : null;
4188
+ if (rn && w.includes(` ${splitWords(rn).join(" ")} `) && !namesKept(a, says)) return M("arg-part");
4189
+ }
4190
+ }
4191
+ }
4192
+ const adds = /^Adds (.+?) to (?:the end of )?(.+?)(?: \(.*\))?$/.exec(says);
4193
+ if (adds && tree) {
4194
+ let core = coreOf(tree.kind === "assign" ? tree.value : tree);
4195
+ for (let c = core; c && c.kind === "call"; c = c.callee?.kind === "member" ? coreOf(c.callee.object) : null) {
4196
+ if (/^(?:add|push|append|insert|extend|concat|Add|AddRange|put|unshift|prepend|push_back|emplace_back|merge)$/.test(c.callee?.property ?? c.callee?.name ?? "")) {
4197
+ core = c;
4198
+ break;
4199
+ }
4200
+ }
4201
+ if (tree.kind === "assign" && tree.op !== "=" && tree.op !== ":=") {
4202
+ if (!namesKept(tree.value, adds[1])) return M("adds-value");
4203
+ } else if (core?.kind === "call" && core.args?.length && !core.args.some((a) => namesKept(a, adds[1]))) return M("adds-value");
4204
+ else if (core?.kind === "call" && core.args?.some((a) => a.kind === "index") && !core.args.every((a) => namesKept(a, adds[1]) || a.kind === "name")) return M("adds-value");
4205
+ }
4206
+ if (/^Calls /.test(says)) return callKept(step, tree, says, code3, lang);
4207
+ if (tree) {
4208
+ const summary = /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes|Stores the result of)\b| the result of /.test(says);
4209
+ const neg = treeNegations(tree, summary), w = saidNegations(says);
4210
+ if (w !== neg && !(w < neg && /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes)\b/.test(says) && !/\b(?:whether|if|when)\b/.test(said))) return M("L320");
4211
+ if (w > neg) return M("L321");
4212
+ if (/^Sets .+ to /.test(says)) {
4213
+ const v = tree.kind === "assign" ? tree.value : null;
4214
+ if (v) {
4215
+ if (!newThing(v, says) && !namesKept(v, says)) return M("L327");
4216
+ if (castCount(v) && !/\bas\b|\bcopy\b|\bconverted\b|\bturned\b/.test(said)) return M("L328");
4217
+ if (!orderingKept(v, says)) return M("L329");
4218
+ }
4219
+ }
4220
+ if (/^Works out (.+?) from (.+)$/.test(says) && tree.kind === "assign") {
4221
+ const m = /^Works out (.+?) from ([\w ]+)$/.exec(says);
4222
+ const callees = chainCallees(tree.value);
4223
+ if (m && callees.length && !callees.some((c) => sameWords(c, m[2]))) return M("L335");
4224
+ }
4225
+ if (/\bif\b.*\botherwise\b/.test(said) && ![...nodesOf2(tree)].some((n) => n.kind === "conditional" || n.kind === "if")) return WHY.form;
4226
+ }
4227
+ return null;
4228
+ }
4229
+ function callKept(step, tree, says, code3, lang) {
4230
+ const m = /^Calls ([^,:(]+?)(?: with these steps| on each| for each|,|:| \(| —|$)/.exec(says);
4231
+ if (!m) return WHY.form;
4232
+ const named2 = m[1].trim();
4233
+ const first = splitWords(named2)[0] ?? "";
4234
+ if (KEYWORD_CALLEE.test(first) && splitWords(named2).length === 1 && !new RegExp(`(?:[.>:]|^)\\s*${named2.replace(/\W/g, "")}\\s*\\(`).test(code3.trim())) return WHY.form;
4235
+ const lead = leadingWord(code3);
4236
+ if (KEYWORD_CALLEE.test(lead) && !/^(?:new|await|go|defer|yield|return|try|do|lock|using|fixed|checked|unchecked|if|unless|when)$/.test(lead) && sameWords(lead, named2) && !new RegExp(`^\\s*${lead}\\s*\\(`).test(code3)) return WHY.form;
4237
+ if (tree) {
4238
+ const core = coreOf(tree.kind === "return" ? tree.value : tree);
4239
+ if (!core) return WHY.form;
4240
+ const callees = [];
4241
+ for (const n of nodesOf2(core)) if (n.kind === "call") {
4242
+ const c = n.callee;
4243
+ if (c.kind === "member") callees.push(c.property);
4244
+ else if (c.kind === "name") callees.push(c.name);
4245
+ }
4246
+ if (core.kind === "name" && (lang === "ruby" || lang === "go" || lang === "perl")) callees.push(core.name);
4247
+ if (core.kind === "member" && lang === "ruby") callees.push(core.property);
4248
+ if (!callees.length) return WHY.form;
4249
+ const objects = [];
4250
+ for (const n of nodesOf2(core)) if (n.kind === "call" && n.callee.kind === "member" && n.callee.object?.kind === "name") objects.push(n.callee.object.name);
4251
+ if (!callees.some((c) => sameWords(c, named2) || splitWords(c).join(" ").endsWith(splitWords(named2).join(" "))) && !objects.some((o) => sameWords(o, named2))) return M("L360");
4252
+ if (core.kind === "logic" || core.kind === "not" || core.kind === "compare" || core.kind === "conditional") return WHY.form;
4253
+ } else if (!["shell", "powershell", "r", "sql"].includes(lang) || lang === "r") {
4254
+ const re = new RegExp(`(?:^|[^\\w$])${splitWords(named2).map((w) => `${w}`).join("[_\\s-]*")}\\s*\\(`, "i");
4255
+ if (!re.test(code3.replace(/::/g, "."))) return WHY.form;
4256
+ }
4257
+ return null;
4258
+ }
4259
+ function conditionCore(test, says, code3, lang) {
4260
+ if (!test || test.kind === "code") {
4261
+ return accountsFor(code3, claimText(says)) ? null : M("L374");
4262
+ }
4263
+ const said = claimText(says);
4264
+ const tn = treeNegations(test), wn = saidNegations(says);
4265
+ if (tn !== wn) return M("L378");
4266
+ let logic = 0;
4267
+ for (const n of nodesOf2(test)) if (n.kind === "logic") logic += n.operands.length - 1;
4268
+ const wl = (said.match(/\band\b|\bor\b/g) || []).length;
4269
+ if (logic !== wl) return M("L381");
4270
+ if (!orderingKept(test, says)) return M("L382");
4271
+ if (arithCount(test) > (said.match(/\b(?:plus|minus|times|divided|multiplied|remainder|shifted|bits?|mod|modulo)\b|[-+*/%&|^~]|<<|>>/g) || []).length + (/\bhow many\b/.test(said) ? 1 : 0)) return M("L383");
4272
+ const one = test.kind === "not" ? test.value : test;
4273
+ if (one?.kind === "call") {
4274
+ const name = one.callee?.kind === "member" ? one.callee.property : one.callee?.name;
4275
+ const w = ` ${splitWords(said).join(" ")} `;
4276
+ if (name && w.replace(/ (?:not|cannot|can t) /g, " ").includes(` ${splitWords(name).join(" ").replace(/^(?:is|can|has|should|does) /, "")} `)) return null;
4277
+ }
4278
+ if (!namesKept(test, says)) return M("L384");
4279
+ return null;
4280
+ }
4281
+ function conditionKept(step, tree, says, code3, lang) {
4282
+ if (isCodeWords(says.replace(/^If (?:not: )?/, "").replace(/ \(\d+ steps? inside\)$/, ""))) return null;
4283
+ const words10 = says.replace(/^If (?:not: )?/, "").replace(/ \(\d+ steps? inside\)$/, "");
4284
+ const not = /^If not: /.test(says);
4285
+ if (tree && tree.kind === "if") {
4286
+ if (tree.init) {
4287
+ const fails = /^If (.+?) fails$/.exec(says);
4288
+ const v = tree.init.kind === "assign" ? coreOf(tree.init.value) : null;
4289
+ const t = tree.test;
4290
+ const errTest = t?.kind === "compare" && t.op === "!=" && t.left?.kind === "name" && /^err\w*$/i.test(t.left.name) && isNullish(t.right);
4291
+ const target = tree.init.target;
4292
+ const assignsErr = target && [...nodesOf2(target)].some((n) => n.kind === "name" && n.name === t?.left?.name);
4293
+ if (fails && errTest && assignsErr && v?.kind === "call" && chainCallees(v).some((c) => sameWords(c, fails[1]))) return null;
4294
+ return WHY.form;
4295
+ }
4296
+ const test = tree.negate && not ? tree.test : tree.negate ? { kind: "not", value: tree.test } : tree.test;
4297
+ if (not && !tree.negate) return conditionCore({ kind: "not", value: test }, `not ${words10}`, code3, lang);
4298
+ return conditionCore(test, words10, code3, lang);
4299
+ }
4300
+ if (tree) return WHY.form;
4301
+ if (lang === "powershell" || lang === "r" || lang === "sql") return null;
4302
+ if (lang === "shell") return shellConditionKept(code3, says);
4303
+ const cond = String(step.cond ?? code3);
4304
+ if (!accountsFor(cond, `${not ? "not " : ""}${claimText(words10)}`)) return M("L402");
4305
+ return null;
4306
+ }
4307
+ function shellConditionKept(code3, says) {
4308
+ const keyword = /^\s*(?:if|elif|while|until)\s/.test(String(code3));
4309
+ let c = stripQuoted(String(code3).replace(/^\s*(?:if|elif|while|until)\s+/, "").replace(/;\s*(?:then|do)\s*$/, ""));
4310
+ if (/<<<|<<-?\s*['"]?\w/.test(c)) return M("shell-heredoc");
4311
+ let connectorNeg = 0;
4312
+ if (!keyword) {
4313
+ const br = /^\s*(\[\[?)/.exec(c);
4314
+ const endBr = br ? c.indexOf(br[1] === "[[" ? "]]" : " ]") : -1;
4315
+ const after = endBr > 0 ? /^\s*(\|\||&&)/.exec(c.slice(endBr + 2)) : null;
4316
+ const at2 = after ? endBr + 2 + after.index + after[0].indexOf(after[1]) : Math.max(c.lastIndexOf("||"), c.lastIndexOf("&&"));
4317
+ if (at2 < 0) return M("shell-form");
4318
+ connectorNeg = c.slice(at2, at2 + 2) === "||" ? 1 : 0;
4319
+ c = c.slice(0, at2);
4320
+ }
4321
+ const neg = connectorNeg + (c.match(/(?:^|\s)!(?=\s)|!=|-ne\b/g) || []).length + (c.match(/\bgrep\b(?:\s+-\w+)*\s+-[a-zA-Z]*v/g) || []).length;
4322
+ const said = claimText(says).replace(FORM_NEGATIONS, " ");
4323
+ const wneg = splitWords(said.replace(/n't\b/g, " nt")).filter((w) => NEG_TOKEN.test(w) || w === "fails" || w === "failed").length;
4324
+ if (/^If that failed$/.test(says)) return /\|\|/.test(c) ? null : M("shell-failed");
4325
+ const logic = (c.match(/&&|\|\|/g) || []).length + (/\[\s|\btest\s/.test(c) ? (c.match(/\s-a\s|\s-o\s/g) || []).length : 0);
4326
+ const wl = (said.match(/\band\b|\bor\b/g) || []).length;
4327
+ const terms = c.split("&&");
4328
+ if (connectorNeg && !/\|\||(?:^|\s)!(?=\s)/.test(c) && terms.length > 1 && wneg === terms.length && (said.match(/\bor\b/g) || []).length >= terms.length - 1) return null;
4329
+ if (neg !== wneg) return M("shell-neg");
4330
+ if (wl < logic) return M("shell-logic");
4331
+ if (/\bgrep\b/.test(c) && /\bcontains?\b|\bmatch/.test(said) && /\s-[a-zA-Z]*v/.test(c) && !/\bnot\b|n't/.test(said)) return M("shell-grep-v");
4332
+ return null;
4333
+ }
4334
+ var ctx_full = "";
4335
+ function repeatsKept(says, full) {
4336
+ const n = /^Repeats (\w+) times/.exec(says)[1];
4337
+ return new RegExp(`\\b${n}\\b`).test(full) && /\b(?:times|range|repeat|for|Repeat|seq|upto)\b|\.\./.test(full);
4338
+ }
4339
+ function doWhileKept(says, full, lang) {
4340
+ const w = /^Runs once, then repeats (while|until) (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
4341
+ const m = /\b(while|until)\s*\((.*)\)\s*;?\s*$/.exec(String(full).split("\n").pop() ?? "") || /\b(while|until)\s+(.*?)\s*;?\s*$/.exec(String(full).split("\n").pop() ?? "");
4342
+ if (!w || !m || w[1] !== m[1]) return WHY.form;
4343
+ const test = parseExpr(m[2], lang);
4344
+ return conditionCore(test, w[2], m[2], lang);
4345
+ }
4346
+ function loopKept(step, tree, says, code3, lang) {
4347
+ if (/^Runs once, then repeats/.test(says)) return doWhileKept(says, ctx_full, lang);
4348
+ if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
4349
+ if (/^`/.test(says) || /^Repeats (?:for|while) `/.test(says)) return null;
4350
+ if (tree && tree.kind === "loop") {
4351
+ if (tree.form === "each") {
4352
+ const m = /^For each (.+?) in (.+?)(?:, only those where .*)?(?: \(\d+ steps? inside\))?$/.exec(says);
4353
+ if (/^(?:For each item in|Repeats once for each item in)/.test(says)) return iterableKept(tree.iterable, says.replace(/^.*? in /, "").replace(/ \(\d+ steps? inside\)$/, "")) ? null : M("L411");
4354
+ if (!m) return WHY.form;
4355
+ for (const t of tree.targets) if (!namesKept(t, m[1])) return M("L413");
4356
+ return iterableKept(tree.iterable, m[2]) ? null : M("L416");
4357
+ }
4358
+ if (tree.form === "while" || tree.form === "until") {
4359
+ if (/^Repeats until (?:something|a step) inside/.test(says)) return tree.test?.kind === "literal" && (tree.test.value === true || tree.test.value === 1) ? null : WHY.form;
4360
+ const m = /^(?:Repeats while|Runs once, then repeats while|Repeats until) (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
4361
+ if (!m) return WHY.form;
4362
+ const neg = /^Repeats until/.test(says) !== (tree.form === "until");
4363
+ return conditionCore(neg ? { kind: "not", value: tree.test } : tree.test, m[1], code3, lang);
4364
+ }
4365
+ if (tree.form === "for") {
4366
+ const m = /^Counts (\w[\w ]*?) from (.+?) while (.+?)(?:, (?:adding|in steps of|going) (.+?))?(?: \(\d+ steps? inside\))?$/.exec(says);
4367
+ if (!m) return /^Repeats until (?:something|a step) inside/.test(says) && !tree.test ? null : WHY.form;
4368
+ const init = tree.init, upd = tree.update;
4369
+ const v = init?.kind === "assign" ? init.target : null;
4370
+ if (!v || v.kind !== "name" || !sameWords(v.name, m[1])) return M("L429");
4371
+ if (!upd || !(upd.kind === "unary" && /^(?:\+\+|--)$/.test(upd.op) && upd.value.kind === "name" && upd.value.name === v.name)) {
4372
+ if (!m[4]) return M("L431");
4373
+ } else if (upd.op === "--" && !/\bdown\b|\bsubtract/.test(says)) return M("L432");
4374
+ if (!namesKept(init.value, m[2]) && !/^-?\d+$/.test(m[2].trim())) return M("L433");
4375
+ return conditionCore(tree.test, m[3], code3, lang);
4376
+ }
4377
+ if (tree.form === "forever") return /^Repeats until/.test(says) ? null : WHY.form;
4378
+ if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
4379
+ return WHY.form;
4380
+ }
4381
+ if (tree) return /^(?:For each|Repeats once for each) /.test(says) && tree.kind === "call" ? callLoopKept(tree, says) : WHY.form;
4382
+ if (/^Repeats while |^Repeats until /.test(says)) return accountsFor(code3.replace(/^\s*(?:while|until)\b/, ""), says.replace(/^Repeats (?:while|until) /, "").replace(/ \(\d+ steps? inside\)$/, "")) ? null : M("L441");
4383
+ if (/\bwhile\b[^;]*\bread\b(?:\s+-\w+)*\s+\w+\s+\w+/.test(code3) || /;\s*read\b/.test(code3)) return WHY.form;
4384
+ return null;
4385
+ }
4386
+ function iterableKept(it, words10) {
4387
+ if (!it) return false;
4388
+ if (namesKept(it, words10)) return true;
4389
+ const w = ` ${splitWords(words10).join(" ")} `;
4390
+ let c = coreOf(it);
4391
+ if (c?.kind === "member" && w.includes(` ${splitWords(c.property).join(" ")} `) && splitWords(words10).length <= splitWords(c.property).length + 1) return true;
4392
+ return chainCallees(it).some((x) => sameWords(x, words10) || w.includes(` ${splitWords(x).join(" ")} `));
4393
+ }
4394
+ function callLoopKept(tree, says) {
4395
+ const callees = chainCallees(tree);
4396
+ if (!callees.some((c) => /^(?:each|forEach|for_each|each_with_index|each_pair|each_key|each_value|times|map|ForEach|foreach|forEachIndexed|iter|for_each_entry|apply|lapply|sapply|walk|upto|downto|step|each_line|each_char|loop)$/i.test(c))) return WHY.form;
4397
+ return null;
4398
+ }
4399
+ function valueKept(v, says, code3, lang) {
4400
+ if (!v) return /^(?:Returns|Gives back)(?: nothing| an? (?:empty|new|computed)| this\b| itself| the same)/.test(says) || !/^(?:Returns|Gives back)/.test(says) ? null : null;
4401
+ const said = claimText(says);
4402
+ const tn = treeNegations(v, / the result of /.test(says)), wn = saidNegations(says);
4403
+ if (wn > tn) return M("L459");
4404
+ if (wn < tn && !/the result of|the items|a new|computed/.test(said)) return M("L460");
4405
+ const m = /^(?:Returns|Gives back) the result of ([\w ]+?)(?:,|$| with| on| from)/.exec(says);
4406
+ if (m) {
4407
+ const callees = chainCallees(v);
4408
+ if (!callees.some((c) => sameWords(c, m[1]))) return M("L464");
4409
+ return null;
4410
+ }
4411
+ const cond = coreOf(v);
4412
+ const iff = /^(?:Returns|Gives back) (.+) if (.+), otherwise (.+)$/.exec(says);
4413
+ if (cond?.kind === "conditional" && iff) {
4414
+ const side = (node, phrase) => /^a new /.test(phrase) ? newThing(node, ` ${phrase}`) : /^the result of /.test(phrase) ? chainCallees(node).some((c) => sameWords(c, phrase.replace(/^the result of /, ""))) : namesKept(node, phrase);
4415
+ if (!side(cond.then, iff[1]) || !side(cond.else, iff[3])) return M("cond-side");
4416
+ return conditionCore(cond.test, iff[2], code3, lang);
4417
+ }
4418
+ if (/^(?:Returns|Gives back) a new /.test(says)) return newThing(v, says) || coreOf(v)?.kind === "call" || coreOf(v)?.kind === "object" || coreOf(v)?.kind === "array" ? null : M("L467");
4419
+ if (castCount(v) && !/\bas\b|\bconverted\b|\bturned\b/.test(said)) return M("L468");
4420
+ if (!orderingKept(v, says)) return M("L469");
4421
+ const core = coreOf(v);
4422
+ if (core && /^(?:name|member|literal|binary|compare|logic|not|unary|index)$/.test(core.kind) && !namesKept(core, says)) return M("L472");
4423
+ if (core?.kind === "call" && !/^(?:Returns|Gives back) (?:the result of|a new|whether|one for each|the items|the first|a copy|what)\b/.test(says)) {
4424
+ const name = core.callee?.kind === "member" ? core.callee.property : core.callee?.name;
4425
+ const wrapper = chainCallees(core).some((c) => /^(?:ConfigureAwait|unwrap|expect|await|get|Result)$/.test(c) && chainCallees(core).some((d) => ` ${splitWords(says).join(" ")} `.includes(` ${splitWords(d).join(" ")} `))) || /^(?:json|send|end|render|redirect|status|sendStatus|JSON|String|Ok|Some|Err|None|Success|Failure|Result|ToString|toString|to_s|to_str|str|repr|String|next|resolve|reject|of|from|wrap|just|pure|Task|FromResult|Promise)$/.test(String(name)) || /\bas text\b/.test(says);
4426
+ if (name && !wrapper && !` ${splitWords(says).join(" ")} `.includes(` ${splitWords(name).join(" ")} `) && !LIBRARY_STEP) return M("return-call");
4427
+ }
4428
+ if (core && core.kind === "binary" && ARITH.has(core.op) && arithCount(core) > (said.match(/\b(?:plus|minus|times|divided|multiplied|remainder|shifted|joined|followed|added|bits?|mod)\b|[-+*/%&|^~]|<<|>>/g) || []).length + (/\bbuilt from its parts\b|\btext\b/.test(said) ? 9 : 0)) return M("L473");
4429
+ return null;
4430
+ }
4431
+ var SAFE_PATH = String.raw`[A-Za-z_][\w]*(?:\s*(?:\.|->|::)\s*[A-Za-z_][\w]*)*`;
4432
+ var SAFE_CALL = new RegExp(String.raw`^\s*(?:await\s+)?(?:\(void\)\s*)?(${SAFE_PATH})\s*\(`);
4433
+ var SAFE_ASSIGN = new RegExp(String.raw`^\s*(?:(?:const|static|unsigned|signed|struct|enum|volatile|register|auto|let|var|val|final|mut)\s+)*(?:[A-Za-z_][\w:<>,\s]*?[\s*&]+)?\**\s*(${SAFE_PATH})\s*=(?!=)\s*(?:\([A-Za-z_][\w\s*]*\)\s*)?(?:await\s+)?(${SAFE_PATH})\s*\(`);
4434
+ function balancedTail(code3, open) {
4435
+ let d = 0;
4436
+ for (let i = open; i < code3.length; i++) {
4437
+ const ch = code3[i];
4438
+ if (ch === '"' || ch === "'") {
4439
+ const q = ch;
4440
+ for (i++; i < code3.length && code3[i] !== q; i++) if (code3[i] === "\\") i++;
4441
+ continue;
4442
+ }
4443
+ if (ch === "(") d++;
4444
+ else if (ch === ")") {
4445
+ d--;
4446
+ if (d === 0) return /^\s*;?\s*(?:\/\/.*|\/\*.*\*\/\s*)?$/.test(code3.slice(i + 1));
4447
+ }
4448
+ }
4449
+ return false;
4450
+ }
4451
+ var TRAILING_CLOSURE = /* @__PURE__ */ new Set(["swift", "kotlin", "ruby", "scala", "groovy"]);
4452
+ function safeForm(step, says, code3, lang = "") {
4453
+ const trailing = TRAILING_CLOSURE.has(lang);
4454
+ if (!trailing && /\{\s*$/.test(String(code3).trim()) && /^(?:Calls|Returns the result of) /.test(says) && !/\)\s*\{\s*$/.test(String(code3).trim())) return WHY.unparsed;
4455
+ let c = String(code3).replace(/\s*\{\s*$/, "").trim().replace(/^(?:try[?!]?\s+)?(?:await\s+)?(?=[A-Za-z_])/, "");
4456
+ c = c.replace(/(?<![=!<>])=(?!=)\s*(?:try[?!]?\s+)?(?:await\s+)?/, "= ");
4457
+ if (step.kind === "return" && !/^return\b/.test(c)) c = `return ${c.replace(/^(?:try[?!]?\s+)?(?:await\s+)?/, "")}`;
4458
+ c = c.replace(/^return\s+(?:try[?!]?\s+)?(?:await\s+)?/, "return ");
4459
+ if (trailing && /^(?:return\s+)?[A-Za-z_][\w.]*\s*\{/.test(c) && /^(?:Calls|Returns the result of) /.test(says)) c = c.replace(/^((?:return\s+)?[A-Za-z_][\w.]*)\s*\{.*$/, "$1()");
4460
+ if (/^(?:return\s+)?[A-Za-z_][\w.]*\s*\(.*\)\s*\{.*$/.test(c) && /^(?:Calls|Returns the result of) /.test(says) && step.children?.length) c = c.replace(/\)\s*\{.*$/, ")");
4461
+ const lastName = (p) => p.split(/\s*(?:\.|->|::|\?\.)\s*/).pop();
4462
+ let m;
4463
+ if (/^defer\b/.test(c) && /^At the end/.test(says)) return null;
4464
+ if (step.kind === "return" && (m = /^return\s+(?:new\s+)?([A-Z][\w]*)(?:\.init)?\s*[({]/.exec(c))) return new RegExp(`^Returns a new ${m[1]}$`, "i").test(says) || sameWords(says.replace(/^Returns a new /, ""), m[1]) ? null : WHY.unparsed;
4465
+ if (trailing && step.children?.length && /^(?:Calls (.+) with these steps|Returns the result of (.+))$/.test(says)) {
4466
+ const header = String(code3).replace(/\{\s*(?:\[[^\]]*\]\s*)?(?:\(?[\w\s,$]*\)?\s+in)?\s*$/, "").trim();
4467
+ const last = /([A-Za-z_]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\))?\s*$/.exec(header)?.[1];
4468
+ const named2 = says.replace(/^Calls (.+) with these steps$/, "$1").replace(/^Returns the result of /, "");
4469
+ if (last && !KEYWORD_CALLEE.test(last) && sameWords(last, named2)) return null;
4470
+ }
4471
+ if ((m = /^(?:(?:let|const|static|var|val|final|readonly)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*("(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?|true|false)\s*;?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(" ")} to ${m[2]}`) return null;
4472
+ if ((m = /^(?:(?:let|const|static|var|val)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*(?:r#*)?"(?:\\.|[^"\\])*\\?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(" ")} to a text written over several lines`) return null;
4473
+ if (m = /^(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)/.exec(c)) {
4474
+ const w = /^Loads (.+) from (\S+)$/.exec(says);
4475
+ return w && w[2] === m[2] && m[1].split(",").every((x) => x.trim() && ` ${splitWords(w[1]).join(" ")} `.includes(` ${splitWords(x.split(":").pop()).join(" ")} `)) ? null : WHY.unparsed;
4476
+ }
4477
+ if (step.kind === "loop" && (m = /^for\s+_\s+in\s+([\w.]+)$/.exec(c))) return new RegExp(`^Repeats once for each item in (?:the [\\w ]+'s )?${splitWords(m[1].split(".").pop()).join(" ")}(?: \\(\\d+ steps? inside\\))?$`).test(says) ? null : WHY.unparsed;
4478
+ if (m = /^([\w.]+)\s*=\s*\.(\w+)$/.exec(c)) {
4479
+ const w = /^Sets (?:the [\w ]+'s )?(.+?) to (.+)$/.exec(says);
4480
+ return w && sameWords(w[1], m[1].split(".").pop()) && sameWords(w[2], m[2]) ? null : WHY.unparsed;
4481
+ }
4482
+ if (step.kind === "return" && /^Returns the result of /.test(says) && /^return\s+[\w.]+(?:\s*\((?:[^()]|\([^()]*\))*\)\s*\.?\s*[\w.]*)*$/.test(c)) {
4483
+ const last = /([A-Za-z_]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\))?\s*$/.exec(c)?.[1];
4484
+ if (last && !KEYWORD_CALLEE.test(last) && sameWords(last, says.replace(/^Returns the result of /, ""))) return null;
4485
+ }
4486
+ if ((m = /^([A-Za-z_]\w*)\s*:$/.exec(c)) && says === `The "${m[1]}" part starts here`) return null;
4487
+ if (step.kind === "loop" && (m = /^for\s+(\w+)\s+in\s+(-?\d+)\s*(\.\.<|\.\.\.)\s*(-?\d+)$/.exec(c))) {
4488
+ const hi = m[3] === "..<" ? Number(m[4]) - 1 : Number(m[4]);
4489
+ return new RegExp(`^Counts ${splitWords(m[1]).join(" ")} from ${m[2]} to ${hi}(?: \\(\\d+ steps? inside\\))?$`).test(says) ? null : WHY.unparsed;
4490
+ }
4491
+ if (step.kind === "return" && /^return\s*;?$/.test(c)) return /^Stops here$/.test(says) ? null : WHY.unparsed;
4492
+ if ((m = /^Handles (GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ALL) (\S+) with these steps$/.exec(says)) && new RegExp(`\\.(?:${m[1].toLowerCase()}|${m[1]}|route|all|use)\\s*\\(`).test(c)) {
4493
+ const parts = m[2].split("/").filter(Boolean);
4494
+ return parts.every((x) => c.includes(x)) ? null : WHY.unparsed;
4495
+ }
4496
+ if (step.kind === "branch" && (m = /^guard\s+(?!let\b|var\b|case\b)(.+?)\s+else(?:\s*\{.*)?$/.exec(c))) {
4497
+ const w = /^If not: (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
4498
+ const test = w && parseExpr(m[1], "swift");
4499
+ return test ? conditionCore(test, w[1], m[1], "swift") : WHY.unparsed;
4500
+ }
4501
+ if (/^Calls .+ with these steps$/.test(says) && step.children?.length && (m = /^\s*(?:await\s+)?([A-Za-z_][\w]*(?:\s*(?:\.|->|::|\?\.)\s*[A-Za-z_][\w]*)*)\s*[({]/.exec(c))) {
4502
+ const named2 = /^Calls (.+?) with these steps$/.exec(says)[1];
4503
+ if (!KEYWORD_CALLEE.test(lastName(m[1])) && sameWords(lastName(m[1].replace(/\?\./g, ".")), named2)) return null;
4504
+ }
4505
+ if (/^Calls /.test(says) && (m = SAFE_CALL.exec(c)) && balancedTail(c, c.indexOf("(", m.index + m[0].length - 1))) {
4506
+ const named2 = /^Calls (.+?)(?: \(only in builds where.*\))?$/.exec(says)?.[1] ?? "";
4507
+ return !KEYWORD_CALLEE.test(lastName(m[1])) && sameWords(lastName(m[1]), named2) ? null : WHY.unparsed;
4508
+ }
4509
+ if (/^Works out /.test(says) && (m = SAFE_ASSIGN.exec(c)) && balancedTail(c, c.indexOf("(", m.index + m[0].length - 1))) {
4510
+ const w = /^Works out (.+?)(?: from (.+?))?(?: \(only in builds where.*\))?$/.exec(says);
4511
+ const target = lastName(m[1]);
4512
+ if (!w || KEYWORD_CALLEE.test(lastName(m[2]))) return WHY.unparsed;
4513
+ const tw = w[1].replace(/^the (?:[\w ]+?'s )?/, "");
4514
+ if (!sameWords(target, tw) && !sameWords(m[1].replace(/->/g, "."), w[1])) return WHY.unparsed;
4515
+ if (w[2] && !sameWords(lastName(m[2]), w[2])) return WHY.unparsed;
4516
+ return null;
4517
+ }
4518
+ if (step.kind === "return" && (m = /^return\s+(?:\([A-Za-z_][\w\s*]*\)\s*)?(?:await\s+)?([A-Za-z_][\w]*(?:\s*(?:\.|->|::)\s*[A-Za-z_][\w]*)*)\s*(\()?/.exec(c))) {
4519
+ const name = lastName(m[1]);
4520
+ if (m[2] && balancedTail(c, c.indexOf("(", m.index + m[0].length - 1))) return new RegExp(`^Returns the result of ${splitWords(name).join(" ")}(?: \\(only in builds where.*\\))?$`).test(says) && !KEYWORD_CALLEE.test(name) ? null : WHY.unparsed;
4521
+ if (!m[2] && /^return\s+[A-Za-z_][\w]*\s*;?$/.test(c)) return new RegExp(`^Returns ${splitWords(name).join(" ")}(?: \\(only in builds where.*\\))?$`).test(says) ? null : WHY.unparsed;
4522
+ }
4523
+ if (step.kind === "return" && (m = /^return\s+(-?\d+|true|false|null|NULL|nil|nullptr)\s*;?$/.exec(c))) return says === `Returns ${m[1]}` || new RegExp(`^Returns ${m[1]}\\b`).test(says) ? null : WHY.unparsed;
4524
+ if (step.kind === "fail" && /^(?:throw|raise)\b/.test(c)) return null;
4525
+ if (step.kind === "branch" && (m = /^(guard)\s+(?:let|var)\s+(\w+)(?:\s*=\s*(.+?))?\s+(else\b.*)$/.exec(c) || /^(if)\s+(?:let|var)\s+(\w+)(?:\s*=\s*([^,{]+?))?\s*()$/.exec(c))) {
4526
+ const w = /^If (not: )?(.+?) is set(?: \(\d+ steps? inside\))?$/.exec(says);
4527
+ if (!w || !!w[1] !== (m[1] === "guard")) return WHY.unparsed;
4528
+ return sameWords(w[2], m[2]) || m[3] && /^[\w.]+$/.test(m[3]) && sameWords(w[2], m[3].split(".").pop()) ? null : WHY.unparsed;
4529
+ }
4530
+ if (/^(?:goto)\s+\w+\s*;?$/.test(c) && /^Jumps to the "\w+" part$/.test(says)) return null;
4531
+ if (/^(?:break|continue)\s*;?$/.test(c)) return null;
4532
+ return WHY.unparsed;
4533
+ }
4534
+ function implicitReturnOk(step, ctx, code3) {
4535
+ if (!IMPLICIT_RETURN_LANGS.has(ctx.lang)) return false;
4536
+ if (ctx.only) return !/\b(?:unless|if|while|until)\b/.test(code3) || ctx.lang === "kotlin" || ctx.lang === "rust" || ctx.lang === "scala";
4537
+ if (!ctx.last) return false;
4538
+ if (ctx.exprValue) return true;
4539
+ if (ctx.lang === "swift") return !!ctx.singleTop;
4540
+ if (!/^(?:ruby|rust|scala|r|elixir|powershell)$/.test(ctx.lang) && !(ctx.lang === "kotlin" && ctx.inLambda)) return false;
4541
+ if (ctx.lang === "ruby" && /\s(?:unless|if|while|until|rescue)\s/.test(code3)) return false;
4542
+ if (ctx.lang === "rust" && /;\s*$/.test(code3)) return false;
4543
+ return true;
4544
+ }
4545
+ function sourceOf(step, ctx) {
4546
+ const short5 = String(step.code ?? "");
4547
+ const sp = step.span;
4548
+ if (!sp || !ctx.lines || step.kind === "check") return short5;
4549
+ if (isBlock(step) || step.nested || step.children?.length) {
4550
+ let head2 = short5;
4551
+ if (sp.startLine >= 1 && !/[{:]\s*$|\b(?:then|do)\s*$/.test(String(ctx.lines[sp.startLine - 1] ?? ""))) {
4552
+ const hl = [];
4553
+ for (let l = sp.startLine; l <= Math.min(sp.endLine, sp.startLine + 5); l++) {
4554
+ const t = ctx.lines[l - 1] ?? "";
4555
+ hl.push(t);
4556
+ if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break;
4557
+ }
4558
+ head2 = hl.join("\n");
4559
+ }
4560
+ const last = ctx.lines[(sp.endLine ?? 0) - 1];
4561
+ return last != null && sp.endLine > sp.startLine ? `${head2}
4562
+ ${last}` : head2;
4563
+ }
4564
+ const a = sp.startLine, b = sp.endLine;
4565
+ if (!(a >= 1 && b >= a && b - a < 8)) return short5;
4566
+ const text2 = ctx.lines.slice(a - 1, b).join("\n");
4567
+ const head = short5.replace(/…$/, "").replace(/\s+/g, " ").trim().slice(0, 40);
4568
+ return text2.replace(/\s+/g, " ").includes(head) ? text2 : short5;
4569
+ }
4570
+ var lineOf = (s) => s?.line ?? s?.span?.startLine ?? null;
4571
+ var endOf = (s) => s?.span?.endLine ?? s?.line ?? null;
4572
+ var isEnding = (s) => s.kind === "return" || s.kind === "fail" || s.jump === "break" || s.jump === "continue";
4573
+ var isBlock = (s) => s.kind === "branch" || s.kind === "loop" || s.kind === "try";
4574
+ function* everyStep(list3) {
4575
+ for (const s of list3 || []) {
4576
+ yield s;
4577
+ yield* everyStep(s.children);
4578
+ yield* everyStep(s.otherwise);
4579
+ for (const h of s.handlers || []) yield* everyStep(h.steps);
4580
+ if (s.always) yield* everyStep(s.always.steps);
4581
+ }
4582
+ }
4583
+ function structureProblem(s, lang, srcLines) {
4584
+ const a = lineOf(s), b = endOf(s);
4585
+ const inner = [...s.children || [], ...s.otherwise || []];
4586
+ if (s.kind === "branch" && !inner.length && !s.unread && !/^(?:Chooses by|Checks these cases)/.test(String(s.says))) return true;
4587
+ if (s.kind === "branch" && /^(?:swift|kotlin|rust|go|scala)$/.test(lang) && s.children?.length && s.children.every((c) => c.kind === "check" && c.caseLabel) && s.children.some((c) => !c.children?.length && !/fall/i.test(String(c.says)) && !/(?:=>|->)\s*(?:\{\s*\}|\(\s*\)|Unit)\s*,?\s*$|\bbreak\b/.test(String(c.code ?? "")))) return true;
4588
+ if (s.kind === "branch" && s.children?.length && s.children.every((c) => c.kind === "check" && c.caseLabel)) {
4589
+ for (const arm of s.children) for (const k of everyStep(arm.children)) if (!k.nested && /^\s*(?:case\b|default\s*:|when\b)/.test(String(k.code ?? ""))) return true;
4590
+ }
4591
+ if (a != null && b != null && b > a) {
4592
+ for (const k of everyStep(s.children)) {
4593
+ const l = lineOf(k);
4594
+ if (l != null && (l < a || l > b + 0)) return true;
4595
+ }
4596
+ }
4597
+ if (srcLines && a != null && b != null && /\{\s*(?:\/\/.*|\/\*.*\*\/)?$/.test(String(srcLines[a - 1] ?? "")) && isBlock(s) && !["python", "ruby", "shell", "powershell", "r", "sql"].includes(lang)) {
4598
+ const close = braceClose(srcLines, a);
4599
+ if (close != null) for (const k of everyStep(s.children)) {
4600
+ const l = lineOf(k);
4601
+ if (l != null && l > close) return true;
4602
+ }
4603
+ }
4604
+ return false;
4605
+ }
4606
+ function braceClose(lines, at2) {
4607
+ let depth = 0, base2 = null;
4608
+ for (let l = at2 - 1; l < lines.length && l < at2 + 2e3; l++) {
4609
+ const t = lines[l] ?? "";
4610
+ for (let i = 0; i < t.length; i++) {
4611
+ const ch = t[i];
4612
+ if (ch === "/" && t[i + 1] === "/") break;
4613
+ if (ch === '"' || ch === "'" || ch === "`") {
4614
+ const q = ch;
4615
+ for (i++; i < t.length && t[i] !== q; i++) if (t[i] === "\\") i++;
4616
+ continue;
4617
+ }
4618
+ if (ch === "{") depth++;
4619
+ else if (ch === "}") {
4620
+ depth--;
4621
+ if (base2 != null && depth < base2) return l + 1;
4622
+ }
4623
+ }
4624
+ if (base2 == null) {
4625
+ if (depth <= 0) return null;
4626
+ base2 = depth;
4627
+ }
4628
+ }
4629
+ return null;
4630
+ }
4631
+ var keepOriginal = (s) => {
4632
+ if (!("origSays" in s)) Object.defineProperty(s, "origSays", { value: s.says, enumerable: false });
4633
+ };
4634
+ var PAREN_IF = /* @__PURE__ */ new Set(["c", "cpp", "java", "csharp", "javascript", "typescript", "php", "kotlin", "scala", "dart", "r", "powershell"]);
4635
+ var currentLines = null;
4636
+ var squash = (t) => String(t).replace(/\s+/g, "");
4637
+ function exactCode(s) {
4638
+ const sp = s.span;
4639
+ if (!currentLines || !sp?.startLine) return;
4640
+ const end = Math.min(sp.endLine ?? sp.startLine, sp.startLine + 7);
4641
+ const text2 = currentLines.slice(sp.startLine - 1, end).join(" ");
4642
+ const short5 = String(s.code ?? "").replace(/…$/, "");
4643
+ const block = isBlock(s) || s.children?.length;
4644
+ if (block && short5.trim()) {
4645
+ let head2 = "";
4646
+ for (let l = sp.startLine; l <= Math.min(end, sp.startLine + 5); l++) {
4647
+ const t = String(currentLines[l - 1] ?? "");
4648
+ head2 += ` ${t}`;
4649
+ if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break;
4650
+ }
4651
+ if (squash(head2).includes(squash(short5)) && squash(head2).length > squash(short5).length + 2 && !/[{:]\s*$|\b(?:then|do)\s*$/.test(String(currentLines[sp.startLine - 1] ?? ""))) {
4652
+ s.code = head2.replace(/\s+/g, " ").trim();
4653
+ return;
4654
+ }
4655
+ }
4656
+ if (!short5.trim() || squash(text2).includes(squash(short5))) return;
4657
+ let head = "";
4658
+ if (block) for (let l = sp.startLine; l <= Math.min(end, sp.startLine + 5); l++) {
4659
+ const t = String(currentLines[l - 1] ?? "");
4660
+ head += ` ${t}`;
4661
+ if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break;
4662
+ }
4663
+ s.code = (block ? head : text2).replace(/\s+/g, " ").trim();
4664
+ }
4665
+ function asCode(s, why) {
4666
+ keepOriginal(s);
4667
+ exactCode(s);
4668
+ s.explained = false;
4669
+ s.notExplainedWhy = why;
4670
+ const code3 = String(s.code ?? s.says ?? "").replace(/\s+/g, " ").trim();
4671
+ if (s.kind === "branch" && !(s.children?.length && s.children.every((c) => c.kind === "check" && c.caseLabel))) {
4672
+ const head = code3.replace(/\s*\{\s*$/, "").replace(/\s*(?:then|do|:)\s*$/, "");
4673
+ const m = /^(?:\}\s*)?(?:else\s*)?(if|elif|elsif|else if|while|unless|guard)\s*(.*)$/.exec(head);
4674
+ if (m && m[2]) {
4675
+ let cond = m[2].trim();
4676
+ if (PAREN_IF.has(currentLang) && /^\(/.test(cond) && closeIdx(cond, 0) > 0) cond = cond.slice(1, closeIdx(cond, 0)).trim();
4677
+ const neg = m[1] === "unless" || m[1] === "guard";
4678
+ if (m[1] === "guard") cond = cond.replace(/\s+else\b[^]*$/, "");
4679
+ s.says = `If ${neg ? "not: " : ""}${asCodeWords(cond)}`;
4680
+ } else {
4681
+ s.kind = "other";
4682
+ s.says = asCodeWords(code3);
4683
+ }
4684
+ return;
4685
+ }
4686
+ if (s.kind === "branch") {
4687
+ s.says = asCodeWords(code3);
4688
+ s.codeWords = true;
4689
+ return;
4690
+ }
4691
+ if (s.kind === "check") {
4692
+ s.says = asCodeWords(code3.replace(/\s*\{\s*$/, ""));
4693
+ s.codeWords = true;
4694
+ return;
4695
+ }
4696
+ if (s.kind === "loop") {
4697
+ s.says = `Repeats: ${asCodeWords(code3.replace(/\s*\{\s*$/, ""))}`;
4698
+ s.codeWords = true;
4699
+ return;
4700
+ }
4701
+ if (s.kind === "return" && why !== WHY.ending) {
4702
+ s.restates = true;
4703
+ s.says = asCodeWords(code3);
4704
+ return;
4705
+ }
4706
+ if (s.kind === "fail" && why !== WHY.ending) {
4707
+ s.says = `Fails with ${asCodeWords(code3)}`;
4708
+ s.codeWords = true;
4709
+ return;
4710
+ }
4711
+ if (s.kind === "try") {
4712
+ s.says = asCodeWords(code3);
4713
+ s.codeWords = true;
4714
+ return;
4715
+ }
4716
+ s.kind = "other";
4717
+ s.says = asCodeWords(code3);
4718
+ }
4719
+ function closeIdx(s, open) {
4720
+ let d = 0;
4721
+ for (let i = open; i < s.length; i++) {
4722
+ if (s[i] === "(") d++;
4723
+ else if (s[i] === ")" && --d === 0) return i;
4724
+ }
4725
+ return -1;
4726
+ }
4727
+ function regionAsCode(s, why) {
4728
+ keepOriginal(s);
4729
+ const head = String(s.code ?? s.says ?? "").replace(/\s+/g, " ").trim();
4730
+ for (const k of ["children", "otherwise", "handlers", "always"]) delete s[k];
4731
+ s.kind = "other";
4732
+ s.says = asCodeWords(head);
4733
+ s.explained = false;
4734
+ s.notExplainedWhy = why;
4735
+ delete s.jump;
4736
+ if (DEBUG) console.error(`[say-less] ${why} | ${s.origSays} | ${String(s.code).slice(0, 120)}`);
4737
+ }
4738
+ var alreadyCode = (s) => s.kind === "other" || s.restates || s.codeWords || isCodeWords(String(s.says ?? "").replace(/^(?:If (?:not: )?|Repeats: |Fails with )/, "").replace(/ \(\d+ steps? inside\)$/, ""));
4739
+ function lengthWords(says, tree) {
4740
+ if (!/\bhow many\b|\.length\b|\.Length\b/.test(String(says))) return says;
4741
+ const lengths = /* @__PURE__ */ new Set();
4742
+ for (const n of nodesOf2(tree)) {
4743
+ if (n.kind === "member" && /^(?:length|Length|size|Count|count)$/.test(n.property)) lengths.add(splitWords(sayFullName(n.object)).join(" "));
4744
+ if (n.kind === "call" && /^(?:len|length|size|count|nchar|strlen|Count|Length)$/.test(n.callee?.property ?? n.callee?.name ?? "")) {
4745
+ const o = n.callee?.kind === "member" ? n.callee.object : n.args?.[0];
4746
+ if (o) lengths.add(splitWords(sayFullName(o)).join(" "));
4747
+ }
4748
+ }
4749
+ if (!lengths.size) return says;
4750
+ return String(says).split(/("(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»)/).map((part, i) => i % 2 ? part : part.replace(/\bhow many ((?:the [\w ]+?'s )?[\w ]+?)(?= is\b| are\b| has\b|,|$| and\b| or\b| plus\b| minus\b| to\b| from\b| times\b|\))/g, (m, x) => lengths.has(splitWords(x.replace(/^the /, "").replace(/'s /g, " ")).join(" ")) || lengths.has(splitWords(x).join(" ")) ? `the length of ${x}` : m).replace(/\b([A-Za-z_][\w]*)\.(?:length|Length)\b(?!\s*\()/g, (m, x) => `the length of ${x}`)).join("");
4751
+ }
4752
+ var sayFullName = (n) => n?.kind === "name" ? n.name : n?.kind === "member" ? `${sayFullName(n.object)} ${n.property}` : "";
4753
+ function valueTarget(s) {
4754
+ if (typeof s.valueOf === "string") return s.valueOf;
4755
+ if (s.kind !== "branch") return null;
4756
+ const m = /^\s*(?:(?:val|var|let|const|auto|my|local)\s+)?([A-Za-z_$][\w$.]*)\s*(?::[^=]+)?=\s*(?:when|switch|match|case|if|select)\b/.exec(String(s.code ?? ""));
4757
+ return m ? m[1] : null;
4758
+ }
4759
+ function sayLessList(list3, ctx, depth, top) {
4760
+ let ended = false, endedImplicit = false;
4761
+ for (let i = 0; i < (list3?.length ?? 0); i++) {
4762
+ const s = list3[i];
4763
+ if (ended && (/^\s*[A-Za-z_]\w*\s*:\s*$/.test(String(s.code ?? "")) || /^The "\w+" part starts here$/.test(String(s.says)))) ended = false;
4764
+ if (ended && s.kind === "return" && /^Stops here$/.test(String(s.says)) && /^\s*return\s*;?\s*$/.test(String(s.code ?? ""))) {
4765
+ s.explained = true;
4766
+ continue;
4767
+ }
4768
+ if (ended && /^Defines (?:a helper|how)\b/.test(String(s.says))) ended = false;
4769
+ if (ended && top && endedImplicit) {
4770
+ list3.length = i;
4771
+ break;
4772
+ }
4773
+ if (ended) {
4774
+ regionAsCode(s, WHY.structure);
4775
+ continue;
4776
+ }
4777
+ if (/^\s*\}?\s*(?:else|elseif|elsif|elif|catch|finally|rescue|ensure)\b(?!\s*(?:->|=>|:\s*$))/.test(String(s.code ?? "")) && s.kind !== "branch" && s.kind !== "check" && !s.caseLabel) {
4778
+ regionAsCode(s, WHY.structure);
4779
+ const prev = list3[i - 1];
4780
+ if (prev && prev.kind === "branch" && prev.explained !== false) regionAsCode(prev, WHY.structure);
4781
+ continue;
4782
+ }
4783
+ if (isBlock(s) && structureProblem(s, ctx.lang, ctx.lines)) {
4784
+ const empty = s.kind === "branch" && !s.children?.length && !s.otherwise?.length;
4785
+ regionAsCode(s, WHY.structure);
4786
+ if (empty && list3[i + 1]) {
4787
+ regionAsCode(list3[i + 1], WHY.structure);
4788
+ i++;
4789
+ }
4790
+ continue;
4791
+ }
4792
+ const last = top && i === list3.length - 1;
4793
+ if (!alreadyCode(s)) {
4794
+ lastTag = null;
4795
+ const sc = Object.create(ctx);
4796
+ sc.last = last || ctx.lastPath && i === list3.length - 1;
4797
+ sc.only = top && list3.length === 1;
4798
+ const why = checkStep(s, sc);
4799
+ if (why) {
4800
+ asCode(s, why);
4801
+ if (lastTag) Object.defineProperty(s, "whyTag", { value: lastTag, enumerable: false });
4802
+ if (DEBUG) console.error(`[say-less] ${why}${lastTag ? ` ${lastTag}` : ""} | ${s.origSays} | ${String(s.code).slice(0, 120)}`);
4803
+ } else {
4804
+ s.explained = true;
4805
+ s.says = lengthWords(s.says, s.expr);
4806
+ }
4807
+ } else {
4808
+ s.explained = false;
4809
+ const before = s.code;
4810
+ exactCode(s);
4811
+ if (s.code !== before && (s.kind === "other" || s.restates)) s.says = asCodeWords(s.code);
4812
+ if (!s.notExplainedWhy) s.notExplainedWhy = s.restates && s.kind === "return" && s.expr && s.expr.kind !== "code" ? WHY.form : s.expr?.kind === "code" ? WHY.unparsed : WHY.form;
4813
+ }
4814
+ if (!s.children && !s.otherwise && !s.handlers && !s.always) {
4815
+ if (isEnding(s) && s.kind !== "other") {
4816
+ ended = true;
4817
+ endedImplicit = i === 0 && s.kind === "return" && !/^\s*return\b/.test(String(s.code ?? ""));
4818
+ }
4819
+ continue;
4820
+ }
4821
+ const valueOf2 = /^\s*return\s+(?:when|switch|match|if|case)\b|^\s*return\s+\S.*\b(?:switch|match)\s*\{|^\s*=\s*(?:when|if)\b/.test(String(s.code ?? ""));
4822
+ const lastPath = (ctx.lastPath || top) && i === list3.length - 1 || s.kind === "check" && s.caseLabel && ctx.armsLast || valueOf2;
4823
+ const armsLast = s.kind === "branch" && lastPath;
4824
+ const inner = { ...ctx, lastPath, armsLast, exprValue: ctx.exprValue || valueOf2, ...valueTarget(s) ? { valueTarget: valueTarget(s) } : {} };
4825
+ if (s.kind === "loop" && !/^\s*(?:for|foreach|while|until|do|loop|repeat)\b/.test(String(s.code ?? "")) && s.children) {
4826
+ for (const k of everyStep(s.children)) if ((k.kind === "return" || k.kind === "fail") && !k.nested) regionAsCode(k, WHY.structure);
4827
+ }
4828
+ if (s.children) sayLessList(s.children, s.nested ? { ...ctx, lastPath: false, armsLast: false, exprValue: false, inLambda: true } : inner, depth + 1, !!s.nested);
4829
+ if (s.otherwise) sayLessList(s.otherwise, inner, depth + 1, false);
4830
+ for (const h of s.handlers || []) sayLessList(h.steps, inner, depth + 1, false);
4831
+ if (s.always) sayLessList(s.always.steps, { ...ctx, lastPath: false }, depth + 1, false);
4832
+ if (isEnding(s) && s.kind !== "other") ended = true;
4833
+ }
4834
+ }
4835
+ var INFRA = /* @__PURE__ */ new Set(["dockerfile", "github-actions", "terraform", "bicep", "kubernetes", "docker-compose"]);
4836
+ function markOnly(list3) {
4837
+ for (const s of everyStep(list3)) {
4838
+ if (alreadyCode(s)) {
4839
+ s.explained = false;
4840
+ s.notExplainedWhy ??= WHY.form;
4841
+ } else s.explained = true;
4842
+ }
4843
+ }
4844
+ function certainlyYesNo(text2, lang) {
4845
+ const valueLogic2 = /^(?:javascript|typescript|python|ruby)$/.test(lang);
4846
+ const t = parseExpr(String(text2 ?? ""), lang);
4847
+ if (!t) return !valueLogic2;
4848
+ const yesNo = (n) => {
4849
+ if (!n) return false;
4850
+ switch (n.kind) {
4851
+ case "compare":
4852
+ case "chain":
4853
+ case "not":
4854
+ return true;
4855
+ case "literal":
4856
+ return n.type === "bool";
4857
+ case "logic":
4858
+ return valueLogic2 ? n.operands.every(yesNo) : true;
4859
+ case "call": {
4860
+ const name = n.callee?.kind === "member" ? n.callee.property : n.callee?.name;
4861
+ return /^(?:is|has|can|should|does|did|was|are|needs?|contains|includes|exists|matches|equals|starts|ends|any|all|every|some|isinstance|is_a\?|kind_of\?|[a-z_]+\?)/i.test(String(name ?? "")) || /\?$/.test(String(name ?? ""));
4862
+ }
4863
+ case "name":
4864
+ case "member": {
4865
+ const w = n.kind === "name" ? n.name : n.property;
4866
+ return !valueLogic2 && /^(?:is|has|can|should)[A-Z_]/.test(String(w));
4867
+ }
4868
+ default:
4869
+ return false;
4870
+ }
4871
+ };
4872
+ return yesNo(t);
4873
+ }
4874
+ function checkInputs(item2, lang, srcLines) {
4875
+ if (!item2.inputs?.length || ["shell", "sql"].includes(lang)) return;
4876
+ const ids = /* @__PURE__ */ new Set();
4877
+ const take = (a, b) => {
4878
+ for (const id of stripQuoted(srcLines.slice(a, b).join("\n")).match(/[A-Za-z_][\w.]*/g) || []) {
4879
+ ids.add(id);
4880
+ if (id.includes(".")) for (const part of id.split(".")) ids.add(part);
4881
+ }
4882
+ };
4883
+ const at2 = Math.max(0, (item2.line ?? 1) - 1);
4884
+ take(at2, at2 + 3);
4885
+ if (item2.inputs.some((p) => !ids.has(String(p.name ?? "").replace(/^[$@&*]+/, "").replace(/\.\.\.$/, "")))) take(at2 + 3, at2 + 13);
4886
+ item2.inputs = item2.inputs.filter((p) => {
4887
+ const n = String(p.name ?? "");
4888
+ const bare2 = n.replace(/^[$@&*]+/, "").replace(/\.\.\.$/, "");
4889
+ if (/^[{[(][^]*[}\])]$/.test(bare2)) {
4890
+ const names = bare2.match(/[A-Za-z_]\w*/g) || [];
4891
+ if (names.length && names.every((x) => ids.has(x))) return true;
4892
+ item2.inputsDropped = (item2.inputsDropped ?? 0) + 1;
4893
+ return false;
4894
+ }
4895
+ if (!/^[A-Za-z_][\w.]*$/.test(bare2)) {
4896
+ item2.inputsDropped = (item2.inputsDropped ?? 0) + 1;
4897
+ return false;
4898
+ }
4899
+ if ((lang === "c" || lang === "cpp") && /^[A-Z][A-Z0-9_]{2,}$/.test(bare2)) {
4900
+ item2.inputsDropped = (item2.inputsDropped ?? 0) + 1;
4901
+ return false;
4902
+ }
4903
+ if (!ids.has(bare2)) {
4904
+ item2.inputsDropped = (item2.inputsDropped ?? 0) + 1;
4905
+ return false;
4906
+ }
4907
+ return true;
4908
+ });
4909
+ }
4910
+ function sayLess(reading, source) {
4911
+ const lang = reading?.language;
4912
+ if (!reading?.items || !lang) return reading;
4913
+ const lines = String(source ?? "").split("\n");
4914
+ const ownFunctions = new Set(reading.items.filter((it) => it.kind === "function" || it.kind === "decision").map((it) => it.name));
4915
+ const helperExits = /* @__PURE__ */ new Map();
4916
+ if (lang === "shell") for (const m of String(source ?? "").matchAll(/^\s*(?:function\s+)?([\w-]+)\s*\(\)\s*\{[^}\n]*\bexit\s+(\d+)\s*;?\s*\}/gm)) helperExits.set(m[1], m[2]);
4917
+ for (const it of reading.items) {
4918
+ if (it.kind !== "function" && it.kind !== "decision") continue;
4919
+ if (!INFRA.has(lang)) checkInputs(it, lang, lines);
4920
+ if (!it.steps?.length) continue;
4921
+ currentLines = lines;
4922
+ currentLang = lang;
4923
+ if (lang === "sql" || INFRA.has(lang)) markOnly(it.steps);
4924
+ else {
4925
+ const ownNames = new Set((it.inputs || []).map((p) => String(p.name).replace(/^[$@&*]+/, "")));
4926
+ const collect = (l) => {
4927
+ for (const s of l || []) {
4928
+ const e = s.expr;
4929
+ if (e?.kind === "assign" && e.declare && e.target?.kind === "name") ownNames.add(e.target.name);
4930
+ if (s.children) collect(s.children);
4931
+ if (s.otherwise) collect(s.otherwise);
4932
+ }
4933
+ };
4934
+ collect(it.steps);
4935
+ sayLessList(it.steps, { lang, lines, helperExits, ownNames, ownFunctions, singleTop: it.steps.length === 1 }, 0, true);
4936
+ }
4937
+ let total = 0, explained = 0;
4938
+ for (const s of everyStep(it.steps)) {
4939
+ total++;
4940
+ if (s.explained !== false) explained++;
4941
+ }
4942
+ it.totalSteps = total;
4943
+ it.explainedSteps = explained;
4944
+ if (it.stepsReadable != null) it.stepsReadable = Math.round(it.steps.filter((x) => x.explained !== false).length / it.steps.length * 100) / 100;
4945
+ }
4946
+ return reading;
4947
+ }
4948
+
3427
4949
  // src/sql-proc.mjs
3428
4950
  var plainName = (x) => words(String(x).replace(/^@+/, "").replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, ""));
3429
4951
  var unq = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/s, "$1");
@@ -3665,7 +5187,7 @@ function targetWords(text2, ctx) {
3665
5187
  }
3666
5188
  var code2 = (text2) => String(text2).replace(/('(?:[^']|'')*')|--([^\n]*)/g, (m, str3, note) => str3 ?? `/*${note.replace(/\*\//g, "* /")} */`).replace(/\s+/g, " ").trim();
3667
5189
  var setPair = (target, v, rawT, rawV) => target === v && rawT.trim() !== rawV.trim() ? `\`${rawT.trim()}\` to \`${rawV.trim()}\`` : `${target} to ${v}`;
3668
- var asCode = (text2, base2) => ({ kind: "other", says: code2(text2), code: code2(text2), restates: code2(text2), ...base2 });
5190
+ var asCode2 = (text2, base2) => ({ kind: "other", says: code2(text2), code: code2(text2), restates: code2(text2), ...base2 });
3669
5191
  function splitComma(ts) {
3670
5192
  const out = [[]];
3671
5193
  let d = 0;
@@ -3734,9 +5256,9 @@ function statementStep(ts, text2, base2, ctx) {
3734
5256
  const using = topWord(ts, ["USING"], k + 1);
3735
5257
  const argTs = ts.slice(k + 1, using < 0 ? ts.length : using);
3736
5258
  const args = isP(argTs[0], ",") ? splitComma(argTs.slice(1)).map((p) => ctx.src.slice(p[0].s, p.at(-1).e).trim()) : [];
3737
- if (argTs.length && !isP(argTs[0], ",")) return level === "EXCEPTION" ? fail2("an error", { message: null }) : asCode(t, base2);
5259
+ if (argTs.length && !isP(argTs[0], ",")) return level === "EXCEPTION" ? fail2("an error", { message: null }) : asCode2(t, base2);
3738
5260
  message2 = raiseMessage(strText(fmt), args);
3739
- if (message2 == null) return level === "EXCEPTION" ? { ...fail2("an error"), says: `Fails with an error: ${asCodeWords(t)}` } : asCode(t, base2);
5261
+ if (message2 == null) return level === "EXCEPTION" ? { ...fail2("an error"), says: `Fails with an error: ${asCodeWords(t)}` } : asCode2(t, base2);
3740
5262
  }
3741
5263
  if (level === "EXCEPTION") {
3742
5264
  if (message2 != null) return fail2(`an error: "${message2}"`, { message: message2 });
@@ -3744,7 +5266,7 @@ function statementStep(ts, text2, base2, ctx) {
3744
5266
  return fail2("an error (its message is worked out when it runs)");
3745
5267
  }
3746
5268
  if (message2 != null) return { kind: "call", says: `${level === "WARNING" ? "Warns" : "Writes a message"}: "${message2}"`, code: t, ...base2 };
3747
- return asCode(t, base2);
5269
+ return asCode2(t, base2);
3748
5270
  }
3749
5271
  if (up === "SIGNAL" || up === "RESIGNAL") {
3750
5272
  if (up === "RESIGNAL" && ts.length === 1) return fail2("the same error again: passes it on", { error: "the same error" });
@@ -3773,70 +5295,70 @@ function statementStep(ts, text2, base2, ctx) {
3773
5295
  const args = close > 0 ? splitComma(ts.slice(2, close)) : [];
3774
5296
  const sev = args[1]?.length === 1 && args[1][0].t === "num" ? Number(args[1][0].v) : null;
3775
5297
  const m = args[0]?.length === 1 && args[0][0].t === "str" ? `"${strText(args[0][0])}"` : args[0] ? targetWords(ctx.src.slice(args[0][0].s, args[0].at(-1).e), ctx) ? `the text in ${targetWords(ctx.src.slice(args[0][0].s, args[0].at(-1).e), ctx)}` : null : null;
3776
- if (sev == null || !m) return asCode(t, base2);
5298
+ if (sev == null || !m) return asCode2(t, base2);
3777
5299
  if (sev <= 10) return { kind: "call", says: `Writes a message: ${m}`, code: t, ...base2 };
3778
5300
  if (sev >= 20 || ctx.inTry) return fail2(m.startsWith('"') ? `an error: ${m}` : `an error whose message is ${m}`, m.startsWith('"') ? { message: m.slice(1, -1) } : {});
3779
5301
  return { kind: "call", says: `Reports an error and carries on (unless a TRY \u2026 CATCH that called it catches the error): ${m}`, code: t, ...base2 };
3780
5302
  }
3781
5303
  if (up === "PRINT") {
3782
5304
  const v = valueWords(restText(1), ctx, rest2);
3783
- return v ? { kind: "call", says: `Writes a message: ${v}`, code: t, ...base2 } : asCode(t, base2);
5305
+ return v ? { kind: "call", says: `Writes a message: ${v}`, code: t, ...base2 } : asCode2(t, base2);
3784
5306
  }
3785
5307
  if ((up === "PERFORM" || up === "CALL") && isW(at2(1))) {
3786
5308
  let k = 1;
3787
5309
  while (isP(at2(k + 1), ".") && isW(at2(k + 2))) k += 2;
3788
5310
  if (isP(at2(k + 1), "(") && matchParen(ts, k + 1) === ts.length - 1) return { kind: "call", says: `Runs ${words(unq(at2(k).v))}`, callee: unq(at2(k).v), code: t, ...base2 };
3789
- return asCode(t, base2);
5311
+ return asCode2(t, base2);
3790
5312
  }
3791
5313
  if (up === "EXEC" || up === "EXECUTE") {
3792
5314
  if (ctx.dialect === "pg") {
3793
5315
  const into = topWord(ts, ["INTO"]);
3794
- if (topWord(ts, ["USING"]) >= 0 || ts.length < 2) return asCode(t, base2);
5316
+ if (topWord(ts, ["USING"]) >= 0 || ts.length < 2) return asCode2(t, base2);
3795
5317
  const what = sqlTextWords(ts.slice(1, into < 0 ? ts.length : into), ctx);
3796
- if (!what) return asCode(t, base2);
5318
+ if (!what) return asCode2(t, base2);
3797
5319
  let keep2 = "";
3798
5320
  if (into >= 0) {
3799
5321
  const strict = isW(ts[into + 1], "STRICT") ? 1 : 0;
3800
5322
  const targets = splitComma(ts.slice(into + 1 + strict)).map((p) => targetWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx));
3801
- if (!targets.length || !targets.every(Boolean)) return asCode(t, base2);
5323
+ if (!targets.length || !targets.every(Boolean)) return asCode2(t, base2);
3802
5324
  keep2 = `, and keeps what it gives back in ${listWords(targets)}`;
3803
5325
  }
3804
5326
  return { kind: "call", says: `Runs the SQL ${what}${keep2}`, code: t, ...base2 };
3805
5327
  }
3806
5328
  if (ctx.dialect === "mysql") {
3807
5329
  if (isW(at2(1)) && (ts.length === 2 || isW(at2(2), "USING"))) return { kind: "call", says: `Runs the prepared statement ${at2(1).v}`, code: t, ...base2 };
3808
- return asCode(t, base2);
5330
+ return asCode2(t, base2);
3809
5331
  }
3810
- if (isW(at2(1), "AS")) return asCode(t, base2);
5332
+ if (isW(at2(1), "AS")) return asCode2(t, base2);
3811
5333
  if (isP(at2(1), "(")) {
3812
5334
  const close = matchParen(ts, 1);
3813
5335
  const inner = close === ts.length - 1 ? ts.slice(2, close) : null;
3814
5336
  const vw = inner && inner.length === 1 && inner[0].t === "word" ? targetWords(inner[0].v, ctx) : null;
3815
- return vw ? { kind: "call", says: `Runs the SQL text in ${vw}`, code: t, ...base2 } : asCode(t, base2);
5337
+ return vw ? { kind: "call", says: `Runs the SQL text in ${vw}`, code: t, ...base2 } : asCode2(t, base2);
3816
5338
  }
3817
5339
  let k = 1, keep = null;
3818
5340
  if (isW(at2(1)) && /^@/.test(at2(1).v) && isP(at2(2), "=")) {
3819
5341
  keep = targetWords(at2(1).v, ctx);
3820
5342
  k = 3;
3821
5343
  }
3822
- if (!isW(at2(k))) return asCode(t, base2);
5344
+ if (!isW(at2(k))) return asCode2(t, base2);
3823
5345
  let name = at2(k).v;
3824
5346
  let j = k;
3825
5347
  while (isP(at2(j + 1), ".") && isW(at2(j + 2))) {
3826
5348
  j += 2;
3827
5349
  name = at2(j).v;
3828
5350
  }
3829
- if (/^@/.test(at2(k).v) && j === k && !keep) return asCode(t, base2);
5351
+ if (/^@/.test(at2(k).v) && j === k && !keep) return asCode2(t, base2);
3830
5352
  if (/^sp_executesql$/i.test(unq(name))) {
3831
5353
  const first = at2(j + 1);
3832
5354
  const vw = first && first.t === "word" && (!at2(j + 2) || isP(at2(j + 2), ",")) ? targetWords(first.v, ctx) : null;
3833
- return vw ? { kind: "call", says: `Runs the SQL text in ${vw}`, code: t, ...base2 } : asCode(t, base2);
5355
+ return vw ? { kind: "call", says: `Runs the SQL text in ${vw}`, code: t, ...base2 } : asCode2(t, base2);
3834
5356
  }
3835
5357
  return { kind: "call", says: `Runs ${words(unq(name))}${keep ? ` and keeps its return code in ${keep}` : ""}`, callee: unq(name), code: t, ...base2 };
3836
5358
  }
3837
5359
  if (up === "PREPARE" && ctx.dialect === "mysql" && isW(at2(1)) && isW(at2(2), "FROM")) {
3838
5360
  const v = valueWords(restText(3), ctx, ts.slice(3));
3839
- return v ? { kind: "call", says: `Prepares the statement ${at2(1).v} from ${v}`, code: t, ...base2 } : asCode(t, base2);
5361
+ return v ? { kind: "call", says: `Prepares the statement ${at2(1).v} from ${v}`, code: t, ...base2 } : asCode2(t, base2);
3840
5362
  }
3841
5363
  if ((up === "DEALLOCATE" || up === "DROP") && isW(at2(1), "PREPARE") && isW(at2(2)) && ts.length === 3) return { kind: "call", says: `Frees the prepared statement ${at2(2).v}`, code: t, ...base2 };
3842
5364
  if (up === "DEALLOCATE" && ctx.dialect === "tsql" && ts.length === 2 && isW(at2(1))) return { kind: "call", says: `Frees the cursor ${at2(1).v}`, code: t, ...base2 };
@@ -3851,12 +5373,12 @@ function statementStep(ts, text2, base2, ctx) {
3851
5373
  const targets = splitComma(ts.slice(into + 1)).map((p) => p.length === 1 ? targetWords(p[0].v, ctx) : null);
3852
5374
  if (targets.every(Boolean)) return { kind: "call", says: `Takes the next row of ${cur.v} into ${listWords(targets)}`, code: t, ...base2 };
3853
5375
  }
3854
- return asCode(t, base2);
5376
+ return asCode2(t, base2);
3855
5377
  }
3856
5378
  if (up === "GET" && ctx.dialect === "pg") {
3857
5379
  const m = t.match(/^GET\s+(?:CURRENT\s+)?DIAGNOSTICS\s+([\w.]+)\s*(?::=|=)\s*ROW_COUNT$/i);
3858
5380
  if (m && targetWords(m[1], ctx)) return { kind: "set", says: `Sets ${targetWords(m[1], ctx)} to how many rows the last statement changed`, code: t, ...base2 };
3859
- return asCode(t, base2);
5381
+ return asCode2(t, base2);
3860
5382
  }
3861
5383
  if (up === "SET" && ctx.dialect !== "pg") {
3862
5384
  const parts = splitComma(rest2);
@@ -3867,11 +5389,11 @@ function statementStep(ts, text2, base2, ctx) {
3867
5389
  let j = k;
3868
5390
  while (isP(p[j + 1], ".") && isW(p[j + 2])) j += 2;
3869
5391
  const op = p[j + 1];
3870
- if (!isW(p[k]) || !(isP(op, "=") || isP(op, ":="))) return [asCode(t, base2)];
5392
+ if (!isW(p[k]) || !(isP(op, "=") || isP(op, ":="))) return [asCode2(t, base2)];
3871
5393
  const target = targetWords(ctx.src.slice(p[k].s, p[j].e), ctx);
3872
5394
  const vts = p.slice(j + 2);
3873
5395
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
3874
- if (!target || !v || k) return [asCode(t, base2)];
5396
+ if (!target || !v || k) return [asCode2(t, base2)];
3875
5397
  sets.push(setPair(target, v, ctx.src.slice(p[k].s, p[j].e), ctx.src.slice(vts[0].s, vts.at(-1).e)));
3876
5398
  }
3877
5399
  return { kind: "set", says: `Sets ${listWords(sets)}`, code: t, ...base2 };
@@ -3886,7 +5408,7 @@ function statementStep(ts, text2, base2, ctx) {
3886
5408
  const vts = ts.slice(j + 2);
3887
5409
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
3888
5410
  if (target && v) return { kind: "set", says: `Sets ${setPair(target, v, ctx.src.slice(at2(0).s, at2(j).e), ctx.src.slice(vts[0].s, vts.at(-1).e))}`, code: t, ...base2 };
3889
- return asCode(t, base2);
5411
+ return asCode2(t, base2);
3890
5412
  }
3891
5413
  }
3892
5414
  }
@@ -3895,22 +5417,22 @@ function statementStep(ts, text2, base2, ctx) {
3895
5417
  const set = topWord(ts, ["SET"]);
3896
5418
  let tEnd = 1;
3897
5419
  while (isP(at2(tEnd + 1), ".") && isW(at2(tEnd + 2))) tEnd += 2;
3898
- if (!isW(at2(1)) || set !== tEnd + 1 && !(set === tEnd + 2 && isW(at2(tEnd + 1)))) return asCode(t, base2);
3899
- if (topWord(ts, ["FROM", "RETURNING", "OUTPUT", "JOIN", "ORDER", "LIMIT", "WHERE CURRENT"], set) >= 0) return asCode(t, base2);
5420
+ if (!isW(at2(1)) || set !== tEnd + 1 && !(set === tEnd + 2 && isW(at2(tEnd + 1)))) return asCode2(t, base2);
5421
+ if (topWord(ts, ["FROM", "RETURNING", "OUTPUT", "JOIN", "ORDER", "LIMIT", "WHERE CURRENT"], set) >= 0) return asCode2(t, base2);
3900
5422
  const where = topWord(ts, ["WHERE"], set);
3901
5423
  const setTs = ts.slice(set + 1, where < 0 ? ts.length : where);
3902
5424
  const sets = [];
3903
5425
  for (const p of splitComma(setTs)) {
3904
5426
  const eq2 = p.findIndex((x) => isP(x, "="));
3905
- if (eq2 < 1) return asCode(t, base2);
5427
+ if (eq2 < 1) return asCode2(t, base2);
3906
5428
  const target = targetWords(ctx.src.slice(p[0].s, p[eq2 - 1].e), { ...ctx, dialect: "pg" });
3907
5429
  const vts = p.slice(eq2 + 1);
3908
5430
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
3909
- if (!target || !v) return asCode(t, base2);
5431
+ if (!target || !v) return asCode2(t, base2);
3910
5432
  sets.push(`${target.replace(/^the .*'s /, "")} to ${v}`);
3911
5433
  }
3912
5434
  const w = where < 0 ? "" : condWords(ctx.src.slice(at2(where + 1).s, ts.at(-1).e), ctx);
3913
- if (w == null) return asCode(t, base2);
5435
+ if (w == null) return asCode2(t, base2);
3914
5436
  return { kind: "call", says: `Records the change in ${words(bare(ctx.src.slice(at2(1).s, at2(tEnd).e)))}: sets ${listWords(sets)}${where < 0 ? " in every row" : ` where ${w}`}`, code: t, ...base2 };
3915
5437
  }
3916
5438
  if (up === "DELETE" && isW(at2(1), "FROM") && isW(at2(2))) {
@@ -3918,18 +5440,18 @@ function statementStep(ts, text2, base2, ctx) {
3918
5440
  while (isP(at2(j + 1), ".") && isW(at2(j + 2))) j += 2;
3919
5441
  const table = words(bare(ctx.src.slice(at2(2).s, at2(j).e)));
3920
5442
  if (ts.length === j + 1) return { kind: "call", says: `Removes every row in ${table}`, code: t, ...base2 };
3921
- if (!isW(at2(j + 1), "WHERE") || topWord(ts, ["USING", "RETURNING", "OUTPUT", "JOIN", "FROM", "ORDER", "LIMIT"], j + 1) >= 0) return asCode(t, base2);
5443
+ if (!isW(at2(j + 1), "WHERE") || topWord(ts, ["USING", "RETURNING", "OUTPUT", "JOIN", "FROM", "ORDER", "LIMIT"], j + 1) >= 0) return asCode2(t, base2);
3922
5444
  const w = condWords(ctx.src.slice(at2(j + 2).s, ts.at(-1).e), ctx);
3923
- return w ? { kind: "call", says: `Removes ${table} where ${w}`, code: t, ...base2 } : asCode(t, base2);
5445
+ return w ? { kind: "call", says: `Removes ${table} where ${w}`, code: t, ...base2 } : asCode2(t, base2);
3924
5446
  }
3925
5447
  if (up === "TRUNCATE") {
3926
5448
  const k = isW(at2(1), "TABLE") ? 2 : 1;
3927
5449
  let j = k;
3928
5450
  while (isP(at2(j + 1), ".") && isW(at2(j + 2))) j += 2;
3929
5451
  if (isW(at2(k)) && ts.length === j + 1) return { kind: "call", says: `Removes every row in ${words(bare(ctx.src.slice(at2(k).s, at2(j).e)))}`, code: t, ...base2 };
3930
- return asCode(t, base2);
5452
+ return asCode2(t, base2);
3931
5453
  }
3932
- return asCode(t, base2);
5454
+ return asCode2(t, base2);
3933
5455
  }
3934
5456
  function matchParen(ts, k) {
3935
5457
  for (let d = 0, j = k; j < ts.length; j++) {
@@ -3945,39 +5467,39 @@ function selectStatement(ts, t, base2, ctx) {
3945
5467
  if (from < 0 && into < 0) {
3946
5468
  const sets = [];
3947
5469
  for (const p of splitComma(ts.slice(1))) {
3948
- if (!(p[0]?.t === "word" && /^@/.test(p[0].v) && isP(p[1], "="))) return asCode(t, base2);
5470
+ if (!(p[0]?.t === "word" && /^@/.test(p[0].v) && isP(p[1], "="))) return asCode2(t, base2);
3949
5471
  const v = valueWords(ctx.src.slice(p[2]?.s ?? 0, p.at(-1).e), ctx, p.slice(2));
3950
- if (!p[2] || !v) return asCode(t, base2);
5472
+ if (!p[2] || !v) return asCode2(t, base2);
3951
5473
  sets.push(`${targetWords(p[0].v, ctx)} to ${v}`);
3952
5474
  }
3953
- return sets.length ? { kind: "set", says: `Sets ${listWords(sets)}`, code: t, ...base2 } : asCode(t, base2);
5475
+ return sets.length ? { kind: "set", says: `Sets ${listWords(sets)}`, code: t, ...base2 } : asCode2(t, base2);
3954
5476
  }
3955
- return asCode(t, base2);
5477
+ return asCode2(t, base2);
3956
5478
  }
3957
- if (into < 0) return asCode(t, base2);
3958
- if (into > from && from > 0) return asCode(t, base2);
5479
+ if (into < 0) return asCode2(t, base2);
5480
+ if (into > from && from > 0) return asCode2(t, base2);
3959
5481
  const strict = isW(ts[into + 1], "STRICT") ? 1 : 0;
3960
5482
  const targetTs = ts.slice(into + 1 + strict, from < 0 ? ts.length : from);
3961
5483
  const targets = splitComma(targetTs).map((p) => targetWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx));
3962
5484
  const cols = splitComma(ts.slice(1, into));
3963
- if (!targets.length || !targets.every(Boolean) || !cols.length) return asCode(t, base2);
5485
+ if (!targets.length || !targets.every(Boolean) || !cols.length) return asCode2(t, base2);
3964
5486
  if (from < 0) {
3965
- if (cols.length !== targets.length) return asCode(t, base2);
5487
+ if (cols.length !== targets.length) return asCode2(t, base2);
3966
5488
  const vals = cols.map((p) => valueWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx, p));
3967
- if (!vals.every(Boolean)) return asCode(t, base2);
5489
+ if (!vals.every(Boolean)) return asCode2(t, base2);
3968
5490
  return { kind: "set", says: `Sets ${listWords(targets.map((x, k2) => `${x} to ${vals[k2]}`))}`, code: t, ...base2 };
3969
5491
  }
3970
5492
  let j = from + 1;
3971
- if (!isW(ts[j])) return asCode(t, base2);
5493
+ if (!isW(ts[j])) return asCode2(t, base2);
3972
5494
  while (isP(ts[j + 1], ".") && isW(ts[j + 2])) j += 2;
3973
5495
  const table = words(bare(ctx.src.slice(ts[from + 1].s, ts[j].e)));
3974
5496
  let k = j + 1;
3975
5497
  if (isW(ts[k], "AS")) k++;
3976
5498
  if (isW(ts[k]) && !isW(ts[k], "WHERE")) k++;
3977
- if (k < ts.length && !isW(ts[k], "WHERE")) return asCode(t, base2);
3978
- if (topWord(ts, ["GROUP", "ORDER", "LIMIT", "HAVING", "UNION", "OFFSET", "FOR", "JOIN", "WINDOW", "FETCH"], from) >= 0) return asCode(t, base2);
5499
+ if (k < ts.length && !isW(ts[k], "WHERE")) return asCode2(t, base2);
5500
+ if (topWord(ts, ["GROUP", "ORDER", "LIMIT", "HAVING", "UNION", "OFFSET", "FOR", "JOIN", "WINDOW", "FETCH"], from) >= 0) return asCode2(t, base2);
3979
5501
  const w = k < ts.length ? condWords(ctx.src.slice(ts[k + 1].s, ts.at(-1).e), ctx) : "";
3980
- if (w == null) return asCode(t, base2);
5502
+ if (w == null) return asCode2(t, base2);
3981
5503
  const colWords2 = cols.map((p) => {
3982
5504
  if (p.length === 1 && isW(p[0])) return words(unq(p[0].v));
3983
5505
  if (p.length === 3 && isW(p[0]) && isP(p[1], ".") && isW(p[2])) return words(unq(p[2].v));
@@ -3988,23 +5510,23 @@ function selectStatement(ts, t, base2, ctx) {
3988
5510
  }
3989
5511
  return null;
3990
5512
  });
3991
- if (!colWords2.every(Boolean) || colWords2.length !== targets.length) return asCode(t, base2);
5513
+ if (!colWords2.every(Boolean) || colWords2.length !== targets.length) return asCode2(t, base2);
3992
5514
  const where = w ? ` where ${w}` : "";
3993
5515
  const same = colWords2.every((c, n) => c === targets[n]);
3994
5516
  return { kind: "call", callee: "find", says: same ? `Finds ${listWords(targets)} in the ${table}${where}` : `Finds ${listWords(colWords2)} in the ${table}${where}, as ${listWords(targets)}`, code: t, ...base2 };
3995
5517
  }
3996
5518
  function insertStatement(ts, t, base2, ctx) {
3997
- if (!isW(ts[1], "INTO") || !isW(ts[2])) return asCode(t, base2);
3998
- if (topWord(ts, ["ON", "RETURNING", "OUTPUT", "IGNORE"]) >= 0) return asCode(t, base2);
5519
+ if (!isW(ts[1], "INTO") || !isW(ts[2])) return asCode2(t, base2);
5520
+ if (topWord(ts, ["ON", "RETURNING", "OUTPUT", "IGNORE"]) >= 0) return asCode2(t, base2);
3999
5521
  let j = 2;
4000
5522
  while (isP(ts[j + 1], ".") && isW(ts[j + 2])) j += 2;
4001
5523
  const table = bare(ctx.src.slice(ts[2].s, ts[j].e));
4002
5524
  let k = j + 1, cols = [];
4003
5525
  if (isP(ts[k], "(")) {
4004
5526
  const close = matchParen(ts, k);
4005
- if (close < 0) return asCode(t, base2);
5527
+ if (close < 0) return asCode2(t, base2);
4006
5528
  cols = splitComma(ts.slice(k + 1, close)).map((p) => p.length === 1 && isW(p[0]) ? words(unq(p[0].v)) : null);
4007
- if (!cols.every(Boolean)) return asCode(t, base2);
5529
+ if (!cols.every(Boolean)) return asCode2(t, base2);
4008
5530
  k = close + 1;
4009
5531
  }
4010
5532
  const withCols = cols.length ? ` with ${listWords(cols)}` : "";
@@ -4013,7 +5535,7 @@ function insertStatement(ts, t, base2, ctx) {
4013
5535
  return { kind: "call", says: rows.length === 1 ? `Records a new ${singular(words(table))}${withCols}` : `Records ${rows.length} new ${words(table)}${withCols}`, code: t, ...base2 };
4014
5536
  }
4015
5537
  if (isW(ts[k], "SELECT", "WITH")) return { kind: "call", says: `Records in ${words(table)} the rows a query finds${withCols}`, code: t, ...base2 };
4016
- return asCode(t, base2);
5538
+ return asCode2(t, base2);
4017
5539
  }
4018
5540
  var TSQL_START = new Set("SELECT INSERT UPDATE DELETE SET DECLARE IF ELSE WHILE BEGIN END RETURN EXEC EXECUTE PRINT RAISERROR THROW CREATE DROP ALTER TRUNCATE MERGE OPEN FETCH CLOSE DEALLOCATE BREAK CONTINUE GOTO WAITFOR USE GRANT REVOKE DENY COMMIT ROLLBACK SAVE DBCC BULK BACKUP RESTORE KILL RECONFIGURE CHECKPOINT WITH".split(" "));
4019
5541
  function bodySteps(toks, ctx, opts = {}) {
@@ -4021,12 +5543,12 @@ function bodySteps(toks, ctx, opts = {}) {
4021
5543
  const n = toks.length;
4022
5544
  const labels = [];
4023
5545
  const peek = (k = 0) => toks[i + k];
4024
- const lineOf5 = (tok) => ctx.lineAt(tok.s);
4025
- const baseOf = (a, b) => ({ line: lineOf5(toks[a]), span: { startLine: lineOf5(toks[a]), endLine: lineOf5(toks[Math.max(a, b - 1)]) } });
5546
+ const lineOf6 = (tok) => ctx.lineAt(tok.s);
5547
+ const baseOf = (a, b) => ({ line: lineOf6(toks[a]), span: { startLine: lineOf6(toks[a]), endLine: lineOf6(toks[Math.max(a, b - 1)]) } });
4026
5548
  const textOf3 = (a, b) => ctx.src.slice(toks[a].s, toks[b - 1].e);
4027
5549
  const semi = ctx.dialect !== "tsql";
4028
5550
  const expect = (cond, what) => {
4029
- if (!cond) throw new Unmatched(`${what} (line ${peek() ? lineOf5(peek()) : "end"})`);
5551
+ if (!cond) throw new Unmatched(`${what} (line ${peek() ? lineOf6(peek()) : "end"})`);
4030
5552
  };
4031
5553
  const skipSemis = () => {
4032
5554
  while (isP(peek(), ";")) i++;
@@ -4204,7 +5726,7 @@ function bodySteps(toks, ctx, opts = {}) {
4204
5726
  kids2 = bodySteps(inner, { ...ctx, depth: 1 });
4205
5727
  } catch (err) {
4206
5728
  if (!(err instanceof Unmatched)) throw err;
4207
- kids2 = [asCode(t.v, baseOf(a, a + 1))];
5729
+ kids2 = [asCode2(t.v, baseOf(a, a + 1))];
4208
5730
  }
4209
5731
  if (t.version == null) return kids2;
4210
5732
  const v = `${Math.floor(t.version / 1e4)}.${Math.floor(t.version / 100) % 100}.${t.version % 100}`;
@@ -4214,7 +5736,7 @@ function bodySteps(toks, ctx, opts = {}) {
4214
5736
  const e2 = simpleEnd(a);
4215
5737
  i = Math.max(e2, a + 1);
4216
5738
  if (isP(peek(), ";")) i++;
4217
- return [asCode(textOf3(a, Math.max(e2, a + 1)), baseOf(a, Math.max(e2, a + 1)))];
5739
+ return [asCode2(textOf3(a, Math.max(e2, a + 1)), baseOf(a, Math.max(e2, a + 1)))];
4218
5740
  }
4219
5741
  const up = t.up;
4220
5742
  if (up === "IF" && semi) {
@@ -4222,19 +5744,19 @@ function bodySteps(toks, ctx, opts = {}) {
4222
5744
  const [c0, c1] = condUntil((x) => isW(x, "THEN"));
4223
5745
  i++;
4224
5746
  const step2 = branch(c0, c1, block(endsWith("ELSIF", "ELSEIF", "ELSE", "END")));
4225
- step2.line = lineOf5(toks[a]);
5747
+ step2.line = lineOf6(toks[a]);
4226
5748
  let tail = step2;
4227
5749
  while (isW(peek(), "ELSIF", "ELSEIF")) {
4228
5750
  const at2 = i;
4229
5751
  i++;
4230
5752
  const [e0, e1] = condUntil((x) => isW(x, "THEN"));
4231
5753
  i++;
4232
- const next = branch(e0, e1, block(endsWith("ELSIF", "ELSEIF", "ELSE", "END")), null, lineOf5(toks[at2]));
5754
+ const next = branch(e0, e1, block(endsWith("ELSIF", "ELSEIF", "ELSE", "END")), null, lineOf6(toks[at2]));
4233
5755
  tail.otherwise = [next];
4234
5756
  tail = next;
4235
5757
  }
4236
5758
  if (isW(peek(), "ELSE")) {
4237
- tail.otherwiseLine = lineOf5(peek());
5759
+ tail.otherwiseLine = lineOf6(peek());
4238
5760
  i++;
4239
5761
  tail.otherwise = block(endsWith("END"));
4240
5762
  }
@@ -4247,9 +5769,9 @@ function bodySteps(toks, ctx, opts = {}) {
4247
5769
  const kids2 = tsqlBody();
4248
5770
  skipSemis();
4249
5771
  const step2 = branch(c0, c1, kids2);
4250
- step2.line = lineOf5(toks[a]);
5772
+ step2.line = lineOf6(toks[a]);
4251
5773
  if (isW(peek(), "ELSE")) {
4252
- step2.otherwiseLine = lineOf5(peek());
5774
+ step2.otherwiseLine = lineOf6(peek());
4253
5775
  i++;
4254
5776
  step2.otherwise = tsqlBody();
4255
5777
  }
@@ -4273,7 +5795,7 @@ function bodySteps(toks, ctx, opts = {}) {
4273
5795
  expect(arms.length, "CASE without WHEN");
4274
5796
  let elseKids = null, elseLine = null;
4275
5797
  if (isW(peek(), "ELSE")) {
4276
- elseLine = lineOf5(peek());
5798
+ elseLine = lineOf6(peek());
4277
5799
  i++;
4278
5800
  elseKids = block(endsWith("END"));
4279
5801
  }
@@ -4286,14 +5808,14 @@ function bodySteps(toks, ctx, opts = {}) {
4286
5808
  text2 = vals.length === 1 ? `${subj} = ${vals[0]}` : `${subj} IN (${vals.join(", ")})`;
4287
5809
  } else text2 = code2(textOf3(arm.w0, arm.w1));
4288
5810
  const w = condWords(text2, ctx);
4289
- return { kind: "branch", says: `If ${w ?? asCodeWords(text2, 400)}`, code: text2, cond: text2, line: lineOf5(toks[arm.at]), span: { startLine: lineOf5(toks[arm.at]), endLine: lineOf5(toks[arm.w1 - 1]) }, children: arm.kids };
5811
+ return { kind: "branch", says: `If ${w ?? asCodeWords(text2, 400)}`, code: text2, cond: text2, line: lineOf6(toks[arm.at]), span: { startLine: lineOf6(toks[arm.at]), endLine: lineOf6(toks[arm.w1 - 1]) }, children: arm.kids };
4290
5812
  });
4291
5813
  for (let k = 0; k < steps.length - 1; k++) steps[k].otherwise = [steps[k + 1]];
4292
5814
  const last = steps.at(-1);
4293
5815
  if (elseKids) {
4294
5816
  last.otherwise = elseKids;
4295
5817
  last.otherwiseLine = elseLine;
4296
- } else last.otherwise = [{ kind: "fail", says: "Fails with an error: no WHEN matched and there is no ELSE (case not found)", error: "case not found", code: code2(textOf3(a, i)), line: lineOf5(toks[a]) }];
5818
+ } else last.otherwise = [{ kind: "fail", says: "Fails with an error: no WHEN matched and there is no ELSE (case not found)", error: "case not found", code: code2(textOf3(a, i)), line: lineOf6(toks[a]) }];
4297
5819
  return [steps[0]];
4298
5820
  }
4299
5821
  if (up === "LOOP" && semi) {
@@ -4378,7 +5900,7 @@ function bodySteps(toks, ctx, opts = {}) {
4378
5900
  const e2 = simpleEnd(a + 1);
4379
5901
  i = e2;
4380
5902
  if (isP(peek(), ";")) i++;
4381
- return [asCode(textOf3(a, e2), baseOf(a, e2))];
5903
+ return [asCode2(textOf3(a, e2), baseOf(a, e2))];
4382
5904
  }
4383
5905
  if (!semi && isW(peek(1), "TRY")) {
4384
5906
  i += 2;
@@ -4389,7 +5911,7 @@ function bodySteps(toks, ctx, opts = {}) {
4389
5911
  closeWith("TRY", "BEGIN TRY");
4390
5912
  skipSemis();
4391
5913
  expect(isW(peek(), "BEGIN") && isW(peek(1), "CATCH"), "BEGIN TRY without BEGIN CATCH");
4392
- const hLine = lineOf5(peek());
5914
+ const hLine = lineOf6(peek());
4393
5915
  i += 2;
4394
5916
  const handler = block(endsWith("END"));
4395
5917
  closeWith("CATCH", "BEGIN CATCH");
@@ -4412,7 +5934,7 @@ function bodySteps(toks, ctx, opts = {}) {
4412
5934
  i++;
4413
5935
  const names = toks.slice(c0, c1).filter((x) => !isW(x, "OR", "SQLSTATE")).map((x) => x.t === "str" ? `error ${strText(x)}` : words(x.v));
4414
5936
  const any = toks.slice(c0, c1).some((x) => isW(x, "OTHERS"));
4415
- handlers.push({ says: any ? "If anything goes wrong" : `If ${names.join(" or ")} goes wrong`, line: lineOf5(toks[hAt]), steps: block(endsWith("WHEN", "END")) });
5937
+ handlers.push({ says: any ? "If anything goes wrong" : `If ${names.join(" or ")} goes wrong`, line: lineOf6(toks[hAt]), steps: block(endsWith("WHEN", "END")) });
4416
5938
  }
4417
5939
  }
4418
5940
  ctx.depth--;
@@ -4441,7 +5963,7 @@ function bodySteps(toks, ctx, opts = {}) {
4441
5963
  const target = targetWords(ts2[0].v, ctx);
4442
5964
  const vts = ts2.slice(at2 + 1);
4443
5965
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
4444
- out.push(target && v ? { kind: "set", says: `Sets ${setPair(target, v, ts2[0].v, ctx.src.slice(vts[0].s, vts.at(-1).e))}`, code: code2(textOf3(d0, d0 + ts2.length)), ...baseOf(d0, d0 + ts2.length) } : asCode(textOf3(d0, d0 + ts2.length), baseOf(d0, d0 + ts2.length)));
5966
+ out.push(target && v ? { kind: "set", says: `Sets ${setPair(target, v, ts2[0].v, ctx.src.slice(vts[0].s, vts.at(-1).e))}`, code: code2(textOf3(d0, d0 + ts2.length)), ...baseOf(d0, d0 + ts2.length) } : asCode2(textOf3(d0, d0 + ts2.length), baseOf(d0, d0 + ts2.length)));
4445
5967
  }
4446
5968
  return out;
4447
5969
  }
@@ -4486,7 +6008,7 @@ function bodySteps(toks, ctx, opts = {}) {
4486
6008
  const after = kind === "CONTINUE" ? "then carries on after the statement that caused it" : "then leaves the block it is declared in";
4487
6009
  const base2 = baseOf(a, Math.max(h0, i));
4488
6010
  if (simple) return [{ kind: "call", says: `From here on, whenever ${conds.join(" or ")}: ${lower1(kids2[0].says)}, ${after}`, code: code2(textOf3(a, i)), ...base2 }];
4489
- return [asCode(textOf3(a, i), base2)];
6011
+ return [asCode2(textOf3(a, i), base2)];
4490
6012
  }
4491
6013
  const e2 = simpleEnd(a);
4492
6014
  const ts = toks.slice(a + 1, e2);
@@ -4503,7 +6025,7 @@ function bodySteps(toks, ctx, opts = {}) {
4503
6025
  const vts = ts.slice(def + 1);
4504
6026
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
4505
6027
  const targets = names.map((x) => targetWords(x, ctx));
4506
- if (!v || !targets.every(Boolean)) return [asCode(textOf3(a, e2), baseOf(a, e2))];
6028
+ if (!v || !targets.every(Boolean)) return [asCode2(textOf3(a, e2), baseOf(a, e2))];
4507
6029
  return [{ kind: "set", says: `Sets ${listWords(targets)} to ${v}`, code: code2(textOf3(a, e2)), ...baseOf(a, e2) }];
4508
6030
  }
4509
6031
  if (isW(ts[1], "CURSOR")) return [];
@@ -4514,7 +6036,7 @@ function bodySteps(toks, ctx, opts = {}) {
4514
6036
  const target = targetWords(p[0].v, ctx);
4515
6037
  const vts = p.slice(eq2 + 1);
4516
6038
  const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
4517
- if (!target || !v) return [asCode(textOf3(a, e2), baseOf(a, e2))];
6039
+ if (!target || !v) return [asCode2(textOf3(a, e2), baseOf(a, e2))];
4518
6040
  sets.push(setPair(target, v, p[0].v, ctx.src.slice(vts[0].s, vts.at(-1).e)));
4519
6041
  }
4520
6042
  return sets.length ? [{ kind: "set", says: `Sets ${listWords(sets)}`, code: code2(textOf3(a, e2)), ...baseOf(a, e2) }] : [];
@@ -4530,9 +6052,9 @@ function bodySteps(toks, ctx, opts = {}) {
4530
6052
  if (isP(peek(), ";")) i++;
4531
6053
  return [{ kind: "call", says: `Jumps to ${toks[a + 1]?.v ?? "a label"}`, code: code2(textOf3(a, e2)), jump: "break", ...baseOf(a, e2) }];
4532
6054
  }
4533
- if (!semi && (up === "ELSE" || up === "END")) throw new Unmatched(`${up} without its IF or BEGIN (line ${lineOf5(t)})`);
4534
- if (semi && (up === "ELSE" || up === "ELSIF" || up === "ELSEIF" || up === "WHEN" || up === "UNTIL" || up === "EXCEPTION")) throw new Unmatched(`${up} outside its block (line ${lineOf5(t)})`);
4535
- if (semi && up === "END" && !ctx.allowEnd) throw new Unmatched(`END without its BEGIN (line ${lineOf5(t)})`);
6055
+ if (!semi && (up === "ELSE" || up === "END")) throw new Unmatched(`${up} without its IF or BEGIN (line ${lineOf6(t)})`);
6056
+ if (semi && (up === "ELSE" || up === "ELSIF" || up === "ELSEIF" || up === "WHEN" || up === "UNTIL" || up === "EXCEPTION")) throw new Unmatched(`${up} outside its block (line ${lineOf6(t)})`);
6057
+ if (semi && up === "END" && !ctx.allowEnd) throw new Unmatched(`END without its BEGIN (line ${lineOf6(t)})`);
4536
6058
  const e = Math.max(simpleEnd(a), a + 1);
4537
6059
  i = e;
4538
6060
  if (isP(peek(), ";")) i++;
@@ -4557,7 +6079,7 @@ var ROUTINE_WORDS = ["FUNCTION", "PROCEDURE", "PROC"];
4557
6079
  function sqlRoutines(src, lineAt3, dialect = sqlDialect(src)) {
4558
6080
  const toks = lexSql(src, 0, src.length, dialect);
4559
6081
  const out = [];
4560
- const lineOf5 = (k) => lineAt3(toks[Math.min(k, toks.length - 1)].s);
6082
+ const lineOf6 = (k) => lineAt3(toks[Math.min(k, toks.length - 1)].s);
4561
6083
  for (let k = 0; k < toks.length; k++) {
4562
6084
  const start = k;
4563
6085
  let j = k;
@@ -4742,8 +6264,8 @@ function sqlRoutines(src, lineAt3, dialect = sqlDialect(src)) {
4742
6264
  steps = [];
4743
6265
  }
4744
6266
  if (dialect === "tsql" || dialect === "mysql") end = bodyEnd;
4745
- const endLine = lineOf5(Math.max(end, start));
4746
- out.push({ name, line: lineOf5(start), endLine, kind: routine, inputs, outs, returns, setof, trigger, steps, ...unreadWhy ? { unreadWhy } : {}, headerEnd: lineOf5(Math.max(start, j - 1)) });
6267
+ const endLine = lineOf6(Math.max(end, start));
6268
+ out.push({ name, line: lineOf6(start), endLine, kind: routine, inputs, outs, returns, setof, trigger, steps, ...unreadWhy ? { unreadWhy } : {}, headerEnd: lineOf6(Math.max(start, j - 1)) });
4747
6269
  k = Math.max(k, Math.min(end, toks.length - 1));
4748
6270
  }
4749
6271
  return out;
@@ -8936,8 +10458,8 @@ function readTerraform(src, file = "main.tf") {
8936
10458
  if (count) {
8937
10459
  const c = count.value;
8938
10460
  const cond = c.t === "cond" ? c : null;
8939
- if (cond && isZero(cond.no)) step = { kind: "branch", says: question(conditionWords(cond.test, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
8940
- else if (cond && isZero(cond.yes)) step = { kind: "branch", says: question(conditionWords({ t: "unary", op: "!", x: cond.test }, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
10461
+ if (cond && isZero2(cond.no)) step = { kind: "branch", says: question(conditionWords(cond.test, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
10462
+ else if (cond && isZero2(cond.yes)) step = { kind: "branch", says: question(conditionWords({ t: "unary", op: "!", x: cond.test }, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
8941
10463
  else if (c.t === "num") {
8942
10464
  if (c.v === 0) step.says += " (none: count is 0)";
8943
10465
  else if (c.v !== 1) step.says = `${verb} ${c.v} of ${what}${inWords}`;
@@ -8973,11 +10495,11 @@ function readTerraform(src, file = "main.tf") {
8973
10495
  const top = comments.find((c) => c.line === 1);
8974
10496
  return { items, things, settings, facts, links, permissions, unknowns, purpose: top && top.text && !/^(disable|tflint)/.test(top.text) ? top.text : null };
8975
10497
  }
8976
- var isZero = (n) => n?.t === "num" && n.v === 0;
10498
+ var isZero2 = (n) => n?.t === "num" && n.v === 0;
8977
10499
  function countWords(n, refWords) {
8978
10500
  if (n.t === "num") return n.v === 0 ? "none (count is 0)" : String(n.v);
8979
- if (n.t === "cond" && isZero(n.no)) return `${n.yes.t === "num" ? n.yes.v === 1 ? "one" : n.yes.v : valueText(n.yes, refWords).text}, only when ${conditionWords(n.test, refWords)}`;
8980
- if (n.t === "cond" && isZero(n.yes)) return `${n.no.t === "num" ? n.no.v === 1 ? "one" : n.no.v : valueText(n.no, refWords).text}, only when ${conditionWords({ t: "unary", op: "!", x: n.test }, refWords)}`;
10501
+ if (n.t === "cond" && isZero2(n.no)) return `${n.yes.t === "num" ? n.yes.v === 1 ? "one" : n.yes.v : valueText(n.yes, refWords).text}, only when ${conditionWords(n.test, refWords)}`;
10502
+ if (n.t === "cond" && isZero2(n.yes)) return `${n.no.t === "num" ? n.no.v === 1 ? "one" : n.no.v : valueText(n.no, refWords).text}, only when ${conditionWords({ t: "unary", op: "!", x: n.test }, refWords)}`;
8981
10503
  return valueText(n, refWords).text;
8982
10504
  }
8983
10505
  function forEachWords(n, refWords) {
@@ -9847,7 +11369,7 @@ var at = (n, ...keys) => {
9847
11369
  for (const k of keys) cur = get(cur, k);
9848
11370
  return cur;
9849
11371
  };
9850
- var lineOf = (n, key, fallback) => entry(n, key)?.line ?? fallback;
11372
+ var lineOf2 = (n, key, fallback) => entry(n, key)?.line ?? fallback;
9851
11373
  var labelsOf = (n) => n?.t === "map" ? Object.fromEntries(n.entries.map((e) => [e.key, str(e.value) ?? ""])) : {};
9852
11374
  var selectorWords = (labels) => listWords2(Object.entries(labels).map(([k, v]) => `${k}=${v}`));
9853
11375
  function selectorOf(n) {
@@ -9948,15 +11470,15 @@ function readKubernetes(src, file = "k8s.yaml") {
9948
11470
  const doc = commentAbove(srcLines, r.line);
9949
11471
  if (doc) thing.doc = doc;
9950
11472
  if (ns) {
9951
- know("Namespace", ns, lineOf(meta, "namespace"));
9952
- link(address, `Namespace/${ns}`, "runs-in", lineOf(meta, "namespace"));
11473
+ know("Namespace", ns, lineOf2(meta, "namespace"));
11474
+ link(address, `Namespace/${ns}`, "runs-in", lineOf2(meta, "namespace"));
9953
11475
  }
9954
11476
  const spec = get(r.n, "spec");
9955
11477
  if (WORKLOADS.has(kind)) {
9956
11478
  readWorkload({ kind, name, spec, n: r.n, address, ns, where, know, fact, setting, link, addr, thing, line: r.line });
9957
11479
  } else if (kind === "Service") {
9958
11480
  const type = str(get(spec, "type")) ?? "ClusterIP";
9959
- const typeLine = lineOf(spec, "type", r.line);
11481
+ const typeLine = lineOf2(spec, "type", r.line);
9960
11482
  const ann = labelsOf(get(meta, "annotations"));
9961
11483
  const internal = Object.entries(ann).some(([k, v]) => /load-balancer-internal$/.test(k) && /^(true|0\.0\.0\.0\/0)$/i.test(v) || /load-balancer-(type|scheme)$/.test(k) && /^internal$/i.test(v));
9962
11484
  const ranges = list(get(spec, "loadBalancerSourceRanges")).map(str);
@@ -9966,7 +11488,7 @@ function readKubernetes(src, file = "k8s.yaml") {
9966
11488
  return `${port}${target && target !== port ? ` (to ${target} on the pods)` : ""}${node ? ` (and ${node} on every node)` : ""}${/^udp$/i.test(str(get(p, "protocol")) ?? "") ? " (UDP)" : ""}`;
9967
11489
  });
9968
11490
  if (type === "ExternalName") {
9969
- know("Sends to", `the outside address ${str(get(spec, "externalName")) ?? "?"}`, lineOf(spec, "externalName"));
11491
+ know("Sends to", `the outside address ${str(get(spec, "externalName")) ?? "?"}`, lineOf2(spec, "externalName"));
9970
11492
  } else {
9971
11493
  const reach = type === "LoadBalancer" ? internal ? "inside the private network only (an internal load balancer)" : ranges.length && !ranges.includes("0.0.0.0/0") ? `outside the cluster, only from ${listWords2(ranges)}` : "the internet, through a load balancer" : type === "NodePort" ? "outside the cluster, on a port of every node" : str(get(spec, "clusterIP")) === "None" ? "inside the cluster, each pod by its own name (no shared address)" : "inside the cluster only";
9972
11494
  know("Reachable from", reach, typeLine);
@@ -9974,12 +11496,12 @@ function readKubernetes(src, file = "k8s.yaml") {
9974
11496
  fact("public-ingress", type === "NodePort" ? `${where} is a NodePort: anyone who can reach a node can reach ${portList.length ? `port${ports.length === 1 ? "" : "s"} ${listWords2(ports.map((p) => str(get(p, "nodePort")) ?? "(picked by Kubernetes)"))}` : "it"}.` : `${where} is a LoadBalancer: anyone on the internet can reach ${portList.length ? `port${ports.length === 1 ? "" : "s"} ${listWords2(ports.map((p) => str(get(p, "port"))))}` : "it"}.`, typeLine);
9975
11497
  }
9976
11498
  }
9977
- if (portList.length) know(ports.length === 1 ? "Port" : "Ports", listWords2(portList), lineOf(spec, "ports"));
11499
+ if (portList.length) know(ports.length === 1 ? "Port" : "Ports", listWords2(portList), lineOf2(spec, "ports"));
9978
11500
  const sel = get(spec, "selector");
9979
11501
  if (sel) {
9980
11502
  const s = selectorOf(sel);
9981
- know("Sends to", s.says, lineOf(spec, "selector"));
9982
- thing.selects = { labels: s.labels, ns, line: lineOf(spec, "selector") };
11503
+ know("Sends to", s.says, lineOf2(spec, "selector"));
11504
+ thing.selects = { labels: s.labels, ns, line: lineOf2(spec, "selector") };
9983
11505
  } else if (type !== "ExternalName") know("Sends to", "addresses listed elsewhere (no selector)", typeLine);
9984
11506
  } else if (kind === "Ingress") {
9985
11507
  readIngress({ spec, meta, where, know, fact, link, address, addr, line: r.line });
@@ -9995,7 +11517,7 @@ function readKubernetes(src, file = "k8s.yaml") {
9995
11517
  }
9996
11518
  } else if (kind === "Secret") {
9997
11519
  const type = str(get(r.n, "type")) ?? "Opaque";
9998
- know("Holds", { "kubernetes.io/tls": "a TLS certificate and its key", "kubernetes.io/dockerconfigjson": "a sign-in for a container registry", "kubernetes.io/dockercfg": "a sign-in for a container registry", "kubernetes.io/service-account-token": "a service account token", "kubernetes.io/basic-auth": "a user name and password", "kubernetes.io/ssh-auth": "an SSH key" }[type] ?? `secret values (${type})`, lineOf(r.n, "type"));
11520
+ know("Holds", { "kubernetes.io/tls": "a TLS certificate and its key", "kubernetes.io/dockerconfigjson": "a sign-in for a container registry", "kubernetes.io/dockercfg": "a sign-in for a container registry", "kubernetes.io/service-account-token": "a service account token", "kubernetes.io/basic-auth": "a user name and password", "kubernetes.io/ssh-auth": "an SSH key" }[type] ?? `secret values (${type})`, lineOf2(r.n, "type"));
9999
11521
  let written = null;
10000
11522
  for (const key of ["data", "stringData"]) for (const e of get(r.n, key)?.entries ?? []) {
10001
11523
  know(e.key, "a secret value (only its name is shown)", e.line, { setting: true, secret: true });
@@ -10005,26 +11527,26 @@ function readKubernetes(src, file = "k8s.yaml") {
10005
11527
  if (written) fact("secret-in-plain-config", `The Secret ${name} has its values written in this file: ${get(r.n, "data") ? "values under data: are only base64-encoded, not encrypted, so " : ""}anyone who can read the file can read them.`, written);
10006
11528
  } else if (kind === "PersistentVolumeClaim") {
10007
11529
  const size = str(at(spec, "resources", "requests", "storage"));
10008
- if (size) know("Asks for", `${memWords(size)} of storage`, lineOf(spec, "resources"));
11530
+ if (size) know("Asks for", `${memWords(size)} of storage`, lineOf2(spec, "resources"));
10009
11531
  const modes = list(get(spec, "accessModes")).map(str);
10010
- if (modes.length) know("Can be", listWords2(modes.map((m) => ACCESS[m] ?? m)), lineOf(spec, "accessModes"));
11532
+ if (modes.length) know("Can be", listWords2(modes.map((m) => ACCESS[m] ?? m)), lineOf2(spec, "accessModes"));
10011
11533
  const sc = str(get(spec, "storageClassName"));
10012
- if (sc != null) know("Storage class", sc === "" ? "none (only a volume made by hand)" : sc, lineOf(spec, "storageClassName"));
11534
+ if (sc != null) know("Storage class", sc === "" ? "none (only a volume made by hand)" : sc, lineOf2(spec, "storageClassName"));
10013
11535
  const vol = str(get(spec, "volumeName"));
10014
11536
  if (vol) {
10015
- know("Uses the volume", vol, lineOf(spec, "volumeName"));
10016
- link(address, `PersistentVolume/${vol}`, "uses", lineOf(spec, "volumeName"));
11537
+ know("Uses the volume", vol, lineOf2(spec, "volumeName"));
11538
+ link(address, `PersistentVolume/${vol}`, "uses", lineOf2(spec, "volumeName"));
10017
11539
  }
10018
11540
  } else if (kind === "PersistentVolume") {
10019
11541
  const size = str(at(spec, "capacity", "storage"));
10020
- if (size) know("Holds", `${memWords(size)} of storage`, lineOf(spec, "capacity"));
11542
+ if (size) know("Holds", `${memWords(size)} of storage`, lineOf2(spec, "capacity"));
10021
11543
  const hp = str(at(spec, "hostPath", "path"));
10022
- if (hp) know("Kept in", `the node's own folder ${hp}`, lineOf(spec, "hostPath"));
11544
+ if (hp) know("Kept in", `the node's own folder ${hp}`, lineOf2(spec, "hostPath"));
10023
11545
  const policy = str(get(spec, "persistentVolumeReclaimPolicy"));
10024
- if (policy) know("When released", { Retain: "kept until someone removes it", Delete: "deleted", Recycle: "emptied and reused" }[policy] ?? policy, lineOf(spec, "persistentVolumeReclaimPolicy"));
11546
+ if (policy) know("When released", { Retain: "kept until someone removes it", Delete: "deleted", Recycle: "emptied and reused" }[policy] ?? policy, lineOf2(spec, "persistentVolumeReclaimPolicy"));
10025
11547
  } else if (kind === "ServiceAccount") {
10026
11548
  const auto = bool(get(r.n, "automountServiceAccountToken"));
10027
- know("Its token", auto === false ? "not handed to its pods unless they ask" : "handed to every pod that runs as it (the default)", lineOf(r.n, "automountServiceAccountToken"));
11549
+ know("Its token", auto === false ? "not handed to its pods unless they ask" : "handed to every pod that runs as it (the default)", lineOf2(r.n, "automountServiceAccountToken"));
10028
11550
  for (const s of list(get(r.n, "imagePullSecrets"))) {
10029
11551
  const sn = str(get(s, "name"));
10030
11552
  if (sn) {
@@ -10042,11 +11564,11 @@ function readKubernetes(src, file = "k8s.yaml") {
10042
11564
  const target = get(spec, "scaleTargetRef");
10043
11565
  const tk = str(get(target, "kind")), tn = str(get(target, "name"));
10044
11566
  if (tk && tn) {
10045
- know("Scales", `the ${kindWords(tk)} ${tn}`, lineOf(spec, "scaleTargetRef"));
10046
- link(address, addr(tk, tn), "uses", lineOf(spec, "scaleTargetRef"));
11567
+ know("Scales", `the ${kindWords(tk)} ${tn}`, lineOf2(spec, "scaleTargetRef"));
11568
+ link(address, addr(tk, tn), "uses", lineOf2(spec, "scaleTargetRef"));
10047
11569
  }
10048
11570
  const min = num2(get(spec, "minReplicas")) ?? 1, max = num2(get(spec, "maxReplicas"));
10049
- know("Copies", `between ${min} and ${max ?? "?"}`, lineOf(spec, "maxReplicas"));
11571
+ know("Copies", `between ${min} and ${max ?? "?"}`, lineOf2(spec, "maxReplicas"));
10050
11572
  const aims = [];
10051
11573
  const v1 = num2(get(spec, "targetCPUUtilizationPercentage"));
10052
11574
  if (v1) aims.push(`${v1}% of the CPU it asks for`);
@@ -10057,21 +11579,21 @@ function readKubernetes(src, file = "k8s.yaml") {
10057
11579
  aims.push(util != null ? `${util}% of the ${str(get(res, "name")) === "memory" ? "memory" : "CPU"} it asks for` : `a ${str(get(res, "name")) ?? "resource"} target`);
10058
11580
  } else aims.push(`a ${str(get(m, "type"))?.toLowerCase() ?? "custom"} measure`);
10059
11581
  }
10060
- if (aims.length) know("Aims for", listWords2(aims), lineOf(spec, v1 ? "targetCPUUtilizationPercentage" : "metrics"));
11582
+ if (aims.length) know("Aims for", listWords2(aims), lineOf2(spec, v1 ? "targetCPUUtilizationPercentage" : "metrics"));
10061
11583
  } else if (kind === "Namespace") {
10062
11584
  know("Is", "a named space that keeps the resources in it apart from others", r.line);
10063
11585
  } else if ((kind === "Kustomization" || kind === "Component") && /kustomize/.test(apiVersion ?? "")) {
10064
11586
  const files = [...list(get(r.n, "resources")), ...list(get(r.n, "components")), ...list(get(r.n, "bases"))].map(str).filter(Boolean);
10065
- know("Combines", files.length ? short3(listWords2(files), 160) : "nothing listed", lineOf(r.n, "resources", lineOf(r.n, "components")));
11587
+ know("Combines", files.length ? short3(listWords2(files), 160) : "nothing listed", lineOf2(r.n, "resources", lineOf2(r.n, "components")));
10066
11588
  const patches = list(get(r.n, "patches")).length + list(get(r.n, "patchesStrategicMerge")).length + list(get(r.n, "patchesJson6902")).length;
10067
- if (patches) know("Changes them with", `${patches} patch${patches === 1 ? "" : "es"}`, lineOf(r.n, "patches", lineOf(r.n, "patchesStrategicMerge")));
11589
+ if (patches) know("Changes them with", `${patches} patch${patches === 1 ? "" : "es"}`, lineOf2(r.n, "patches", lineOf2(r.n, "patchesStrategicMerge")));
10068
11590
  const nsSet = str(get(r.n, "namespace"));
10069
- if (nsSet) know("Puts everything in the namespace", nsSet, lineOf(r.n, "namespace"));
11591
+ if (nsSet) know("Puts everything in the namespace", nsSet, lineOf2(r.n, "namespace"));
10070
11592
  for (const im of list(get(r.n, "images"))) know(`Image ${str(get(im, "name"))}`, `becomes ${[str(get(im, "newName")) ?? str(get(im, "name")), str(get(im, "newTag")) ?? str(get(im, "digest"))].filter(Boolean).join(":")}`, im.line);
10071
11593
  thing.label = `Kustomization ${kind === "Component" ? "component " : ""}(${file.slice(file.lastIndexOf("/") + 1)})`;
10072
11594
  } else if (kind === "PodDisruptionBudget") {
10073
11595
  const min = str(get(spec, "minAvailable")), max = str(get(spec, "maxUnavailable"));
10074
- know("Keeps running", min != null ? `at least ${min} of ${selectorOf(get(spec, "selector")).says}` : `all but ${max ?? "?"} of ${selectorOf(get(spec, "selector")).says}`, lineOf(spec, min != null ? "minAvailable" : "maxUnavailable"));
11596
+ know("Keeps running", min != null ? `at least ${min} of ${selectorOf(get(spec, "selector")).says}` : `all but ${max ?? "?"} of ${selectorOf(get(spec, "selector")).says}`, lineOf2(spec, min != null ? "minAvailable" : "maxUnavailable"));
10075
11597
  } else {
10076
11598
  const keys = (spec?.t === "map" ? spec.entries : r.n.entries.filter((e) => !["apiVersion", "kind", "metadata"].includes(e.key))).map((e) => e.key);
10077
11599
  know("Kind", `${kind}${apiVersion ? ` (${apiVersion})` : ""}: Thunder draws it but does not read its settings yet`, r.line);
@@ -10193,26 +11715,26 @@ function readWorkload(c) {
10193
11715
  const sched = str(get(spec, "schedule"));
10194
11716
  const tz = str(get(spec, "timeZone"));
10195
11717
  const w = sched ? cronWords(sched) : null;
10196
- know("When", w ? tz ? w.replace(/ UTC$/, ` (${tz} time)`) : w.replace(/ UTC$/, " (the cluster's time zone)") : `on the schedule ${sched ?? "?"} (cron)`, lineOf(spec, "schedule"));
10197
- if (bool(get(spec, "suspend"))) know("Paused", "yes: it does not run until someone turns it back on", lineOf(spec, "suspend"));
11718
+ know("When", w ? tz ? w.replace(/ UTC$/, ` (${tz} time)`) : w.replace(/ UTC$/, " (the cluster's time zone)") : `on the schedule ${sched ?? "?"} (cron)`, lineOf2(spec, "schedule"));
11719
+ if (bool(get(spec, "suspend"))) know("Paused", "yes: it does not run until someone turns it back on", lineOf2(spec, "suspend"));
10198
11720
  const cp = str(get(spec, "concurrencyPolicy"));
10199
- if (cp) know("If the last run is still going", { Allow: "runs again anyway", Forbid: "skips this run", Replace: "stops the last run and starts again" }[cp] ?? cp, lineOf(spec, "concurrencyPolicy"));
11721
+ if (cp) know("If the last run is still going", { Allow: "runs again anyway", Forbid: "skips this run", Replace: "stops the last run and starts again" }[cp] ?? cp, lineOf2(spec, "concurrencyPolicy"));
10200
11722
  } else if (kind === "Job") {
10201
11723
  const back = num2(get(spec, "backoffLimit"));
10202
11724
  const comp = num2(get(spec, "completions"));
10203
- know("How many", `runs ${comp && comp > 1 ? `until it succeeds ${comp} times` : "once until it succeeds"}, trying up to ${back ?? 6} more times`, lineOf(spec, "backoffLimit"));
11725
+ know("How many", `runs ${comp && comp > 1 ? `until it succeeds ${comp} times` : "once until it succeeds"}, trying up to ${back ?? 6} more times`, lineOf2(spec, "backoffLimit"));
10204
11726
  } else if (kind === "DaemonSet") {
10205
11727
  know("How many", "one copy on every node", c.line);
10206
11728
  } else if (kind !== "Pod") {
10207
11729
  const repl = get(spec, "replicas");
10208
11730
  const rn = num2(repl);
10209
- know("How many", repl ? rn != null ? `${rn} cop${rn === 1 ? "y" : "ies"}` : `${str(repl)} copies` : "1 copy (the default; an autoscaler may change it)", lineOf(spec, "replicas"));
11731
+ know("How many", repl ? rn != null ? `${rn} cop${rn === 1 ? "y" : "ies"}` : `${str(repl)} copies` : "1 copy (the default; an autoscaler may change it)", lineOf2(spec, "replicas"));
10210
11732
  }
10211
11733
  if (kind === "StatefulSet") {
10212
11734
  const svc = str(get(spec, "serviceName"));
10213
11735
  if (svc) {
10214
- know("Named through", `the service ${svc}`, lineOf(spec, "serviceName"));
10215
- link(address, addr("Service", svc), "uses", lineOf(spec, "serviceName"));
11736
+ know("Named through", `the service ${svc}`, lineOf2(spec, "serviceName"));
11737
+ link(address, addr("Service", svc), "uses", lineOf2(spec, "serviceName"));
10216
11738
  }
10217
11739
  for (const vct of list(get(spec, "volumeClaimTemplates"))) {
10218
11740
  const size = str(at(vct, "spec", "resources", "requests", "storage"));
@@ -10222,16 +11744,16 @@ function readWorkload(c) {
10222
11744
  if (!podSpec) return;
10223
11745
  const sa = str(get(podSpec, "serviceAccountName")) ?? str(get(podSpec, "serviceAccount"));
10224
11746
  if (sa) {
10225
- know("Runs as the identity", `the service account ${sa}`, lineOf(podSpec, sa === str(get(podSpec, "serviceAccountName")) ? "serviceAccountName" : "serviceAccount"));
10226
- link(address, addr("ServiceAccount", sa), "uses", lineOf(podSpec, "serviceAccountName", lineOf(podSpec, "serviceAccount")));
11747
+ know("Runs as the identity", `the service account ${sa}`, lineOf2(podSpec, sa === str(get(podSpec, "serviceAccountName")) ? "serviceAccountName" : "serviceAccount"));
11748
+ link(address, addr("ServiceAccount", sa), "uses", lineOf2(podSpec, "serviceAccountName", lineOf2(podSpec, "serviceAccount")));
10227
11749
  }
10228
11750
  for (const h of ["hostNetwork", "hostPID", "hostIPC"]) if (bool(get(podSpec, h))) {
10229
11751
  const what = { hostNetwork: "the node's own network", hostPID: "every process on the node", hostIPC: "the node's shared memory" }[h];
10230
- know("Shares", what, lineOf(podSpec, h));
10231
- fact("privileged-container", `${where} shares ${what} (${h}: true), so it can see or reach far more than its own containers.`, lineOf(podSpec, h));
11752
+ know("Shares", what, lineOf2(podSpec, h));
11753
+ fact("privileged-container", `${where} shares ${what} (${h}: true), so it can see or reach far more than its own containers.`, lineOf2(podSpec, h));
10232
11754
  }
10233
11755
  const nodeSel = labelsOf(get(podSpec, "nodeSelector"));
10234
- if (Object.keys(nodeSel).length) know("Runs only on nodes with", selectorWords(nodeSel), lineOf(podSpec, "nodeSelector"));
11756
+ if (Object.keys(nodeSel).length) know("Runs only on nodes with", selectorWords(nodeSel), lineOf2(podSpec, "nodeSelector"));
10235
11757
  for (const s of list(get(podSpec, "imagePullSecrets"))) {
10236
11758
  const sn = str(get(s, "name"));
10237
11759
  if (sn) link(address, addr("Secret", sn), "reads-from", s.line);
@@ -10272,15 +11794,15 @@ function readWorkload(c) {
10272
11794
  const cwhere = many ? `The container ${cn} in ${where.replace(/^The /, "the ")}` : where;
10273
11795
  const image = str(get(ct, "image"));
10274
11796
  if (image) {
10275
- know(`${pre}Runs`, imageWords2(image, STARTS), lineOf(ct, "image"), { name: "image", ...hasVar2(image) ? { computed: true } : {} });
11797
+ know(`${pre}Runs`, imageWords2(image, STARTS), lineOf2(ct, "image"), { name: "image", ...hasVar2(image) ? { computed: true } : {} });
10276
11798
  const says = imageNotPinned(image, cwhere);
10277
- if (says) fact("image-not-pinned", says, lineOf(ct, "image"));
10278
- thing.images = [...thing.images ?? [], { name: parseImage(image).name, ref: image, line: lineOf(ct, "image") }];
11799
+ if (says) fact("image-not-pinned", says, lineOf2(ct, "image"));
11800
+ thing.images = [...thing.images ?? [], { name: parseImage(image).name, ref: image, line: lineOf2(ct, "image") }];
10279
11801
  }
10280
11802
  const cmd = list(get(ct, "command")).map(str), args = list(get(ct, "args")).map(str);
10281
- if (cmd.length || args.length) know(`${pre}Starts with`, short3(commandText([...cmd, ...args]), 120), lineOf(ct, cmd.length ? "command" : "args"));
11803
+ if (cmd.length || args.length) know(`${pre}Starts with`, short3(commandText([...cmd, ...args]), 120), lineOf2(ct, cmd.length ? "command" : "args"));
10282
11804
  const ports = list(get(ct, "ports"));
10283
- if (ports.length) know(`${pre}${ports.length === 1 ? "Opens port" : "Opens ports"}`, listWords2(ports.map((p) => `${str(get(p, "containerPort"))}${str(get(p, "name")) ? ` (${str(get(p, "name"))})` : ""}${/^udp$/i.test(str(get(p, "protocol")) ?? "") ? " (UDP)" : ""}`)), lineOf(ct, "ports"));
11805
+ if (ports.length) know(`${pre}${ports.length === 1 ? "Opens port" : "Opens ports"}`, listWords2(ports.map((p) => `${str(get(p, "containerPort"))}${str(get(p, "name")) ? ` (${str(get(p, "name"))})` : ""}${/^udp$/i.test(str(get(p, "protocol")) ?? "") ? " (UDP)" : ""}`)), lineOf2(ct, "ports"));
10284
11806
  for (const e of list(get(ct, "env"))) {
10285
11807
  const en = str(get(e, "name"));
10286
11808
  if (!en) continue;
@@ -10329,27 +11851,27 @@ function readWorkload(c) {
10329
11851
  const res = get(ct, "resources");
10330
11852
  const req = get(res, "requests"), lim = get(res, "limits");
10331
11853
  const amount = (m) => listWords2([str(get(m, "cpu")) && cpuWords(str(get(m, "cpu"))), str(get(m, "memory")) && `${memWords(str(get(m, "memory")))} of memory`].filter(Boolean));
10332
- if (req && amount(req)) know(`${pre}Asks for`, amount(req), lineOf(res, "requests"));
10333
- if (lim && amount(lim)) know(`${pre}Can use at most`, amount(lim), lineOf(res, "limits"));
10334
- if (!init && (!lim || !lim.entries?.length)) fact("no-resource-limits", `${cwhere} has no resource limits, so it can use as much CPU and memory as the node has.`, lineOf(ct, "resources", lineOf(ct, "name", ct.line)));
11854
+ if (req && amount(req)) know(`${pre}Asks for`, amount(req), lineOf2(res, "requests"));
11855
+ if (lim && amount(lim)) know(`${pre}Can use at most`, amount(lim), lineOf2(res, "limits"));
11856
+ if (!init && (!lim || !lim.entries?.length)) fact("no-resource-limits", `${cwhere} has no resource limits, so it can use as much CPU and memory as the node has.`, lineOf2(ct, "resources", lineOf2(ct, "name", ct.line)));
10335
11857
  for (const [key, label] of [["startupProbe", "Has started when"], ["readinessProbe", "Ready for traffic when"], ["livenessProbe", "Restarted when"]]) {
10336
11858
  const p = get(ct, key);
10337
- if (p) know(`${pre}${label}`, probeWords(p, key === "livenessProbe" ? "fails" : "succeeds"), lineOf(ct, key));
11859
+ if (p) know(`${pre}${label}`, probeWords(p, key === "livenessProbe" ? "fails" : "succeeds"), lineOf2(ct, key));
10338
11860
  }
10339
11861
  const sc = get(ct, "securityContext");
10340
11862
  const pick = (k) => {
10341
11863
  const a = get(sc, k);
10342
- return a ? { v: scalar(a), line: lineOf(sc, k) } : get(pod, k) ? { v: scalar(get(pod, k)), line: lineOf(pod, k) } : null;
11864
+ return a ? { v: scalar(a), line: lineOf2(sc, k) } : get(pod, k) ? { v: scalar(get(pod, k)), line: lineOf2(pod, k) } : null;
10343
11865
  };
10344
11866
  const user = pick("runAsUser"), nonRoot = pick("runAsNonRoot");
10345
11867
  const privileged = bool(get(sc, "privileged"));
10346
11868
  const adds = list(at(sc, "capabilities", "add")).map(str);
10347
- const scLine = lineOf(ct, "securityContext", lineOf(ct, "name", ct.line));
11869
+ const scLine = lineOf2(ct, "securityContext", lineOf2(ct, "name", ct.line));
10348
11870
  if (privileged) {
10349
- know(`${pre}Privileged`, "yes: it can do almost anything on the node", lineOf(sc, "privileged"));
10350
- fact("privileged-container", `${cwhere} is privileged (privileged: true), so it can do almost anything on the node.`, lineOf(sc, "privileged"));
11871
+ know(`${pre}Privileged`, "yes: it can do almost anything on the node", lineOf2(sc, "privileged"));
11872
+ fact("privileged-container", `${cwhere} is privileged (privileged: true), so it can do almost anything on the node.`, lineOf2(sc, "privileged"));
10351
11873
  }
10352
- if (adds.some((a) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(a))) fact("privileged-container", `${cwhere} adds the ${adds.filter((a) => /ALL|SYS_ADMIN/i.test(a)).join(" and ")} capabilit${adds.length === 1 ? "y" : "ies"}, which gives it nearly the power of the node itself.`, lineOf(sc, "capabilities"));
11874
+ if (adds.some((a) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(a))) fact("privileged-container", `${cwhere} adds the ${adds.filter((a) => /ALL|SYS_ADMIN/i.test(a)).join(" and ")} capabilit${adds.length === 1 ? "y" : "ies"}, which gives it nearly the power of the node itself.`, lineOf2(sc, "capabilities"));
10353
11875
  if (user && Number(user.v) === 0) {
10354
11876
  know(`${pre}Runs as`, "root (user 0), the user that can do anything", user.line);
10355
11877
  fact("runs-as-root", `${cwhere} runs as root (runAsUser: 0).`, user.line);
@@ -10361,7 +11883,7 @@ function readWorkload(c) {
10361
11883
  know(`${pre}Runs as`, "the image's own user (the file does not say; it may be root)", scLine);
10362
11884
  fact("runs-as-root", `${cwhere} may run as root: nothing in the file stops it (no runAsNonRoot: true and no runAsUser).`, scLine);
10363
11885
  }
10364
- if (bool(get(sc, "readOnlyRootFilesystem"))) know(`${pre}Its own files`, "read-only (it cannot change its image)", lineOf(sc, "readOnlyRootFilesystem"));
11886
+ if (bool(get(sc, "readOnlyRootFilesystem"))) know(`${pre}Its own files`, "read-only (it cannot change its image)", lineOf2(sc, "readOnlyRootFilesystem"));
10365
11887
  for (const m of list(get(ct, "volumeMounts"))) {
10366
11888
  const v = volumes.get(str(get(m, "name")));
10367
11889
  const ro = bool(get(m, "readOnly"));
@@ -10373,7 +11895,7 @@ function readWorkload(c) {
10373
11895
  }
10374
11896
  function readIngress({ spec, meta, where, know, fact, link, address, addr, line }) {
10375
11897
  const cls = str(get(spec, "ingressClassName")) ?? labelsOf(get(meta, "annotations"))["kubernetes.io/ingress.class"];
10376
- if (cls) know("Handled by", `the ${cls} ingress controller`, lineOf(spec, "ingressClassName", line));
11898
+ if (cls) know("Handled by", `the ${cls} ingress controller`, lineOf2(spec, "ingressClassName", line));
10377
11899
  const backend = (b) => {
10378
11900
  if (!b) return null;
10379
11901
  const svc = get(b, "service");
@@ -10388,8 +11910,8 @@ function readIngress({ spec, meta, where, know, fact, link, address, addr, line
10388
11910
  const hosts = [];
10389
11911
  const def = backend(get(spec, "defaultBackend") ?? get(spec, "backend"));
10390
11912
  if (def) {
10391
- know("Everything else goes to", def.says, lineOf(spec, "defaultBackend", lineOf(spec, "backend")));
10392
- if (def.sn) link(address, addr("Service", def.sn), "sends-to", lineOf(spec, "defaultBackend", lineOf(spec, "backend")));
11913
+ know("Everything else goes to", def.says, lineOf2(spec, "defaultBackend", lineOf2(spec, "backend")));
11914
+ if (def.sn) link(address, addr("Service", def.sn), "sends-to", lineOf2(spec, "defaultBackend", lineOf2(spec, "backend")));
10393
11915
  }
10394
11916
  for (const rule of list(get(spec, "rules"))) {
10395
11917
  const host = str(get(rule, "host"));
@@ -10408,7 +11930,7 @@ function readIngress({ spec, meta, where, know, fact, link, address, addr, line
10408
11930
  know("Uses HTTPS for", `${th.length ? listWords2(th) : "its addresses"}${sn ? `, with the certificate in the Secret ${sn}` : ""}`, t.line);
10409
11931
  if (sn) link(address, addr("Secret", sn), "reads-from", t.line);
10410
11932
  }
10411
- fact("public-ingress", `${where} lets requests from outside the cluster reach ${hosts.length ? listWords2([...new Set(hosts)]) : "its paths"} (wherever its ingress controller listens).`, lineOf(spec, "rules", line));
11933
+ fact("public-ingress", `${where} lets requests from outside the cluster reach ${hosts.length ? listWords2([...new Set(hosts)]) : "its paths"} (wherever its ingress controller listens).`, lineOf2(spec, "rules", line));
10412
11934
  }
10413
11935
  function readRole({ kind, name, n, ns, know, permissions, file }) {
10414
11936
  const scope = kind === "ClusterRole" ? "wherever it is given (one namespace, or the whole cluster)" : `in the namespace ${ns ?? "it is made in"}`;
@@ -10438,7 +11960,7 @@ function readRole({ kind, name, n, ns, know, permissions, file }) {
10438
11960
  });
10439
11961
  }
10440
11962
  const agg = get(n, "aggregationRule");
10441
- if (agg) know("Gathers", `the rules of every cluster role with ${listWords2(list(get(agg, "clusterRoleSelectors")).map((s) => selectorOf(s).says.replace(/^pods with /, "")))}`, lineOf(n, "aggregationRule"));
11963
+ if (agg) know("Gathers", `the rules of every cluster role with ${listWords2(list(get(agg, "clusterRoleSelectors")).map((s) => selectorOf(s).says.replace(/^pods with /, "")))}`, lineOf2(n, "aggregationRule"));
10442
11964
  }
10443
11965
  function subjectWords(s) {
10444
11966
  const k = str(get(s, "kind")), n = str(get(s, "name")), ns = str(get(s, "namespace"));
@@ -10459,10 +11981,10 @@ function readBinding({ kind, name, n, ns, know, permissions, file, address, link
10459
11981
  const can = builtin ?? `do what the ${kindWords(rk)} ${rn} allows`;
10460
11982
  const anyone = subs.some((s) => /^system:(unauthenticated|anonymous|authenticated)$/.test(str(get(s, "name")) ?? ""));
10461
11983
  const wide = rn === "cluster-admin" || kind === "ClusterRoleBinding" && (rn === "admin" || rn === "edit") || anyone && rn !== "system:public-info-viewer" && rn !== "system:discovery" && rn !== "system:basic-user";
10462
- know("Gives", `${who} the ${kindWords(rk)} ${rn}`, lineOf(n, "roleRef"));
10463
- know("Where", scope, lineOf(n, "roleRef"));
11984
+ know("Gives", `${who} the ${kindWords(rk)} ${rn}`, lineOf2(n, "roleRef"));
11985
+ know("Where", scope, lineOf2(n, "roleRef"));
10464
11986
  permissions.push({
10465
- id: `${file}#permission#${lineOf(n, "roleRef", n.line)}#${permissions.length}`,
11987
+ id: `${file}#permission#${lineOf2(n, "roleRef", n.line)}#${permissions.length}`,
10466
11988
  who,
10467
11989
  can,
10468
11990
  on: scope,
@@ -10470,10 +11992,10 @@ function readBinding({ kind, name, n, ns, know, permissions, file, address, link
10470
11992
  role: rn,
10471
11993
  ...wide ? { why: rn === "cluster-admin" ? `cluster-admin lets ${anyone ? "them" : "it"} do anything in the whole cluster` : anyone ? `it gives ${rn} to ${who}` : `${rn} ${scope} lets it change almost everything` } : {},
10472
11994
  file,
10473
- line: lineOf(n, "roleRef", n.line),
11995
+ line: lineOf2(n, "roleRef", n.line),
10474
11996
  says: `${cap(who)} can ${can} ${scope}${wide ? " (wide)" : ""}`
10475
11997
  });
10476
- link(address, addr(rk, rn), "uses", lineOf(n, "roleRef"));
11998
+ link(address, addr(rk, rn), "uses", lineOf2(n, "roleRef"));
10477
11999
  for (const s of subs) if (str(get(s, "kind")) === "ServiceAccount") link(address, k8sAddress("ServiceAccount", str(get(s, "name")), str(get(s, "namespace")) ?? ns), "uses", s.line);
10478
12000
  }
10479
12001
  function peerWords(p) {
@@ -10491,14 +12013,14 @@ function peerWords(p) {
10491
12013
  return parts.join(" and ") || "anywhere";
10492
12014
  }
10493
12015
  function readNetworkPolicy({ spec, know }) {
10494
- know("Applies to", `${selectorOf(get(spec, "podSelector")).says} in its namespace`, lineOf(spec, "podSelector"));
12016
+ know("Applies to", `${selectorOf(get(spec, "podSelector")).says} in its namespace`, lineOf2(spec, "podSelector"));
10495
12017
  const types = list(get(spec, "policyTypes")).map(str);
10496
12018
  const has2 = (k) => types.includes(k) || !types.length && (k === "Ingress" || get(spec, "egress"));
10497
12019
  for (const [key, type, label, dir] of [["ingress", "Ingress", "Lets in", "from"], ["egress", "Egress", "Lets out", "to"]]) {
10498
12020
  if (!has2(type)) continue;
10499
12021
  const rules = list(get(spec, key));
10500
12022
  if (!rules.length) {
10501
- know(label, `nothing: every ${key === "ingress" ? "incoming" : "outgoing"} connection is blocked`, lineOf(spec, key, lineOf(spec, "policyTypes")));
12023
+ know(label, `nothing: every ${key === "ingress" ? "incoming" : "outgoing"} connection is blocked`, lineOf2(spec, key, lineOf2(spec, "policyTypes")));
10502
12024
  continue;
10503
12025
  }
10504
12026
  for (const r of rules) {
@@ -10515,7 +12037,7 @@ var str2 = (n) => {
10515
12037
  const v = scalar(n);
10516
12038
  return v == null ? void 0 : String(v);
10517
12039
  };
10518
- var lineOf2 = (n, key, fallback) => entry(n, key)?.line ?? fallback;
12040
+ var lineOf3 = (n, key, fallback) => entry(n, key)?.line ?? fallback;
10519
12041
  var short4 = (s, n = 80) => s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
10520
12042
  var varsIn = (s) => {
10521
12043
  const out = [];
@@ -10626,19 +12148,19 @@ function readCompose(src, file = "compose.yaml") {
10626
12148
  const ext = get(v, "external");
10627
12149
  const external = str2(ext) === "true" || ext?.t === "map";
10628
12150
  const realName = str2(get(v, "name")) ?? str2(get(ext, "name"));
10629
- if (external) know("Made", `elsewhere: Compose uses the existing ${word}${realName ? ` ${realName}` : ""}`, lineOf2(v, "external"));
10630
- else if (realName) know("Named", realName, lineOf2(v, "name"));
12151
+ if (external) know("Made", `elsewhere: Compose uses the existing ${word}${realName ? ` ${realName}` : ""}`, lineOf3(v, "external"));
12152
+ else if (realName) know("Named", realName, lineOf3(v, "name"));
10631
12153
  const driver = str2(get(v, "driver"));
10632
- if (driver) know("Driver", driver, lineOf2(v, "driver"));
10633
- if (key === "networks" && str2(get(v, "internal")) === "true") know("Reaches", "only the services on it (no way out to the internet)", lineOf2(v, "internal"));
12154
+ if (driver) know("Driver", driver, lineOf3(v, "driver"));
12155
+ if (key === "networks" && str2(get(v, "internal")) === "true") know("Reaches", "only the services on it (no way out to the internet)", lineOf3(v, "internal"));
10634
12156
  if (key === "secrets" || key === "configs") {
10635
12157
  const f = str2(get(v, "file")), env = str2(get(v, "environment")), content = get(v, "content");
10636
- if (f) know("Read from", `the file ${f} on the computer it starts on`, lineOf2(v, "file"));
10637
- if (env) know("Taken from", `the variable ${env} on the computer it starts on`, lineOf2(v, "environment"));
10638
- if (content) know("Written here", key === "secrets" ? "yes (not shown)" : short4(str2(content) ?? ""), lineOf2(v, "content"));
12158
+ if (f) know("Read from", `the file ${f} on the computer it starts on`, lineOf3(v, "file"));
12159
+ if (env) know("Taken from", `the variable ${env} on the computer it starts on`, lineOf3(v, "environment"));
12160
+ if (content) know("Written here", key === "secrets" ? "yes (not shown)" : short4(str2(content) ?? ""), lineOf3(v, "content"));
10639
12161
  if (key === "secrets") {
10640
12162
  setting({ name, source: "secret", secret: true, line: e.line });
10641
- if (content && !hasVar2(str2(content))) fact("secret-in-plain-config", `The secret ${name} has its value written in the Compose file.`, lineOf2(v, "content"));
12163
+ if (content && !hasVar2(str2(content))) fact("secret-in-plain-config", `The secret ${name} has its value written in the Compose file.`, lineOf3(v, "content"));
10642
12164
  }
10643
12165
  }
10644
12166
  const address = `${key}.${name}`;
@@ -10662,31 +12184,31 @@ function readCompose(src, file = "compose.yaml") {
10662
12184
  const target = build.t === "map" ? str2(get(build, "target")) : void 0;
10663
12185
  const remote = /^(https?|git|ssh):\/\/|^git@|\.git(#|$)/.test(ctx);
10664
12186
  info.build = ctx;
10665
- know("Built from", `${remote ? `the repository ${ctx}` : ctx === "." ? "this folder" : `the folder ${ctx}`}${df ? `, with ${df}` : ""}${target ? `, the ${target} stage` : ""}`, build.t === "map" ? lineOf2(build, "context", lineOf2(s, "build")) : lineOf2(s, "build"), { name: "build" });
12187
+ know("Built from", `${remote ? `the repository ${ctx}` : ctx === "." ? "this folder" : `the folder ${ctx}`}${df ? `, with ${df}` : ""}${target ? `, the ${target} stage` : ""}`, build.t === "map" ? lineOf3(build, "context", lineOf3(s, "build")) : lineOf3(s, "build"), { name: "build" });
10666
12188
  if (!remote && !hasVar2(ctx) && !(df && (hasVar2(df) || df.startsWith("/")))) {
10667
12189
  const path = normPath(`${dir ? `${dir}/` : ""}${ctx}/${df ?? "Dockerfile"}`);
10668
- if (path) link(address, `image:${path}`, "uses", lineOf2(s, "build"));
12190
+ if (path) link(address, `image:${path}`, "uses", lineOf3(s, "build"));
10669
12191
  }
10670
12192
  for (const a of envEntries(build.t === "map" ? get(build, "args") : null)) {
10671
12193
  const secret = isSecretName(a.key);
10672
12194
  if (secretLiteral(a.key, a.value)) fact("secret-in-plain-env", `${where} passes ${a.key} to its build with the value written in the file.`, a.line);
10673
12195
  setting({ name: a.key, source: a.value == null || hasVar2(a.value) ? "computed" : "parameter", secret, line: a.line, ...a.value == null || hasVar2(a.value) ? { computed: true } : {}, ...!secret && a.value != null && !hasVar2(a.value) ? { default: a.value } : {} });
10674
12196
  }
10675
- if (image) know("Names the image", image, lineOf2(s, "image"));
12197
+ if (image) know("Names the image", image, lineOf3(s, "image"));
10676
12198
  } else if (image) {
10677
- know("Runs", imageWords2(image, later(image)), lineOf2(s, "image"), { name: "image", ...hasVar2(image) ? { computed: true } : {} });
12199
+ know("Runs", imageWords2(image, later(image)), lineOf3(s, "image"), { name: "image", ...hasVar2(image) ? { computed: true } : {} });
10678
12200
  const says = imageNotPinned(image, where);
10679
- if (says) fact("image-not-pinned", says, lineOf2(s, "image"));
12201
+ if (says) fact("image-not-pinned", says, lineOf3(s, "image"));
10680
12202
  } else if (get(s, "extends")) {
10681
12203
  const ex = get(s, "extends");
10682
- know("Builds on", `the service ${str2(get(ex, "service")) ?? str2(ex)}${str2(get(ex, "file")) ? ` in ${str2(get(ex, "file"))}` : ""}`, lineOf2(s, "extends"));
12204
+ know("Builds on", `the service ${str2(get(ex, "service")) ?? str2(ex)}${str2(get(ex, "file")) ? ` in ${str2(get(ex, "file"))}` : ""}`, lineOf3(s, "extends"));
10683
12205
  }
10684
12206
  const ent = get(s, "entrypoint"), cmd = get(s, "command");
10685
12207
  const cmdText = (n) => n?.t === "seq" ? commandText(list(n).map(str2)) : str2(n);
10686
- if (ent || cmd) know("Starts with", short4([cmdText(ent), cmdText(cmd)].filter(Boolean).join(" "), 120), lineOf2(s, ent ? "entrypoint" : "command"));
12208
+ if (ent || cmd) know("Starts with", short4([cmdText(ent), cmdText(cmd)].filter(Boolean).join(" "), 120), lineOf3(s, ent ? "entrypoint" : "command"));
10687
12209
  const deploy = get(s, "deploy");
10688
12210
  const replicas = str2(get(deploy, "replicas")) ?? str2(get(s, "scale"));
10689
- if (replicas) know("How many", `${replicas} cop${replicas === "1" ? "y" : "ies"}`, lineOf2(deploy, "replicas", lineOf2(s, "scale")));
12211
+ if (replicas) know("How many", `${replicas} cop${replicas === "1" ? "y" : "ies"}`, lineOf3(deploy, "replicas", lineOf3(s, "scale")));
10690
12212
  const ports = list(get(s, "ports")).map(portOf);
10691
12213
  for (const p of ports) {
10692
12214
  const local = p.ip && LOCAL.test(p.ip);
@@ -10696,13 +12218,13 @@ function readCompose(src, file = "compose.yaml") {
10696
12218
  if (!local && anyIp) fact("public-ingress", `${where} publishes ${p.host ? `port ${p.host}` : `port ${p.container} on a port Docker picks`} on every network address of the computer it runs on, so anyone who can reach that computer can reach it.`, p.line);
10697
12219
  }
10698
12220
  const expose = list(get(s, "expose")).map(str2);
10699
- if (expose.length) know("Open to the other services on", `port${expose.length === 1 ? "" : "s"} ${listWords2(expose)}`, lineOf2(s, "expose"));
12221
+ if (expose.length) know("Open to the other services on", `port${expose.length === 1 ? "" : "s"} ${listWords2(expose)}`, lineOf3(s, "expose"));
10700
12222
  const nm = str2(get(s, "network_mode"));
10701
- if (nm === "host") know("Network", "the computer's own network: every port it opens is open on the computer", lineOf2(s, "network_mode"));
12223
+ if (nm === "host") know("Network", "the computer's own network: every port it opens is open on the computer", lineOf3(s, "network_mode"));
10702
12224
  else if (nm?.startsWith("service:")) {
10703
12225
  const other = nm.slice(8);
10704
- know("Network", `shares the network of the service ${other}`, lineOf2(s, "network_mode"));
10705
- link(address, `services.${other}`, "runs-in", lineOf2(s, "network_mode"));
12226
+ know("Network", `shares the network of the service ${other}`, lineOf3(s, "network_mode"));
12227
+ link(address, `services.${other}`, "runs-in", lineOf3(s, "network_mode"));
10706
12228
  }
10707
12229
  for (const x of envEntries(get(s, "environment"))) {
10708
12230
  const secret = isSecretName(x.key);
@@ -10769,7 +12291,7 @@ function readCompose(src, file = "compose.yaml") {
10769
12291
  info.after.push(x);
10770
12292
  link(address, `services.${x.name}`, "uses", x.line);
10771
12293
  }
10772
- if (deps.length) know("Starts after", listWords2(deps.map((x) => `${x.name}${x.cond === "service_healthy" ? " (once it is healthy)" : x.cond === "service_completed_successfully" ? " (once it has finished successfully)" : ""}`)), lineOf2(s, "depends_on"));
12294
+ if (deps.length) know("Starts after", listWords2(deps.map((x) => `${x.name}${x.cond === "service_healthy" ? " (once it is healthy)" : x.cond === "service_completed_successfully" ? " (once it has finished successfully)" : ""}`)), lineOf3(s, "depends_on"));
10773
12295
  for (const nx of list(get(s, "networks")).length ? list(get(s, "networks")) : get(s, "networks")?.entries?.map((x) => ({ t: "str", v: x.key, line: x.line })) ?? []) {
10774
12296
  const nn = str2(nx);
10775
12297
  if (nn) {
@@ -10780,30 +12302,30 @@ function readCompose(src, file = "compose.yaml") {
10780
12302
  const hc = get(s, "healthcheck");
10781
12303
  if (hc) {
10782
12304
  const t = testWords(get(hc, "test"));
10783
- if (str2(get(hc, "disable")) === "true" || t === null) know("Health check", "turned off", lineOf2(s, "healthcheck"));
10784
- else know("Checks its health with", `${short4(t ?? "", 100)}${str2(get(hc, "interval")) ? `, every ${str2(get(hc, "interval"))}` : ""}`, lineOf2(s, "healthcheck"));
12305
+ if (str2(get(hc, "disable")) === "true" || t === null) know("Health check", "turned off", lineOf3(s, "healthcheck"));
12306
+ else know("Checks its health with", `${short4(t ?? "", 100)}${str2(get(hc, "interval")) ? `, every ${str2(get(hc, "interval"))}` : ""}`, lineOf3(s, "healthcheck"));
10785
12307
  }
10786
12308
  const restart = str2(get(s, "restart")) ?? str2(get(get(deploy, "restart_policy"), "condition"));
10787
- if (restart) know("Restarts", RESTART[restart.split(":")[0]] ?? restart, lineOf2(s, "restart", lineOf2(deploy, "restart_policy")));
12309
+ if (restart) know("Restarts", RESTART[restart.split(":")[0]] ?? restart, lineOf3(s, "restart", lineOf3(deploy, "restart_policy")));
10788
12310
  const user = str2(get(s, "user"));
10789
12311
  if (user) {
10790
12312
  const root2 = /^(root|0)(:.*)?$/.test(user);
10791
- know("Runs as", root2 ? "root, the user that can do anything" : `the user ${user}`, lineOf2(s, "user"));
10792
- if (root2) fact("runs-as-root", `${where} runs as root (user: ${user}).`, lineOf2(s, "user"));
12313
+ know("Runs as", root2 ? "root, the user that can do anything" : `the user ${user}`, lineOf3(s, "user"));
12314
+ if (root2) fact("runs-as-root", `${where} runs as root (user: ${user}).`, lineOf3(s, "user"));
10793
12315
  }
10794
12316
  if (str2(get(s, "privileged")) === "true") {
10795
- know("Privileged", "yes: it can do almost anything on the computer", lineOf2(s, "privileged"));
10796
- fact("privileged-container", `${where} is privileged (privileged: true), so it can do almost anything on the computer it runs on.`, lineOf2(s, "privileged"));
12317
+ know("Privileged", "yes: it can do almost anything on the computer", lineOf3(s, "privileged"));
12318
+ fact("privileged-container", `${where} is privileged (privileged: true), so it can do almost anything on the computer it runs on.`, lineOf3(s, "privileged"));
10797
12319
  }
10798
12320
  const caps = list(get(s, "cap_add")).map(str2);
10799
- if (caps.some((c) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(c))) fact("privileged-container", `${where} adds the ${caps.filter((c) => /ALL|SYS_ADMIN/i.test(c)).join(" and ")} capabilit${caps.length === 1 ? "y" : "ies"}, which gives it nearly the power of the computer itself.`, lineOf2(s, "cap_add"));
10800
- if (str2(get(s, "pid")) === "host") fact("privileged-container", `${where} shares every process on the computer (pid: host).`, lineOf2(s, "pid"));
12321
+ if (caps.some((c) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(c))) fact("privileged-container", `${where} adds the ${caps.filter((c) => /ALL|SYS_ADMIN/i.test(c)).join(" and ")} capabilit${caps.length === 1 ? "y" : "ies"}, which gives it nearly the power of the computer itself.`, lineOf3(s, "cap_add"));
12322
+ if (str2(get(s, "pid")) === "host") fact("privileged-container", `${where} shares every process on the computer (pid: host).`, lineOf3(s, "pid"));
10801
12323
  const lim = get(get(deploy, "resources"), "limits"), res = get(get(deploy, "resources"), "reservations");
10802
12324
  const amount = (m) => listWords2([str2(get(m, "cpus")) && cpuWords(str2(get(m, "cpus"))), str2(get(m, "memory")) && `${memWords(str2(get(m, "memory")))} of memory`].filter(Boolean));
10803
- if (res && amount(res)) know("Asks for", amount(res), lineOf2(get(deploy, "resources"), "reservations"));
10804
- if (lim && amount(lim)) know("Can use at most", amount(lim), lineOf2(get(deploy, "resources"), "limits"));
10805
- else if (str2(get(s, "mem_limit")) || str2(get(s, "cpus"))) know("Can use at most", listWords2([str2(get(s, "cpus")) && cpuWords(str2(get(s, "cpus"))), str2(get(s, "mem_limit")) && `${memWords(str2(get(s, "mem_limit")))} of memory`].filter(Boolean)), lineOf2(s, "mem_limit", lineOf2(s, "cpus")));
10806
- if (info.profiles.length) know("Only starts with", `the profile${info.profiles.length === 1 ? "" : "s"} ${orWords(info.profiles)}`, lineOf2(s, "profiles"));
12325
+ if (res && amount(res)) know("Asks for", amount(res), lineOf3(get(deploy, "resources"), "reservations"));
12326
+ if (lim && amount(lim)) know("Can use at most", amount(lim), lineOf3(get(deploy, "resources"), "limits"));
12327
+ else if (str2(get(s, "mem_limit")) || str2(get(s, "cpus"))) know("Can use at most", listWords2([str2(get(s, "cpus")) && cpuWords(str2(get(s, "cpus"))), str2(get(s, "mem_limit")) && `${memWords(str2(get(s, "mem_limit")))} of memory`].filter(Boolean)), lineOf3(s, "mem_limit", lineOf3(s, "cpus")));
12328
+ if (info.profiles.length) know("Only starts with", `the profile${info.profiles.length === 1 ? "" : "s"} ${orWords(info.profiles)}`, lineOf3(s, "profiles"));
10807
12329
  things.push({ kind: "resource", name: address, label: `Service ${name}`, resourceType: "compose-service", address, file, lines: [e.line, Math.max(e.line, lastLine3(s))], knows, choices: [] });
10808
12330
  starts.set(address, { name, line: e.line, info });
10809
12331
  }
@@ -11868,14 +13390,14 @@ function sayNativeShape(head, text2, innerNote) {
11868
13390
  }
11869
13391
  return null;
11870
13392
  }
11871
- var STATUS_NAMES = { CONTINUE: 100, OK: 200, CREATED: 201, ACCEPTED: 202, NO_CONTENT: 204, NoContent: 204, MOVED_PERMANENTLY: 301, FOUND: 302, BAD_REQUEST: 400, BadRequest: 400, UNAUTHORIZED: 401, Unauthorized: 401, FORBIDDEN: 403, Forbidden: 403, NOT_FOUND: 404, NotFound: 404, CONFLICT: 409, Conflict: 409, UNPROCESSABLE_ENTITY: 422, UnprocessableEntity: 422, TOO_MANY_REQUESTS: 429, INTERNAL_SERVER_ERROR: 500, InternalServerError: 500, StatusOK: 200, StatusCreated: 201, StatusAccepted: 202, StatusNoContent: 204, StatusBadRequest: 400, StatusUnauthorized: 401, StatusForbidden: 403, StatusNotFound: 404, StatusConflict: 409, StatusUnprocessableEntity: 422, StatusInternalServerError: 500 };
13393
+ var STATUS_NAMES2 = { CONTINUE: 100, OK: 200, CREATED: 201, ACCEPTED: 202, NO_CONTENT: 204, NoContent: 204, MOVED_PERMANENTLY: 301, FOUND: 302, BAD_REQUEST: 400, BadRequest: 400, UNAUTHORIZED: 401, Unauthorized: 401, FORBIDDEN: 403, Forbidden: 403, NOT_FOUND: 404, NotFound: 404, CONFLICT: 409, Conflict: 409, UNPROCESSABLE_ENTITY: 422, UnprocessableEntity: 422, TOO_MANY_REQUESTS: 429, INTERNAL_SERVER_ERROR: 500, InternalServerError: 500, StatusOK: 200, StatusCreated: 201, StatusAccepted: 202, StatusNoContent: 204, StatusBadRequest: 400, StatusUnauthorized: 401, StatusForbidden: 403, StatusNotFound: 404, StatusConflict: 409, StatusUnprocessableEntity: 422, StatusInternalServerError: 500 };
11872
13394
  var SUCCESS_WORDS = { 200: "", 201: "201 Created", 202: "202 Accepted", 204: "204 No Content" };
11873
13395
  function statusOf(text2) {
11874
13396
  const t = String(text2 || "").trim();
11875
13397
  let m;
11876
13398
  if (m = t.match(/^(\d{3})$/)) return Number(m[1]);
11877
13399
  if ((m = t.match(/HTTP_(\d{3})/)) || (m = t.match(/Status(\d{3})/))) return Number(m[1]);
11878
- if ((m = t.match(/(?:^|\.)(\w+)$/)) && STATUS_NAMES[m[1]]) return STATUS_NAMES[m[1]];
13400
+ if ((m = t.match(/(?:^|\.)(\w+)$/)) && STATUS_NAMES2[m[1]]) return STATUS_NAMES2[m[1]];
11879
13401
  return null;
11880
13402
  }
11881
13403
  function payloadWords(arg) {
@@ -12192,7 +13714,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
12192
13714
  else if (text2.includes("\n") && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first)) && !/=>\s*\{?\s*$/.test(first) && text2.length < 2e3 && balancedText(text2) && (!/\{\s*$/.test(text2.split("\n")[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first))) {
12193
13715
  const lines = text2.split("\n");
12194
13716
  const joined = lines.map((l) => l.trim()).join(" ");
12195
- if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || "")) first = joined;
13717
+ if (!bracketsClosed2(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || "")) first = joined;
12196
13718
  }
12197
13719
  let jmp;
12198
13720
  const mls = text2.match(/^(?:let(?:\s+mut)?|const|var|val)\s+([A-Za-z_]\w*)(?:\s*:[^=\n]+)?\s*=\s*(?:r#*)?("""|")/);
@@ -12249,7 +13771,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
12249
13771
  return { kind: "branch", says: `If ${sayCodeCondition(cond)}`, cond, code: code3, inline: body2 };
12250
13772
  }
12251
13773
  }
12252
- if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && balancedText(inl[1]) && balancedText(inl[3]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/\[[^\]]*\bfor\b/.test(head)) {
13774
+ if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed2(inl[1]) && balancedText(inl[1]) && balancedText(inl[3]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/\[[^\]]*\bfor\b/.test(head)) {
12253
13775
  const cond = sayCodeCondition(inl[3]);
12254
13776
  return { kind: "branch", says: inl[2] === "unless" ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === "unless", code: code3, inline: inl[1] };
12255
13777
  }
@@ -12571,7 +14093,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
12571
14093
  }
12572
14094
  var spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...s.start != null && s.end != null ? { start: s.start, end: s.end } : {} });
12573
14095
  var BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
12574
- var bracketsClosed = (x) => {
14096
+ var bracketsClosed2 = (x) => {
12575
14097
  let d = 0;
12576
14098
  for (const ch of x) {
12577
14099
  if ("([{".includes(ch)) d++;
@@ -13623,6 +15145,40 @@ function indentStatements(body2, { depthKey = "indent" } = {}) {
13623
15145
  return out;
13624
15146
  }
13625
15147
 
15148
+ // src/money.mjs
15149
+ var MoneyError = class extends Error {
15150
+ };
15151
+ var MONEY_DEFAULT_MINOR_UNITS = 2;
15152
+ var DECIMAL = /^([+-])?(\d+)(?:\.(\d+))?$/;
15153
+ function parseMoney(text2, { minorUnits = MONEY_DEFAULT_MINOR_UNITS, allowDollar = false } = {}) {
15154
+ let t = typeof text2 === "number" ? numberToDecimalText(text2) : String(text2 ?? "").trim();
15155
+ if (allowDollar) {
15156
+ const d = t.replace(/,/g, "").match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
15157
+ if (d) t = `${d[1] || d[2] ? "-" : ""}${d[3]}`;
15158
+ }
15159
+ const m = t.match(DECIMAL);
15160
+ if (!m) throw new MoneyError(`"${text2}" is not an amount. Write digits with an optional decimal point, such as 12.30.`);
15161
+ const frac = m[3] || "";
15162
+ const extra = frac.slice(minorUnits);
15163
+ if (/[1-9]/.test(extra)) throw new MoneyError(`${t} has more decimal places than Money's ${minorUnits} minor unit${minorUnits === 1 ? "" : "s"}; Thunder will not round it silently.`);
15164
+ const minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, "0"));
15165
+ return m[1] === "-" ? -minor : minor;
15166
+ }
15167
+ function formatMoney(minor, { minorUnits = MONEY_DEFAULT_MINOR_UNITS } = {}) {
15168
+ const v = BigInt(minor);
15169
+ const neg = v < 0n;
15170
+ const digits = (neg ? -v : v).toString().padStart(minorUnits + 1, "0");
15171
+ const whole = minorUnits ? digits.slice(0, -minorUnits) : digits;
15172
+ const frac = minorUnits ? `.${digits.slice(-minorUnits)}` : "";
15173
+ return `${neg ? "-" : ""}${whole}${frac}`;
15174
+ }
15175
+ function numberToDecimalText(n) {
15176
+ if (typeof n !== "number" || !Number.isFinite(n)) throw new MoneyError(`${n} is not a finite amount.`);
15177
+ const s = String(n);
15178
+ if (/e/i.test(s)) throw new MoneyError(`${s} is too large or too small to be an exact amount.`);
15179
+ return s;
15180
+ }
15181
+
13626
15182
  // src/expr.mjs
13627
15183
  var ExprError = class extends Error {
13628
15184
  };
@@ -13844,6 +15400,8 @@ function evalNode(n, inputs) {
13844
15400
  case "arith": {
13845
15401
  const a = Number(evalNode(n.a, inputs));
13846
15402
  const b = Number(evalNode(n.b, inputs));
15403
+ const exact = decimalArith(n.op, a, b);
15404
+ if (exact !== null) return exact;
13847
15405
  const r = n.op === "+" ? a + b : n.op === "-" ? a - b : n.op === "*" ? a * b : n.op === "/" ? a / b : a % b;
13848
15406
  return Number.isFinite(r) ? r : null;
13849
15407
  }
@@ -13870,6 +15428,37 @@ function evalNode(n, inputs) {
13870
15428
  throw new ExprError(`unknown node ${n.k}`);
13871
15429
  }
13872
15430
  }
15431
+ var PLAIN_DECIMAL = /^(-)?(\d+)(?:\.(\d+))?$/;
15432
+ function decimalParts(x) {
15433
+ if (!Number.isFinite(x)) return null;
15434
+ const m = String(x).match(PLAIN_DECIMAL);
15435
+ if (!m) return null;
15436
+ const frac = m[3] || "";
15437
+ const int = BigInt(m[2] + frac);
15438
+ return { int: m[1] ? -int : int, scale: frac.length };
15439
+ }
15440
+ function decimalArith(op, a, b) {
15441
+ if (op !== "+" && op !== "-" && op !== "*") return null;
15442
+ const x = decimalParts(a);
15443
+ const y = decimalParts(b);
15444
+ if (!x || !y) return null;
15445
+ let int;
15446
+ let scale;
15447
+ if (op === "*") {
15448
+ int = x.int * y.int;
15449
+ scale = x.scale + y.scale;
15450
+ } else {
15451
+ scale = Math.max(x.scale, y.scale);
15452
+ const xi = x.int * 10n ** BigInt(scale - x.scale);
15453
+ const yi = y.int * 10n ** BigInt(scale - y.scale);
15454
+ int = op === "+" ? xi + yi : xi - yi;
15455
+ }
15456
+ const neg = int < 0n;
15457
+ const digits = (neg ? -int : int).toString().padStart(scale + 1, "0");
15458
+ const text2 = scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
15459
+ const r = Number(`${neg ? "-" : ""}${text2}`);
15460
+ return Number.isFinite(r) ? r : null;
15461
+ }
13873
15462
  function eq(a, b) {
13874
15463
  const na = asNum(a);
13875
15464
  const nb = asNum(b);
@@ -14927,7 +16516,8 @@ var SEMANTIC = {
14927
16516
  timestamp: { type: "string", format: "date-time" },
14928
16517
  duration: { type: "string", format: "duration" },
14929
16518
  uuid: { type: "string", format: "uuid" },
14930
- money: { type: "number" },
16519
+ // Thunder Money is an exact decimal string ("12.30"), never a JSON number a consumer would read as a float.
16520
+ money: { type: "string", pattern: "^-?[0-9]+(\\.[0-9]{1,2})?$", description: "Thunder Money: an exact decimal amount with up to 2 minor units, as a string." },
14931
16521
  currency: { type: "string" },
14932
16522
  percentage: { type: "number", minimum: 0, maximum: 100 },
14933
16523
  secret: { type: "string", writeOnly: true },
@@ -14955,12 +16545,12 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
14955
16545
  var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
14956
16546
 
14957
16547
  // src/emit.mjs
14958
- var COMPILER_VERSION = "1.0.4";
16548
+ var COMPILER_VERSION = "1.1.0";
14959
16549
 
14960
16550
  // src/lift.mjs
14961
16551
  var IR_SCHEMA_VERSION = "0.1.0";
14962
16552
  var LINE_STARTS = /* @__PURE__ */ new Map();
14963
- var lineOf3 = (source, index) => {
16553
+ var lineOf4 = (source, index) => {
14964
16554
  let starts = LINE_STARTS.get(source);
14965
16555
  if (!starts) {
14966
16556
  starts = [0];
@@ -14995,10 +16585,10 @@ function extractFactsTypeScript(source, file = "input.ts") {
14995
16585
  functions.push({
14996
16586
  name,
14997
16587
  file,
14998
- line: lineOf3(source, idx),
16588
+ line: lineOf4(source, idx),
14999
16589
  parameters: parseParams(paramsRaw || ""),
15000
16590
  returnType: ret ? ret.trim().replace(/[{=].*$/, "").trim() : null,
15001
- evidence: [{ kind: "function_signature", file, line: lineOf3(source, idx) }]
16591
+ evidence: [{ kind: "function_signature", file, line: lineOf4(source, idx) }]
15002
16592
  });
15003
16593
  };
15004
16594
  let m;
@@ -15008,13 +16598,13 @@ function extractFactsTypeScript(source, file = "input.ts") {
15008
16598
  while (m = arrow.exec(source)) addFn(m[1], m[2], m[3], m.index);
15009
16599
  const tests = [];
15010
16600
  const testRe = /\b(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]/g;
15011
- while (m = testRe.exec(source)) tests.push({ name: m[1], file, line: lineOf3(source, m.index) });
16601
+ while (m = testRe.exec(source)) tests.push({ name: m[1], file, line: lineOf4(source, m.index) });
15012
16602
  const errors = [];
15013
16603
  const errSeen = /* @__PURE__ */ new Set();
15014
16604
  const addErr = (name, idx) => {
15015
16605
  if (name && !errSeen.has(name)) {
15016
16606
  errSeen.add(name);
15017
- errors.push({ name, file, line: lineOf3(source, idx) });
16607
+ errors.push({ name, file, line: lineOf4(source, idx) });
15018
16608
  }
15019
16609
  };
15020
16610
  const classErr = /class\s+([A-Za-z_$][\w$]*(?:Error|Exception))\b/g;
@@ -15057,7 +16647,7 @@ function extractFactsRust(source, file = "input.rs") {
15057
16647
  const testNames = /* @__PURE__ */ new Set();
15058
16648
  const testRe = /#\[\s*(?:tokio::)?test\s*\][\s\S]*?fn\s+(\w+)/g;
15059
16649
  while (m = testRe.exec(source)) {
15060
- tests.push({ name: m[1], file, line: lineOf3(source, m.index) });
16650
+ tests.push({ name: m[1], file, line: lineOf4(source, m.index) });
15061
16651
  testNames.add(m[1]);
15062
16652
  }
15063
16653
  const functions = [];
@@ -15070,10 +16660,10 @@ function extractFactsRust(source, file = "input.rs") {
15070
16660
  functions.push({
15071
16661
  name,
15072
16662
  file,
15073
- line: lineOf3(source, m.index),
16663
+ line: lineOf4(source, m.index),
15074
16664
  parameters: parseRustParams(m[2] || ""),
15075
16665
  returnType: m[3] ? m[3].trim() : null,
15076
- evidence: [{ kind: "function_signature", file, line: lineOf3(source, m.index) }]
16666
+ evidence: [{ kind: "function_signature", file, line: lineOf4(source, m.index) }]
15077
16667
  });
15078
16668
  }
15079
16669
  const errors = [];
@@ -15084,7 +16674,7 @@ function extractFactsRust(source, file = "input.rs") {
15084
16674
  const v = raw.trim().replace(/[({].*$/s, "").trim();
15085
16675
  if (v && /^[A-Z]/.test(v) && !seenErr.has(v)) {
15086
16676
  seenErr.add(v);
15087
- errors.push({ name: v, source: m[1], file, line: lineOf3(source, m.index) });
16677
+ errors.push({ name: v, source: m[1], file, line: lineOf4(source, m.index) });
15088
16678
  }
15089
16679
  }
15090
16680
  }
@@ -15107,7 +16697,7 @@ function extractFactsPerl(source, file = "input.pl") {
15107
16697
  const mm = after.match(/my\s*\(([^)]*)\)\s*=\s*@_/);
15108
16698
  if (mm) params = mm[1].split(",").map((s) => s.trim().replace(/^\$/, "")).filter(Boolean).map((n) => ({ name: n, type: "Unknown" }));
15109
16699
  }
15110
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: params, returnType: null, evidence: [{ kind: "sub", file, line: lineOf3(source, m.index) }] });
16700
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: params, returnType: null, evidence: [{ kind: "sub", file, line: lineOf4(source, m.index) }] });
15111
16701
  }
15112
16702
  const errors = [];
15113
16703
  const seenErr = /* @__PURE__ */ new Set();
@@ -15117,7 +16707,7 @@ function extractFactsPerl(source, file = "input.pl") {
15117
16707
  const key = s.toLowerCase();
15118
16708
  if (s && !seenErr.has(key)) {
15119
16709
  seenErr.add(key);
15120
- errors.push({ name: s, file, line: lineOf3(source, m.index) });
16710
+ errors.push({ name: s, file, line: lineOf4(source, m.index) });
15121
16711
  }
15122
16712
  }
15123
16713
  const tests = [];
@@ -15126,7 +16716,7 @@ function extractFactsPerl(source, file = "input.pl") {
15126
16716
  const k = name.toLowerCase();
15127
16717
  if (name && !seenT.has(k)) {
15128
16718
  seenT.add(k);
15129
- tests.push({ name, file, line: lineOf3(source, idx) });
16719
+ tests.push({ name, file, line: lineOf4(source, idx) });
15130
16720
  }
15131
16721
  };
15132
16722
  const subtestRe = /subtest\s+["']([^"']+)["']/g;
@@ -15150,7 +16740,7 @@ function parseTypeFirstParams(raw) {
15150
16740
  var addErrOf = (errors, seen, source) => (name, idx) => {
15151
16741
  if (name && !seen.has(name)) {
15152
16742
  seen.add(name);
15153
- errors.push({ name, file: source._file, line: lineOf3(source._src, idx) });
16743
+ errors.push({ name, file: source._file, line: lineOf4(source._src, idx) });
15154
16744
  }
15155
16745
  };
15156
16746
  function extractFactsPython(source, file = "input.py") {
@@ -15162,7 +16752,7 @@ function extractFactsPython(source, file = "input.py") {
15162
16752
  while (m = fnRe.exec(source)) {
15163
16753
  const name = m[1];
15164
16754
  if (/^test_/.test(name)) {
15165
- tests.push({ name, file, line: lineOf3(source, m.index) });
16755
+ tests.push({ name, file, line: lineOf4(source, m.index) });
15166
16756
  continue;
15167
16757
  }
15168
16758
  if (seen.has(name)) continue;
@@ -15172,7 +16762,7 @@ function extractFactsPython(source, file = "input.py") {
15172
16762
  const mm = nd.match(/^(\w+)\s*:\s*(.+)$/);
15173
16763
  return mm ? { name: mm[1], type: mm[2].trim() } : { name: nd, type: null };
15174
16764
  });
15175
- functions.push({ name, file, line: lineOf3(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters: params, returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "def", file, line: lineOf3(source, m.index) }] });
16765
+ functions.push({ name, file, line: lineOf4(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters: params, returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "def", file, line: lineOf4(source, m.index) }] });
15176
16766
  }
15177
16767
  const errors = [];
15178
16768
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15197,12 +16787,12 @@ function extractFactsJava(source, file = "input.java") {
15197
16787
  if (["if", "for", "while", "switch", "catch", "return"].includes(name)) continue;
15198
16788
  if (["class", "interface", "enum", "new", "return"].includes(ret)) continue;
15199
16789
  if (testMethods.has(name)) {
15200
- if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf3(source, m.index) });
16790
+ if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf4(source, m.index) });
15201
16791
  continue;
15202
16792
  }
15203
16793
  if (seen.has(name)) continue;
15204
16794
  seen.add(name);
15205
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "method", file, line: lineOf3(source, m.index) }] });
16795
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "method", file, line: lineOf4(source, m.index) }] });
15206
16796
  }
15207
16797
  const errors = [];
15208
16798
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15227,12 +16817,12 @@ function extractFactsCSharp(source, file = "input.cs") {
15227
16817
  const name = m[2];
15228
16818
  if (["if", "for", "while", "switch", "catch", "return", "using", "lock"].includes(name)) continue;
15229
16819
  if (testMethods.has(name)) {
15230
- if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf3(source, m.index) });
16820
+ if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf4(source, m.index) });
15231
16821
  continue;
15232
16822
  }
15233
16823
  if (seen.has(name)) continue;
15234
16824
  seen.add(name);
15235
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "method", file, line: lineOf3(source, m.index) }] });
16825
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "method", file, line: lineOf4(source, m.index) }] });
15236
16826
  }
15237
16827
  const errors = [];
15238
16828
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15253,7 +16843,7 @@ function extractFactsGo(source, file = "input.go") {
15253
16843
  const name = m[1];
15254
16844
  const params = m[2] || "";
15255
16845
  if (/^Test/.test(name) && /testing\.[TBM]/.test(params)) {
15256
- tests.push({ name, file, line: lineOf3(source, m.index) });
16846
+ tests.push({ name, file, line: lineOf4(source, m.index) });
15257
16847
  continue;
15258
16848
  }
15259
16849
  if (seen.has(name)) continue;
@@ -15262,7 +16852,7 @@ function extractFactsGo(source, file = "input.go") {
15262
16852
  const parts = p.split(/\s+/);
15263
16853
  return parts.length >= 2 ? { name: parts[0], type: parts.slice(1).join(" ").replace(/^[*&]+/, "") } : { name: p, type: null };
15264
16854
  });
15265
- functions.push({ name, file, line: lineOf3(source, m.index), parameters, returnType: (m[3] || "").trim() || null, evidence: [{ kind: "func", file, line: lineOf3(source, m.index) }] });
16855
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters, returnType: (m[3] || "").trim() || null, evidence: [{ kind: "func", file, line: lineOf4(source, m.index) }] });
15266
16856
  }
15267
16857
  const errors = [];
15268
16858
  const seenErr = /* @__PURE__ */ new Set();
@@ -15270,7 +16860,7 @@ function extractFactsGo(source, file = "input.go") {
15270
16860
  const k = String(n).toLowerCase();
15271
16861
  if (n && !seenErr.has(k)) {
15272
16862
  seenErr.add(k);
15273
- errors.push({ name: n, file, line: lineOf3(source, idx) });
16863
+ errors.push({ name: n, file, line: lineOf4(source, idx) });
15274
16864
  }
15275
16865
  };
15276
16866
  let mm;
@@ -15286,7 +16876,7 @@ function extractFactsCpp(source, file = "input.cpp") {
15286
16876
  const tests = [];
15287
16877
  const seen = /* @__PURE__ */ new Set();
15288
16878
  const tr = /\bTEST(?:_F|_P)?\s*\(\s*\w+\s*,\s*(\w+)\s*\)/g;
15289
- while (m = tr.exec(source)) tests.push({ name: m[1], file, line: lineOf3(source, m.index) });
16879
+ while (m = tr.exec(source)) tests.push({ name: m[1], file, line: lineOf4(source, m.index) });
15290
16880
  const CTRL = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "sizeof", "else", "do"]);
15291
16881
  const fnRe = /(?:^|\n)[ \t]*((?:[A-Za-z_][\w:]*(?:\s*<[^;{>]*>)?[\s*&]+)+)([A-Za-z_]\w*)\s*\(([^)]*)\)\s*(?:const|noexcept|override)?\s*\{/g;
15292
16882
  while (m = fnRe.exec(source)) {
@@ -15295,7 +16885,7 @@ function extractFactsCpp(source, file = "input.cpp") {
15295
16885
  if (CTRL.has(name)) continue;
15296
16886
  if (seen.has(name)) continue;
15297
16887
  seen.add(name);
15298
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "function", file, line: lineOf3(source, m.index) }] });
16888
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: parseTypeFirstParams(m[3] || ""), returnType: ret, evidence: [{ kind: "function", file, line: lineOf4(source, m.index) }] });
15299
16889
  }
15300
16890
  const errors = [];
15301
16891
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15315,7 +16905,7 @@ function extractFactsPhp(source, file = "input.php") {
15315
16905
  while (m = fnRe.exec(source)) {
15316
16906
  const name = m[1];
15317
16907
  if (/^test/i.test(name)) {
15318
- tests.push({ name, file, line: lineOf3(source, m.index) });
16908
+ tests.push({ name, file, line: lineOf4(source, m.index) });
15319
16909
  continue;
15320
16910
  }
15321
16911
  if (seen.has(name)) continue;
@@ -15324,7 +16914,7 @@ function extractFactsPhp(source, file = "input.php") {
15324
16914
  const mm2 = p.match(/^(?:\??([\w\\|]+)\s+)?[&.]*\$(\w+)/);
15325
16915
  return mm2 ? { name: mm2[2], type: mm2[1] || null } : { name: p.replace(/[^\w]/g, ""), type: null };
15326
16916
  });
15327
- functions.push({ name, file, line: lineOf3(source, m.index), parameters, returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "function", file, line: lineOf3(source, m.index) }] });
16917
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters, returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "function", file, line: lineOf4(source, m.index) }] });
15328
16918
  }
15329
16919
  const errors = [];
15330
16920
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15344,20 +16934,20 @@ function extractFactsRuby(source, file = "input.rb") {
15344
16934
  while (m = fnRe.exec(source)) {
15345
16935
  const name = m[1];
15346
16936
  if (/^test_/.test(name)) {
15347
- tests.push({ name, file, line: lineOf3(source, m.index) });
16937
+ tests.push({ name, file, line: lineOf4(source, m.index) });
15348
16938
  continue;
15349
16939
  }
15350
16940
  if (seen.has(name)) continue;
15351
16941
  seen.add(name);
15352
16942
  const parameters = splitTopLevel(m[2] || "", ",").map((p) => p.trim()).filter(Boolean).map((p) => ({ name: p.split(/[:=]/)[0].trim().replace(/^[*&]+/, ""), type: null }));
15353
- functions.push({ name, file, line: lineOf3(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters, returnType: null, evidence: [{ kind: "def", file, line: lineOf3(source, m.index) }] });
16943
+ functions.push({ name, file, line: lineOf4(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters, returnType: null, evidence: [{ kind: "def", file, line: lineOf4(source, m.index) }] });
15354
16944
  }
15355
16945
  const seenT = /* @__PURE__ */ new Set();
15356
16946
  const addTest = (n, idx) => {
15357
16947
  const k = String(n).toLowerCase();
15358
16948
  if (n && !seenT.has(k)) {
15359
16949
  seenT.add(k);
15360
- tests.push({ name: n, file, line: lineOf3(source, idx) });
16950
+ tests.push({ name: n, file, line: lineOf4(source, idx) });
15361
16951
  }
15362
16952
  };
15363
16953
  const itRe = /\b(?:it|test|describe|context|specify)\s+["']([^"']+)["']/g;
@@ -15367,7 +16957,7 @@ function extractFactsRuby(source, file = "input.rb") {
15367
16957
  const addErr = (n, idx) => {
15368
16958
  if (n && !seenErr.has(n)) {
15369
16959
  seenErr.add(n);
15370
- errors.push({ name: n, file, line: lineOf3(source, idx) });
16960
+ errors.push({ name: n, file, line: lineOf4(source, idx) });
15371
16961
  }
15372
16962
  };
15373
16963
  const ce = /class\s+(\w*(?:Error|Exception))\s*</g;
@@ -15398,12 +16988,12 @@ function extractFactsKotlin(source, file = "input.kt") {
15398
16988
  while (m = fnRe.exec(source)) {
15399
16989
  const name = m[1] || m[2];
15400
16990
  if (testMethods.has(name)) {
15401
- if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf3(source, m.index) });
16991
+ if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf4(source, m.index) });
15402
16992
  continue;
15403
16993
  }
15404
16994
  if (seen.has(name)) continue;
15405
16995
  seen.add(name);
15406
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: parseNameColonTypeParams(m[3] || ""), returnType: m[4] ? m[4].trim() : null, evidence: [{ kind: "fun", file, line: lineOf3(source, m.index) }] });
16996
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: parseNameColonTypeParams(m[3] || ""), returnType: m[4] ? m[4].trim() : null, evidence: [{ kind: "fun", file, line: lineOf4(source, m.index) }] });
15407
16997
  }
15408
16998
  const errors = [];
15409
16999
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15424,7 +17014,7 @@ function extractFactsSwift(source, file = "input.swift") {
15424
17014
  while (m = fnRe.exec(source)) {
15425
17015
  const name = m[2] || m[3];
15426
17016
  if (m[1] || xctest && /^test/.test(name)) {
15427
- if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf3(source, m.index + (m[1] || "").length) });
17017
+ if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf4(source, m.index + (m[1] || "").length) });
15428
17018
  continue;
15429
17019
  }
15430
17020
  if (seen.has(name)) continue;
@@ -15433,7 +17023,7 @@ function extractFactsSwift(source, file = "input.swift") {
15433
17023
  const q = p.replace(/=.*$/, "").match(/^(?:\w+\s+)?(\w+)\s*:\s*(.+)$/);
15434
17024
  return q ? { name: q[1], type: q[2].trim() } : { name: p, type: null };
15435
17025
  });
15436
- functions.push({ name, file, line: lineOf3(source, m.index), parameters, returnType: m[5] ? m[5].trim() : null, evidence: [{ kind: "func", file, line: lineOf3(source, m.index) }] });
17026
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters, returnType: m[5] ? m[5].trim() : null, evidence: [{ kind: "func", file, line: lineOf4(source, m.index) }] });
15437
17027
  }
15438
17028
  const errors = [];
15439
17029
  const addErr = addErrOf(errors, /* @__PURE__ */ new Set(), { _src: source, _file: file });
@@ -15454,14 +17044,14 @@ function extractFactsScala(source, file = "input.scala") {
15454
17044
  const name = m[1];
15455
17045
  if (seen.has(name)) continue;
15456
17046
  seen.add(name);
15457
- functions.push({ name, file, line: lineOf3(source, m.index), parameters: parseNameColonTypeParams(m[2] || ""), returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "def", file, line: lineOf3(source, m.index) }] });
17047
+ functions.push({ name, file, line: lineOf4(source, m.index), parameters: parseNameColonTypeParams(m[2] || ""), returnType: m[3] ? m[3].trim() : null, evidence: [{ kind: "def", file, line: lineOf4(source, m.index) }] });
15458
17048
  }
15459
17049
  const seenT = /* @__PURE__ */ new Set();
15460
17050
  const addTest = (n, idx) => {
15461
17051
  const k = String(n).toLowerCase();
15462
17052
  if (n && !seenT.has(k)) {
15463
17053
  seenT.add(k);
15464
- tests.push({ name: n, file, line: lineOf3(source, idx) });
17054
+ tests.push({ name: n, file, line: lineOf4(source, idx) });
15465
17055
  }
15466
17056
  };
15467
17057
  const tr = /\btest\s*\(\s*"([^"]+)"/g;
@@ -15487,7 +17077,7 @@ function extractFactsElixir(source, file = "input.ex") {
15487
17077
  const k = String(n).toLowerCase();
15488
17078
  if (n && !seenT.has(k)) {
15489
17079
  seenT.add(k);
15490
- tests.push({ name: n, file, line: lineOf3(source, idx) });
17080
+ tests.push({ name: n, file, line: lineOf4(source, idx) });
15491
17081
  }
15492
17082
  };
15493
17083
  const tr = /\btest\s+"([^"]+)"/g;
@@ -15498,14 +17088,14 @@ function extractFactsElixir(source, file = "input.ex") {
15498
17088
  if (seen.has(name)) continue;
15499
17089
  seen.add(name);
15500
17090
  const parameters = splitTopLevel(m[2] || "", ",").map((p) => p.trim()).filter(Boolean).map((p) => ({ name: p.split(/\\\\/)[0].trim().replace(/^%\{?/, "").replace(/[^\w].*$/, "") || p, type: null }));
15501
- functions.push({ name, file, line: lineOf3(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters, returnType: null, evidence: [{ kind: "def", file, line: lineOf3(source, m.index) }] });
17091
+ functions.push({ name, file, line: lineOf4(source, m.index), indent: (m[0].match(/^[ \t]*/) || [""])[0].length, parameters, returnType: null, evidence: [{ kind: "def", file, line: lineOf4(source, m.index) }] });
15502
17092
  }
15503
17093
  const errors = [];
15504
17094
  const seenErr = /* @__PURE__ */ new Set();
15505
17095
  const addErr = (n, idx) => {
15506
17096
  if (n && !seenErr.has(n)) {
15507
17097
  seenErr.add(n);
15508
- errors.push({ name: n, file, line: lineOf3(source, idx) });
17098
+ errors.push({ name: n, file, line: lineOf4(source, idx) });
15509
17099
  }
15510
17100
  };
15511
17101
  const modErr = /defmodule\s+([\w.]*(?:Error|Exception))\b/g;
@@ -16848,7 +18438,7 @@ function varWords(name) {
16848
18438
  if (SPECIAL[name]) return SPECIAL[name];
16849
18439
  return words7(name.replace(/\[.*$/, "")) || name;
16850
18440
  }
16851
- var asCode2 = (code3, n = 100) => {
18441
+ var asCode3 = (code3, n = 100) => {
16852
18442
  const t = String(code3).replace(/\s+/g, " ").trim();
16853
18443
  return `\`${t.length > n ? `${t.slice(0, n - 1)}\u2026` : t}\``;
16854
18444
  };
@@ -16999,15 +18589,15 @@ function outputWords(cmdText) {
16999
18589
  const n = nodes[0];
17000
18590
  if (!n) return "the output of a command";
17001
18591
  const say = sayNode(n);
17002
- return say && !isCode(say) ? `the output of ${gerund(say)}` : `the output of ${asCode2(cmdText)}`;
18592
+ return say && !isCode(say) ? `the output of ${gerund(say)}` : `the output of ${asCode3(cmdText)}`;
17003
18593
  } catch {
17004
18594
  return "the output of a command";
17005
18595
  }
17006
18596
  }
17007
18597
  function valueWords4(p) {
17008
18598
  if (p.cmd != null) return outputWords(p.cmd);
17009
- if (p.arith != null) return arithWords(p.arith) ?? asCode2(p.code);
17010
- return p.v ?? asCode2(p.code);
18599
+ if (p.arith != null) return arithWords(p.arith) ?? asCode3(p.code);
18600
+ return p.v ?? asCode3(p.code);
17011
18601
  }
17012
18602
  function sayWord(raw) {
17013
18603
  const parts = partsOf(raw).filter((p) => !p.glob);
@@ -17252,7 +18842,7 @@ function nodeCond(n, neg) {
17252
18842
  if (n.type === "andor" && n.rest.every((r) => r.op === "||")) return [n.first, ...n.rest.map((r) => r.node)].map((x) => nodeCond(x, neg)).join(neg ? " and " : " or ");
17253
18843
  if (n.type === "arith") {
17254
18844
  const lone = n.expr.trim().match(/^\$?([A-Za-z_]\w*)$/);
17255
- const w = lone ? `${varWords(lone[1])} is not 0` : arithWords(n.expr) ?? asCode2(`((${n.expr}))`);
18845
+ const w = lone ? `${varWords(lone[1])} is not 0` : arithWords(n.expr) ?? asCode3(`((${n.expr}))`);
17256
18846
  return neg ? `not: ${w}` : w;
17257
18847
  }
17258
18848
  if (n.type === "group" || n.type === "subshell") return condWords2(n.body, neg);
@@ -17385,7 +18975,7 @@ function assignWords(a, { exported = false, readonly = false } = {}) {
17385
18975
  const pos = val.match(/^"?\$\{?([1-9])(?:(:?)[-=]([^}]*))?\}?"?$/);
17386
18976
  if (pos) return `Takes ${who} from the ${ORDINAL[pos[1]]} input${pos[3] ? ` (${sayWord(pos[3])} when it is ${pos[2] ? "empty or " : ""}not given)` : ""}${tail}`;
17387
18977
  const parts = partsOf(val).filter((p) => !p.glob);
17388
- if (parts.length === 1 && parts[0].arith != null) return `Works out ${who}: ${arithWords(parts[0].arith) ?? asCode2(parts[0].code)}${tail}`;
18978
+ if (parts.length === 1 && parts[0].arith != null) return `Works out ${who}: ${arithWords(parts[0].arith) ?? asCode3(parts[0].code)}${tail}`;
17389
18979
  if (plus) return `Adds ${sayWord(val)} to ${who}${tail}`;
17390
18980
  return `Sets ${who} to ${sayWord(val)}${tail}`;
17391
18981
  }
@@ -17715,7 +19305,7 @@ function makeStepper(src) {
17715
19305
  const [init, cond] = n.cstyle.split(";").map((x) => x.trim());
17716
19306
  const im = init.match(/^(\w+)\s*=\s*(.+)$/);
17717
19307
  const from = im && arithWords(im[2]), wh = cond ? arithWords(cond) : "";
17718
- says = im && from && wh != null ? `Counts ${varWords(im[1])} from ${from}${wh ? ` while ${wh}` : ""}` : `Repeats: ${asCode2(`for ((${n.cstyle}))`)}`;
19308
+ says = im && from && wh != null ? `Counts ${varWords(im[1])} from ${from}${wh ? ` while ${wh}` : ""}` : `Repeats: ${asCode3(`for ((${n.cstyle}))`)}`;
17719
19309
  } else {
17720
19310
  const items = n.items;
17721
19311
  let what;
@@ -17751,7 +19341,7 @@ function makeStepper(src) {
17751
19341
  else if (pats.every((p) => !isGlob(p))) {
17752
19342
  const ws = pats.map(sayWord);
17753
19343
  says = `When it is ${ws.length > 1 ? `${ws.slice(0, -1).join(", ")} or ${ws.at(-1)}` : ws[0]}`;
17754
- } else says = `When it matches ${pats.map((p) => asCode2(p)).join(" or ")}`;
19344
+ } else says = `When it matches ${pats.map((p) => asCode3(p)).join(" or ")}`;
17755
19345
  const kids2 = steps(a.body);
17756
19346
  return { kind: "check", says, caseLabel: true, code: src.slice(a.at, src.indexOf(")", a.at) + 1).trim().slice(0, 90), line: lineAt3(a.at), span: { startLine: lineAt3(a.at), endLine: lineAt3(Math.max(a.at, a.end - 1)) }, ...kids2.length ? { children: kids2 } : {} };
17757
19347
  });
@@ -22358,8 +23948,8 @@ function leadingDoc(lines, fnLine, language) {
22358
23948
  }
22359
23949
  if (/\*\/\s*$/.test(lines[k])) {
22360
23950
  const end = k;
22361
- while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
22362
- if (k < 0) return null;
23951
+ while (k >= 0 && !/\/\*/.test(lines[k])) k--;
23952
+ if (k < 0 || !/^\s*\/\*\*(?!\/)/.test(lines[k])) return null;
22363
23953
  return cleanDoc2(lines.slice(k, end + 1).join("\n").replace(/^\s*\/\*\*/, "").replace(/\*\/\s*$/, ""));
22364
23954
  }
22365
23955
  const lineDoc = language === "go" || language === "c" || language === "cpp" ? /^\s*\/\/(?!\/)|^\s*\/\/\/(?!\/)/ : language === "ruby" ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
@@ -22367,6 +23957,25 @@ function leadingDoc(lines, fnLine, language) {
22367
23957
  while (k >= 0 && lineDoc.test(lines[k])) got.unshift(lines[k--]);
22368
23958
  return got.length ? cleanDoc2(got.join("\n")) : null;
22369
23959
  }
23960
+ function withClassPrefix(lines, fnLine, path, style) {
23961
+ if (style === "aspnet" && /^~?\//.test(path)) return "/" + path.replace(/^~?\/+/, "");
23962
+ let prefix = "";
23963
+ for (let i = fnLine - 2; i >= 0; i--) {
23964
+ const c = lines[i].match(/\bclass\s+(\w+)/);
23965
+ if (!c) continue;
23966
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
23967
+ const t = lines[j].trim();
23968
+ const r = style === "aspnet" ? t.match(/^\[(?:Route|RoutePrefix)\(\s*"([^"]*)"/) : t.match(/^@RequestMapping\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["']/);
23969
+ if (r) {
23970
+ prefix = r[1].replace(/\[controller\]/gi, c[1].replace(/Controller$/, ""));
23971
+ break;
23972
+ }
23973
+ if (t && !/^(\[|@|\/\/|\*|\/\*)/.test(t)) break;
23974
+ }
23975
+ break;
23976
+ }
23977
+ return "/" + [prefix, path].map((x) => x.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
23978
+ }
22370
23979
  function annotateRoutes(fns, src) {
22371
23980
  const lines = src.split("\n");
22372
23981
  for (const fn of fns) {
@@ -22383,7 +23992,7 @@ function annotateRoutes(fns, src) {
22383
23992
  break;
22384
23993
  }
22385
23994
  if (m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["'])?/)) {
22386
- fn.route = { method: m[1] === "Request" ? "ANY" : m[1].toUpperCase(), path: m[2] || "/" };
23995
+ fn.route = { method: m[1] === "Request" ? "ANY" : m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || "", "spring") };
22387
23996
  break;
22388
23997
  }
22389
23998
  if (m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/)) {
@@ -22391,7 +24000,7 @@ function annotateRoutes(fns, src) {
22391
24000
  break;
22392
24001
  }
22393
24002
  if (m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/)) {
22394
- fn.route = { method: m[1].toUpperCase(), path: m[2] || "" };
24003
+ fn.route = { method: m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || "", "aspnet") };
22395
24004
  break;
22396
24005
  }
22397
24006
  if (m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/)) {
@@ -22920,7 +24529,7 @@ function swiftImplicitResult(text2, returns) {
22920
24529
  var rebind = (guard, name, subject) => guard.replace(new RegExp(`\\b${name}\\b`, "g"), subject);
22921
24530
  function switchArms(body2, language, baseLine) {
22922
24531
  const arms = [];
22923
- const lineOf5 = (idx) => baseLine + lineAt(body2, idx) - 1;
24532
+ const lineOf6 = (idx) => baseLine + lineAt(body2, idx) - 1;
22924
24533
  if (language === "rust" || language === "csharp-expr") {
22925
24534
  let i = 0;
22926
24535
  while (i < body2.length) {
@@ -22943,7 +24552,7 @@ function switchArms(body2, language, baseLine) {
22943
24552
  value = body2.slice(j, end).trim();
22944
24553
  }
22945
24554
  const g = head.match(/^(.*?)\s+(?:if|when)\s+(.+)$/s);
22946
- arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line: lineOf5(i) });
24555
+ arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line: lineOf6(i) });
22947
24556
  i = end + 1;
22948
24557
  }
22949
24558
  return arms;
@@ -22982,8 +24591,8 @@ function switchArms(body2, language, baseLine) {
22982
24591
  }
22983
24592
  const patterns = [...pending, pattern2];
22984
24593
  pending = [];
22985
- if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line: lineOf5(starts[k]) });
22986
- else arms.push({ pattern: patterns.join(language === "go" && patterns.length === 1 ? "" : ", ") || patterns[0], guard: g ? g[2].trim() : null, value, line: lineOf5(starts[k]) });
24594
+ if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line: lineOf6(starts[k]) });
24595
+ else arms.push({ pattern: patterns.join(language === "go" && patterns.length === 1 ? "" : ", ") || patterns[0], guard: g ? g[2].trim() : null, value, line: lineOf6(starts[k]) });
22987
24596
  }
22988
24597
  return arms;
22989
24598
  }
@@ -23276,12 +24885,12 @@ function readBraceStatements(stmts, language, inputs) {
23276
24885
  }
23277
24886
  let rest2 = t;
23278
24887
  let ok = true;
23279
- const lineOf5 = (part) => {
24888
+ const lineOf6 = (part) => {
23280
24889
  const at2 = t.lastIndexOf(part);
23281
24890
  return st.line + (at2 > 0 ? (t.slice(0, at2).match(/\n/g) || []).length : 0);
23282
24891
  };
23283
24892
  while (rest2) {
23284
- const here = lineOf5(rest2);
24893
+ const here = lineOf6(rest2);
23285
24894
  const head2 = rest2.match(/^(?:else\s+)?if\b\s*/);
23286
24895
  if (!head2) break;
23287
24896
  rest2 = rest2.slice(head2[0].length);
@@ -23334,9 +24943,9 @@ function readBraceStatements(stmts, language, inputs) {
23334
24943
  const elseBody = remaining.replace(/^else\s*/, "");
23335
24944
  const v = elseBody.startsWith("{") ? blockValue(elseBody) : elseBody.startsWith("return ") ? elseBody.slice(7).replace(/;$/, "") : null;
23336
24945
  if (v == null) {
23337
- unread.push({ line: lineOf5(remaining), text: "else", reason: "The fallback branch does more than choose an answer." });
24946
+ unread.push({ line: lineOf6(remaining), text: "else", reason: "The fallback branch does more than choose an answer." });
23338
24947
  ok = false;
23339
- } else take(null, v, lineOf5(remaining));
24948
+ } else take(null, v, lineOf6(remaining));
23340
24949
  }
23341
24950
  rest2 = "";
23342
24951
  }
@@ -24105,7 +25714,11 @@ function functionSteps(fn, lang, code3, names, srcLines = []) {
24105
25714
  }
24106
25715
  return r;
24107
25716
  }
24108
- function readCode(source, { language, file = "", allSteps: allSteps2 = false } = {}) {
25717
+ function readCode(source, opts = {}) {
25718
+ const reading = readCodeAsIs(source, opts);
25719
+ return opts.sayEverything ? reading : sayLess(reading, String(source ?? ""));
25720
+ }
25721
+ function readCodeAsIs(source, { language, file = "", allSteps: allSteps2 = false } = {}) {
24109
25722
  const src = String(source ?? "");
24110
25723
  if (src.length > 4e5) throw new Error("Source is larger than 400 KB. Read one file or module at a time.");
24111
25724
  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").replace(/^(docker|containerfile)$/, "dockerfile").replace(/^(gha|github[ -]?actions?|workflow)$/, "github-actions").replace(/^(tf|hcl|opentofu|tofu)$/, "terraform").replace(/^(k8s|kube|kubectl)$/, "kubernetes").replace(/^(compose|docker[ -]?compose)$/, "docker-compose").replace(/^(c\+\+|cxx|cc|hpp|hxx|hh)$/, "cpp").replace(/^h$/, "c").replace(/^(sh|bash|zsh|ksh|dash|posix)$/, "shell").replace(/^(ps1|psm1|pwsh|ps)$/, "powershell").replace(/^(rlang|rscript)$/, "r");
@@ -24124,7 +25737,7 @@ function readCode(source, { language, file = "", allSteps: allSteps2 = false } =
24124
25737
  const read = lang === "python" ? readPythonBody(fn.pyBody, names) : lang === "ruby" ? readRubyBody(fn.rbBody, names) : readBraceStatements(splitStatements3(lang === "kotlin" ? kotlinTerminate(fn.body) : fn.body, lineAt(code3, fn.bodyStart)), lang, names);
24125
25738
  if (!read.rules.length && !read.otherwise) {
24126
25739
  const pred = readPredicate(fn, lang, names, code3);
24127
- if (pred) {
25740
+ if (pred && (certainlyYesNo(pred.rule.when, lang) || /^(?:bool|boolean|Bool|Boolean|BOOL|_Bool)$/.test(String(simpleType(fn.returns) ?? "").trim()) || /\?$/.test(fn.name))) {
24128
25741
  read.rules.push(pred.rule);
24129
25742
  read.otherwise = { result: "false", line: pred.rule.line };
24130
25743
  read.unread = [];
@@ -24444,9 +26057,17 @@ var pascal = (s) => s.replace(/[^A-Za-z0-9 ]/g, " ").trim().split(/\s+/).filter(
24444
26057
  function formatValue(input, value) {
24445
26058
  if (input.kind === "yesno") return value ? input.yes : input.no;
24446
26059
  if (input.kind === "text") return value === "" ? "empty" : JSON.stringify(String(value));
24447
- if (input.kind === "dollars") return `${value < 0 ? "-" : ""}$${Math.abs(value)}`;
26060
+ if (input.kind === "dollars") return `${value < 0 ? "-" : ""}$${dollarText(Math.abs(value))}`;
24448
26061
  return String(value);
24449
26062
  }
26063
+ function dollarText(value) {
26064
+ try {
26065
+ const minor = parseMoney(value);
26066
+ return minor % 100n === 0n ? String(minor / 100n) : formatMoney(minor);
26067
+ } catch {
26068
+ return String(value);
26069
+ }
26070
+ }
24450
26071
  function conditionText(model, c) {
24451
26072
  const input = model.inputs.find((i) => i.id === c.input);
24452
26073
  if (!input) return "(unknown input)";
@@ -25811,10 +27432,70 @@ function urlArg(call) {
25811
27432
  if (/^(request|Request|exchange|send)$/.test(last) && args[0]?.kind === "literal" && /^[A-Z]+$/.test(String(args[0].value))) return args[1];
25812
27433
  return args[0];
25813
27434
  }
27435
+ function httpOfCode(calls) {
27436
+ for (const call of calls) {
27437
+ const path = calleePath(call.callee) || [];
27438
+ if (path.length === 2 && /^(?:axios|http|https|client|api|request|superagent|ky|got|\$http|httpClient|HttpClient|requests|session)$/i.test(path[0]) && /^(get|post|put|patch|delete|head)$/i.test(path[1])) return [null, path[1].toUpperCase()];
27439
+ }
27440
+ return null;
27441
+ }
25814
27442
  var EVENT_PUBLISH = /^(emit|publish|publishEvent|sendToQueue|enqueue|basic_publish|produce|dispatch)$/;
25815
27443
  var EVENT_SUBSCRIBE = /\.(on|once|addListener|subscribe|consume|listen|handle)\(\s*(['"`])([^'"`]+)\2\s*,\s*(?:(?:async\s*)?(?:function\b|\(|[\w$]+\s*=>)|((?:this\.|self\.)?[\w$]+)\s*[,)])/g;
25816
27444
  var EVENT_DECORATOR = /@(OnEvent|EventPattern|MessagePattern|KafkaListener|RabbitListener|SqsListener|JmsListener|StreamListener|Subscribe|EventHandler|Consumer)\s*\(\s*(?:\{?\s*)?(?:(?:topics|queues|destination|value|pattern|event)\s*[:=]\s*)?(?:\[\s*)?(['"])([^'"]+)\2/g;
25817
27445
  var GENERIC_EVENTS = /* @__PURE__ */ new Set(["error", "close", "end", "data", "finish", "open", "message", "connect", "connection", "request", "response", "listening", "drain", "pipe", "unpipe", "readable", "timeout", "abort", "change", "click", "input", "submit", "load", "ready", "exit", "mount", "start", "stop", "done", "update", "success", "fail", "progress", "headers", "upgrade", "secureConnection", "disconnect", "reconnect"]);
27446
+ function routesIn(model, isDefaultExport) {
27447
+ const routes = [];
27448
+ for (const m of model.members) {
27449
+ if (!m.route) continue;
27450
+ const r = m.route.match(/^(\w+)\s+(.*)$/);
27451
+ if (r) routes.push({ member: m, method: r[1].toUpperCase(), segs: routeSegs(r[2]), path: r[2] });
27452
+ }
27453
+ for (const m of model.members) {
27454
+ if (m.route || m.owner) continue;
27455
+ const app = m.file.match(/(?:^|\/)app\/(.*?)\/?route\.(?:ts|js|tsx|jsx|mjs)$/);
27456
+ if (app && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(m.name)) routes.push({ member: m, method: m.name, segs: routeSegs("/" + app[1].replace(/\([^)]*\)\/?/g, "")), path: "/" + app[1] });
27457
+ const pages = m.file.match(/(?:^|\/)pages\/(api\/.*?)(?:\/index)?\.(?:ts|js|tsx|jsx)$/);
27458
+ if (pages && isDefaultExport(m)) routes.push({ member: m, method: "ANY", segs: routeSegs("/" + pages[1]), path: "/" + pages[1] });
27459
+ }
27460
+ return routes;
27461
+ }
27462
+ function listenersIn(model, sources, membersOf) {
27463
+ const listeners = /* @__PURE__ */ new Map();
27464
+ const addListener = (name, member, how) => {
27465
+ if (!member) return;
27466
+ const l = listeners.get(name) ?? listeners.set(name, []).get(name);
27467
+ if (!l.some((x) => x.member === member)) l.push({ member, how });
27468
+ };
27469
+ for (const f of model.files) {
27470
+ const src = sources.get(f.path);
27471
+ if (!src || !/\.(on|once|addListener|subscribe|consume|listen|handle)\(|@\w+(Listener|Pattern|Event|Handler)\b|@Subscribe|@Consumer|new\s+Worker\(/.test(src)) continue;
27472
+ const ms = membersOf.get(f.path) || [];
27473
+ for (const m of src.matchAll(EVENT_SUBSCRIBE)) {
27474
+ if (GENERIC_EVENTS.has(m[3])) continue;
27475
+ const line = lineAt2(src, m.index);
27476
+ const handler = m[4] ? ms.find((x) => x.name === m[4].replace(/^(this|self)\./, "") && !x.callback) ?? null : ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0];
27477
+ addListener(m[3], handler, m[1]);
27478
+ }
27479
+ for (const m of src.matchAll(/new\s+Worker\(\s*(['"`])([^'"`]+)\1\s*,/g)) {
27480
+ const line = lineAt2(src, m.index);
27481
+ addListener(m[2], ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0], "worker");
27482
+ }
27483
+ for (const m of src.matchAll(EVENT_DECORATOR)) {
27484
+ const line = lineAt2(src, m.index);
27485
+ addListener(m[3], ms.filter((x) => x.lines[0] > line && x.lines[0] <= line + 6).sort((a, b) => a.lines[0] - b.lines[0])[0], m[1]);
27486
+ }
27487
+ }
27488
+ return listeners;
27489
+ }
27490
+ function queueNamesIn(model, sources) {
27491
+ const queueNames = /* @__PURE__ */ new Map();
27492
+ for (const f of model.files) {
27493
+ const src = sources.get(f.path);
27494
+ if (!src || !/new\s+Queue\(/.test(src)) continue;
27495
+ for (const m of src.matchAll(/(?:\b(?:const|let|var)\s+|this\.)([\w$]+)\s*=\s*new\s+Queue\(\s*(['"`])([^'"`]+)\2/g)) queueNames.set(`${f.path}|${m[1]}`, m[3]);
27496
+ }
27497
+ return queueNames;
27498
+ }
25818
27499
  function linkSystem(model, files) {
25819
27500
  const sources = new Map(files.map((f) => [f.path, String(f.source ?? "")]));
25820
27501
  const langOf = new Map(model.files.map((f) => [f.path, f.language]));
@@ -26269,50 +27950,9 @@ function linkSystem(model, files) {
26269
27950
  }
26270
27951
  return { why: null };
26271
27952
  };
26272
- const routes = [];
26273
- for (const m of model.members) {
26274
- if (!m.route) continue;
26275
- const r = m.route.match(/^(\w+)\s+(.*)$/);
26276
- if (r) routes.push({ member: m, method: r[1].toUpperCase(), segs: routeSegs(r[2]), path: r[2] });
26277
- }
26278
- for (const m of model.members) {
26279
- if (m.route || m.owner) continue;
26280
- const app = m.file.match(/(?:^|\/)app\/(.*?)\/?route\.(?:ts|js|tsx|jsx|mjs)$/);
26281
- if (app && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(m.name)) routes.push({ member: m, method: m.name, segs: routeSegs("/" + app[1].replace(/\([^)]*\)\/?/g, "")), path: "/" + app[1] });
26282
- const pages = m.file.match(/(?:^|\/)pages\/(api\/.*?)(?:\/index)?\.(?:ts|js|tsx|jsx)$/);
26283
- if (pages && topOf(m.file).get(m.name)?.[0] === m && jsExp(m.file).def === m.name) routes.push({ member: m, method: "ANY", segs: routeSegs("/" + pages[1]), path: "/" + pages[1] });
26284
- }
26285
- const listeners = /* @__PURE__ */ new Map();
26286
- const addListener = (name, member, how) => {
26287
- if (!member) return;
26288
- const l = listeners.get(name) ?? listeners.set(name, []).get(name);
26289
- if (!l.some((x) => x.member === member)) l.push({ member, how });
26290
- };
26291
- for (const f of model.files) {
26292
- const src = sources.get(f.path);
26293
- if (!src || !/\.(on|once|addListener|subscribe|consume|listen|handle)\(|@\w+(Listener|Pattern|Event|Handler)\b|@Subscribe|@Consumer|new\s+Worker\(/.test(src)) continue;
26294
- const ms = membersOf.get(f.path) || [];
26295
- for (const m of src.matchAll(EVENT_SUBSCRIBE)) {
26296
- if (GENERIC_EVENTS.has(m[3])) continue;
26297
- const line = lineAt2(src, m.index);
26298
- const handler = m[4] ? ms.find((x) => x.name === m[4].replace(/^(this|self)\./, "") && !x.callback) ?? null : ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0];
26299
- addListener(m[3], handler, m[1]);
26300
- }
26301
- for (const m of src.matchAll(/new\s+Worker\(\s*(['"`])([^'"`]+)\1\s*,/g)) {
26302
- const line = lineAt2(src, m.index);
26303
- addListener(m[2], ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0], "worker");
26304
- }
26305
- for (const m of src.matchAll(EVENT_DECORATOR)) {
26306
- const line = lineAt2(src, m.index);
26307
- addListener(m[3], ms.filter((x) => x.lines[0] > line && x.lines[0] <= line + 6).sort((a, b) => a.lines[0] - b.lines[0])[0], m[1]);
26308
- }
26309
- }
26310
- const queueNames = /* @__PURE__ */ new Map();
26311
- for (const f of model.files) {
26312
- const src = sources.get(f.path);
26313
- if (!src || !/new\s+Queue\(/.test(src)) continue;
26314
- for (const m of src.matchAll(/(?:\b(?:const|let|var)\s+|this\.)([\w$]+)\s*=\s*new\s+Queue\(\s*(['"`])([^'"`]+)\2/g)) queueNames.set(`${f.path}|${m[1]}`, m[3]);
26315
- }
27953
+ const routes = routesIn(model, (m) => topOf(m.file).get(m.name)?.[0] === m && jsExp(m.file).def === m.name);
27954
+ const listeners = listenersIn(model, sources, membersOf);
27955
+ const queueNames = queueNamesIn(model, sources);
26316
27956
  const seen = /* @__PURE__ */ new Set();
26317
27957
  const link = (l) => {
26318
27958
  const k = `${l.from}|${l.to}|${l.node}|${l.kind}`;
@@ -26327,7 +27967,7 @@ function linkSystem(model, files) {
26327
27967
  if (!nd.expr) continue;
26328
27968
  const calls = callsIn(nd.expr);
26329
27969
  if (!calls.length) continue;
26330
- const http = HTTP_SAYS.exec(nd.text || "");
27970
+ const http = HTTP_SAYS.exec(nd.text || "") || (nd.explained === false ? httpOfCode(calls) : null);
26331
27971
  let httpDone = false;
26332
27972
  for (const call of calls) {
26333
27973
  const path = calleePath(call.callee);
@@ -26528,7 +28168,7 @@ function braceEnd2(src, open) {
26528
28168
  }
26529
28169
  return -1;
26530
28170
  }
26531
- var lineOf4 = (src, idx) => src.slice(0, idx).split("\n").length;
28171
+ var lineOf5 = (src, idx) => src.slice(0, idx).split("\n").length;
26532
28172
  function tsThings(src, file) {
26533
28173
  const out = [];
26534
28174
  const re = /(?:^|\n)[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|enum)\s+(\w+)[^{]*\{/g;
@@ -26538,11 +28178,11 @@ function tsThings(src, file) {
26538
28178
  const close = braceEnd2(src, open);
26539
28179
  if (close < 0) continue;
26540
28180
  const body2 = src.slice(open + 1, close);
26541
- const startLine = lineOf4(src, m.index + (m[0].startsWith("\n") ? 1 : 0));
28181
+ const startLine = lineOf5(src, m.index + (m[0].startsWith("\n") ? 1 : 0));
26542
28182
  const before = src.slice(0, m.index).split("\n").slice(-4).join("\n");
26543
28183
  const docm = before.match(/\/\*\*([\s\S]*?)\*\/\s*$/);
26544
28184
  const doc = docm ? docm[1].split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim()).filter((l) => l && !l.startsWith("@")).join(" ") || null : null;
26545
- const thing = { kind: m[1] === "enum" ? "choices" : m[1] === "interface" ? "record" : "thing", name: m[2], file, lines: [startLine, lineOf4(src, close)], ...doc ? { doc } : {}, knows: [], choices: [] };
28185
+ const thing = { kind: m[1] === "enum" ? "choices" : m[1] === "interface" ? "record" : "thing", name: m[2], file, lines: [startLine, lineOf5(src, close)], ...doc ? { doc } : {}, knows: [], choices: [] };
26546
28186
  if (m[1] === "enum") {
26547
28187
  for (const part of body2.split(",")) {
26548
28188
  const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s);
@@ -26632,14 +28272,15 @@ function stepDoes(step) {
26632
28272
  var outsideQuotes = (text2, fn) => String(text2).split(/("(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»)/).map((part, i) => i % 2 ? part : fn(part)).join("");
26633
28273
  var possessive2 = (text2) => outsideQuotes(text2, possessiveWords2);
26634
28274
  var possessiveWords2 = (text2) => String(text2).replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => /^(self|this)$/.test(a) ? `the ${words9(b)}` : `the ${words9(a)}'s ${words9(b)}`).replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words9(m));
26635
- var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : /^(["'`]).*\1$/s.test(String(r).trim()) ? String(r).trim() : cap3(words9(r));
28275
+ var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : /^(["'`]).*\1$/s.test(String(r).trim()) ? String(r).trim() : /^[A-Za-z]{2,4}$/.test(String(r).trim()) && /[a-z][A-Z]|[A-Z][a-z]+[A-Z]/.test(String(r)) ? String(r).trim() : cap3(words9(r));
26636
28276
  function askAsQuestion(step, ruleLabel) {
26637
28277
  const run = String(step.says).match(/^If (not: )?([A-Z]?[a-z]+ing\b[^]* (?:works|fails))$/);
26638
28278
  if (run && !ruleLabel) return { text: `${cap3(run[2])}?`, flip: !!run[1] };
26639
28279
  const held = [];
26640
28280
  const says = String(step.says).replace(/"(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»/g, (m) => isCodeWords(String(step.says).replace(/^If (?:not: )?/, "")) ? m : `${held.push(m) - 1}`);
26641
28281
  const r = askWords({ ...step, says }, ruleLabel);
26642
- return { ...r, text: r.text.replace(/\u0001(\d+)\u0002/g, (m, k) => held[Number(k)]) };
28282
+ const back = (t) => String(t).replace(/\u0001(\d+)\u0002/g, (m, k) => held[Number(k)]);
28283
+ return { ...r, text: back(r.text), ...r.holds ? { holds: { yes: back(r.holds.yes), no: back(r.holds.no) } } : {} };
26643
28284
  }
26644
28285
  function askWords(step, ruleLabel) {
26645
28286
  let c = String(step.says).replace(/^If /, "").replace(/ \(\d+ steps? inside\)$/, "").trim();
@@ -26681,7 +28322,7 @@ function ruleFlow(item2, start) {
26681
28322
  let n = 0;
26682
28323
  const node = (kind, text2, extra = {}) => {
26683
28324
  const id = `n${n++}`;
26684
- nodes.push({ id, kind, text: text2, row: nodes.length, ...extra });
28325
+ nodes.push({ id, kind, text: text2, row: nodes.length, explained: true, ...extra });
26685
28326
  return id;
26686
28327
  };
26687
28328
  let prev = node("start", start, { lane: 0, does: "start" });
@@ -26724,6 +28365,9 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
26724
28365
  const id = `n${n++}`;
26725
28366
  const { [DETAIL_OF]: of, ...rest2 } = extra;
26726
28367
  const nd = { id, kind, text: text2, ...rest2 };
28368
+ nd.explained = !(kind === "code" || nd.code || rest2.explained === false);
28369
+ if (nd.explained) delete nd.notExplainedWhy;
28370
+ else if (!nd.notExplainedWhy) nd.notExplainedWhy = "the reader did not recognize this form";
26727
28371
  if (of) lazyDetail(nd, of);
26728
28372
  nodes.push(nd);
26729
28373
  return id;
@@ -26748,7 +28392,7 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
26748
28392
  const blocks2 = [];
26749
28393
  for (const st of list3) {
26750
28394
  const does = stepDoes(st);
26751
- const base2 = { line: st.line, lane, does, ...usesOf(st) ? { uses: usesOf(st) } : {}, ...st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {} };
28395
+ const base2 = { line: st.line, lane, does, ...st.explained === false ? { explained: false, ...st.notExplainedWhy ? { notExplainedWhy: st.notExplainedWhy } : {} } : {}, ...st.codeWords ? { code: true } : {}, ...usesOf(st) ? { uses: usesOf(st) } : {}, ...st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {} };
26752
28396
  const arms = st.kind === "branch" && st.children?.length && st.children.every((c) => c.kind === "check" && c.caseLabel) ? st.children : null;
26753
28397
  if (arms) {
26754
28398
  const d = node("decision", st.says.replace(/\?$/, ""), { ...base2, cases: true });
@@ -27064,6 +28708,8 @@ function thunderModel(files, { name = "app" } = {}) {
27064
28708
  ...rule ? { rule, question: rule.question } : {},
27065
28709
  // A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
27066
28710
  ...kind === "rule" ? { yesNo: [...(item2.rules || []).map((r) => r.result), item2.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {},
28711
+ // How sure: of the steps Thunder read, how many it put into words (the rest are shown as code, not explained).
28712
+ ...item2.totalSteps != null ? { explainedSteps: item2.explainedSteps, totalSteps: item2.totalSteps } : {},
27067
28713
  _steps: item2.steps || [],
27068
28714
  _item: item2,
27069
28715
  ...item2.qualifier && !owner ? { _qualifier: item2.qualifier } : {}
@@ -27148,7 +28794,9 @@ function thunderModel(files, { name = "app" } = {}) {
27148
28794
  if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1);
27149
28795
  else t.kind = "record";
27150
28796
  }
27151
- const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts };
28797
+ const totalSteps = members.reduce((n, m) => n + (m.totalSteps ?? 0), 0);
28798
+ const explainedSteps = members.reduce((n, m) => n + (m.explainedSteps ?? 0), 0);
28799
+ const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
27152
28800
  try {
27153
28801
  linkSystem(model, files);
27154
28802
  } catch (e) {
@@ -27161,7 +28809,7 @@ function flowLines(flow, depth = 1, note = null, full = false) {
27161
28809
  const out = [];
27162
28810
  const pad = (d) => " ".repeat(d);
27163
28811
  const at2 = (n) => `${n.line ? ` (line ${n.line})` : ""}${note && note(n) || ""}`;
27164
- const say = (n) => n.kind === "end" && n.code && !/^(?:return|yield)\b/.test(String(n.text).trim()) ? `Gives back \`${n.text}\` (code, not explained)` : n.kind === "code" || n.kind === "end" && n.code ? `\`${n.text}\` (code, not explained)` : n.kind === "decision" && n.cases ? n.text : n.kind === "decision" ? `Ask: ${n.text}${n.code ? " (code, not explained)" : ""}` : n.kind === "end" && n.answer ? `Answer: ${n.text}` : n.text;
28812
+ const say = (n) => n.kind === "end" && n.code && !/^(?:return|yield|exit|exec|die|abort|quit|halt|throw|raise|panic|break|continue|Exit|Throw|Write-Error)\b/.test(String(n.text).trim()) ? `Gives back \`${n.text}\` (code, not explained)` : n.kind === "code" || n.kind === "end" && n.code ? `\`${n.text}\` (code, not explained)` : (n.kind === "loop" || n.kind === "stop" || n.kind === "step") && n.code ? `${n.text} (code, not explained)` : n.kind === "decision" && n.cases ? `${n.text}${n.code ? " (code, not explained)" : ""}` : n.kind === "decision" ? `Ask: ${n.text}${n.code ? " (code, not explained)" : ""}` : n.kind === "end" && n.answer ? `Answer: ${n.text}` : n.text;
27165
28813
  const go = (blocks, d) => {
27166
28814
  for (const b of blocks || []) {
27167
28815
  const n = byId.get(b.id);
@@ -27897,22 +29545,22 @@ def place_order(order, card):
27897
29545
 
27898
29546
  // src/learn.mjs
27899
29547
  var LEARN_SCHEMA = "thunder-learn-v1";
27900
- var squash = (s) => String(s).replace(/[_\s]/g, "").toLowerCase();
29548
+ var squash2 = (s) => String(s).replace(/[_\s]/g, "").toLowerCase();
27901
29549
  var EXT = { python: "py", typescript: "ts", javascript: "js", java: "java", go: "go", csharp: "cs", ruby: "rb", php: "php", rust: "rs", kotlin: "kt" };
27902
29550
  var MODEL_SHOWS = /* @__PURE__ */ new Set(["thing", "flow"]);
27903
29551
  function lessonContext(lesson) {
27904
29552
  const files = lesson.files.map((f, i) => ({ path: `lesson${i ? i + 1 : ""}.${EXT[f.language] ?? "txt"}`, source: f.code }));
27905
29553
  const readings = lesson.files.map((f) => readCode(f.code, { language: f.language }));
27906
29554
  const all = readings.flatMap((r) => r.items);
27907
- const focus = lesson.focus ? readings.map((r) => r.items.find((i) => squash(i.name) === squash(lesson.focus))) : [];
29555
+ const focus = lesson.focus ? readings.map((r) => r.items.find((i) => squash2(i.name) === squash2(lesson.focus))) : [];
27908
29556
  const model = MODEL_SHOWS.has(lesson.show) && files.length ? thunderModel(files) : null;
27909
29557
  const target = model && (lesson.show === "thing" ? model.things.find((t) => t.name === lesson.focus) : model.members.find((m) => m.name === lesson.focus));
27910
29558
  const run = (facts, name) => {
27911
- const item2 = name ? all.find((i) => squash(i.name) === squash(name)) : focus[0];
29559
+ const item2 = name ? all.find((i) => squash2(i.name) === squash2(name)) : focus[0];
27912
29560
  const plain = plainFromReading(item2);
27913
29561
  const values = {};
27914
29562
  for (const input of plain.inputs) {
27915
- const key = Object.keys(facts).find((k) => squash(k) === squash(String(input.label).replace(/^the /, "")));
29563
+ const key = Object.keys(facts).find((k) => squash2(k) === squash2(String(input.label).replace(/^the /, "")));
27916
29564
  if (key === void 0) throw new Error(`no value given for ${input.label}`);
27917
29565
  values[input.id] = facts[key];
27918
29566
  }