@skillstech/thunderlang 1.3.0 → 1.4.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.
package/dist/learn.cjs CHANGED
@@ -3483,7 +3483,8 @@ function accountsFor(code3, said, tree = null) {
3483
3483
  const bare2 = stripQuoted(String(said).replace(/`[^`]*`/g, "Q"));
3484
3484
  if (/&&|\|\||[!=]==?|<=|>=|\s[<>]\s|^\s*[<>]|\bis is\b/.test(bare2)) return false;
3485
3485
  const c = tree && tree.kind !== "code" ? exprCounts(tree) : codeCounts(code3), w = wordCounts(said);
3486
- return c.neg === w.neg && c.logic === w.logic && w.compare >= c.compare;
3486
+ const named2 = (String(code3).match(/\bIsNullOr(?:Empty|WhiteSpace)\s*\(/g) || []).length;
3487
+ return c.neg === w.neg && c.logic + named2 === w.logic && w.compare >= c.compare;
3487
3488
  }
3488
3489
  var asCodeWords = (code3, n = 120) => {
3489
3490
  const t = String(code3).replace(/\s+/g, " ").trim();
@@ -3901,6 +3902,13 @@ function newThing(v, says) {
3901
3902
  if (!m) return false;
3902
3903
  let c = coreOf(v);
3903
3904
  if (c?.kind === "unary" && c.op === "&") c = coreOf(c.value);
3905
+ if (m[1] === "random ID") {
3906
+ let x = c;
3907
+ if (x?.kind === "call" && x.callee?.kind === "member" && /^(?:ToString|toString)$/.test(x.callee.property)) x = x.callee.object;
3908
+ if (x?.kind === "member" && x.property === "hex") x = x.object;
3909
+ const name = x?.kind === "call" ? x.callee?.kind === "member" ? x.callee.property : x.callee?.name : null;
3910
+ return /^(?:randomUUID|uuid4|NewGuid|uuidv4|v4|new_v4)$/.test(name ?? "") && !x.args?.length;
3911
+ }
3904
3912
  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;
3905
3913
  return !!type && sameWords(String(type).replace(/<.*$/, "").split(/::|\./).pop(), m[1]);
3906
3914
  }
@@ -3966,9 +3974,9 @@ var SAID_AS = {
3966
3974
  none: / set | nothing | none | missing /
3967
3975
  };
3968
3976
  function namesKept(tree, said) {
3969
- const norm2 = (t) => t.replace(/ have /g, " has ").replace(/ are /g, " is ").replace(/ does /g, " ");
3977
+ const norm3 = (t) => t.replace(/ have /g, " has ").replace(/ are /g, " is ").replace(/ does /g, " ");
3970
3978
  const base2 = ` ${splitWords(claimText(said)).join(" ")} ${splitWords(said).join(" ")} `;
3971
- const sw = norm2(`${base2} ${base2.replace(/ (?:not|no|does not|doesn t) /g, " ")} `);
3979
+ const sw = norm3(`${base2} ${base2.replace(/ (?:not|no|does not|doesn t) /g, " ")} `);
3972
3980
  const has2 = (x) => {
3973
3981
  const w = splitWords(x).join(" ");
3974
3982
  if (!w || /^(?:self|this|it|super)$/.test(w) || sw.includes(` ${w} `) || sw.includes(` ${w.replace(/s$/, "")} `) || sw.includes(` ${w}s `)) return true;
@@ -4027,6 +4035,7 @@ function namesKept(tree, said) {
4027
4035
  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));
4028
4036
  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);
4029
4037
  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);
4038
+ if (name && /^IsNullOr(?:Empty|WhiteSpace)$/.test(name) && c?.kind === "member" && /^[Ss]tring$/.test(c.object?.name ?? "") && setWords2) return ok(n.args);
4030
4039
  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);
4031
4040
  return (name == null || has2(name)) && (c?.kind !== "member" || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? "")) && ok(n.args);
4032
4041
  }
@@ -4056,7 +4065,7 @@ function namesKept(tree, said) {
4056
4065
  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)$/;
4057
4066
  var coreOf = (e) => {
4058
4067
  let c = e;
4059
- while (c && (c.kind === "unary" && (c.op === "await" || c.op === "?" || c.op === "!!") || c.kind === "cast" && c.form === "nonnull")) c = c.value;
4068
+ while (c && (c.kind === "unary" && (c.op === "await" || c.op === "?" || c.op === "!!") || c.kind === "cast" && c.form === "nonnull" || c.kind === "member" && c.property === "Value" && c.object?.kind === "call" && c.object.callee?.property === "GetOrAdd")) c = c.kind === "member" ? c.object : c.value;
4060
4069
  return c;
4061
4070
  };
4062
4071
  function chainCallees(e) {
@@ -4342,6 +4351,7 @@ function conditionCore(test, says, code3, lang) {
4342
4351
  if (tn !== wn) return M("L378");
4343
4352
  let logic = 0;
4344
4353
  for (const n of nodesOf2(test)) if (n.kind === "logic") logic += n.operands.length - 1;
4354
+ else if (n.kind === "call" && /^IsNullOr(?:Empty|WhiteSpace)$/.test(n.callee?.property ?? "")) logic++;
4345
4355
  const wl = (said.match(/\band\b|\bor\b/g) || []).length;
4346
4356
  if (logic !== wl) return M("L381");
4347
4357
  if (!orderingKept(test, says)) return M("L382");
@@ -12664,10 +12674,21 @@ var CATALOG = [
12664
12674
  } },
12665
12675
  { re: /^(?:axios|http|httpClient|client|api|ky|got|superagent|request)\s*\.\s*(get|post|put|patch|delete|head)\s*\(/i, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12666
12676
  { re: /^(?:requests|httpx|session|self\.session|aiohttp\.ClientSession\(\))\s*\.\s*(get|post|put|patch|delete)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12667
- { re: /^(?:_?httpClient|client|_client|HttpClient)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12677
+ { re: /^(?:this\.)?(?:_?[Hh]ttp(?:Client)?|_?client|\w*HttpClient|_?\w+Client)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12668
12678
  { re: /^(?:restTemplate|webClient)\s*\.\s*(get|post|put|delete|patch)(?:ForObject|ForEntity)?\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12669
12679
  { re: /^http\s*\.\s*(Get|Post|Head)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12670
12680
  { re: /^reqwest\s*::\s*get\s*\(/, say: (m, c) => ({ says: `Sends a GET request to ${URL_WORDS(splitTop2(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
12681
+ // ── A new random ID: crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), uuidv4(), UUID.randomUUID() ──
12682
+ { re: /^(?:(?:globalThis\.|window\.)?crypto\.randomUUID|uuid\.uuid4|Guid\.NewGuid|uuidv4|uuid\.v4|UUID\.randomUUID|Uuid::new_v4)\s*\(\s*\)(?:\.(?:ToString|toString|hex)\(\)|\.hex)?$/, say: () => ({ says: "a new random ID", does: "calculate", value: true }) },
12683
+ // ── .NET: a shared lookup table that makes an entry only once (ConcurrentDictionary.GetOrAdd) ──
12684
+ // `byKey.GetOrAdd(key, _ => new Lazy<Task<T>>(() => Place(request))).Value`: later calls with the same key get the
12685
+ // entry made the first time. The function that makes it is named when the code names one.
12686
+ { re: /^(?:this\.)?(_?[A-Za-z]\w*)\s*\.\s*GetOrAdd\s*\(/, say: (m, c) => {
12687
+ const args = splitTop2(inside(c, c.indexOf("(", m.index + m[0].length - 1)) ?? "");
12688
+ if (args.length !== 2) return null;
12689
+ const made = [...args[1].matchAll(/\b([A-Za-z_]\w*)\s*\(/g)].map((x) => x[1]).filter((x) => !/^(?:new|Lazy|Task|ValueTask)$/.test(x)).pop();
12690
+ return { says: `the entry for ${valueWords3(args[0])} in ${words5(m[1])}, made${made ? ` by ${words5(made)}` : ""} if it is missing (a later call with the same ${valueWords3(args[0]).replace(/^the [\w ]+'s /, "")} gets that same entry)`, does: "find", value: true };
12691
+ } },
12671
12692
  // ── Prisma ──
12672
12693
  { re: /^(?:this\.)?prisma\s*\.\s*(\w+)\s*\.\s*(findUnique|findUniqueOrThrow|findFirst|findFirstOrThrow|findMany|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate)\s*\(/, say: (m, c) => {
12673
12694
  const thing = words5(m[1]), args = inside(c, c.indexOf("(", m.index + m[0].length - 1)) ?? "", whose = whereOf(args);
@@ -12759,6 +12780,14 @@ var CATALOG = [
12759
12780
  { re: /^(?:\w+\.)?(?:queue|producer|channel)\s*\.\s*(add|send|publish|enqueue|basic_publish|sendMessage)\s*\(/, say: () => ({ says: "Puts a message on the queue", does: "send" }) },
12760
12781
  // ── JSON, files, time ──
12761
12782
  { re: /^JSON\s*\.\s*parse\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords3(m[1])} as JSON`, does: "calculate" }) },
12783
+ // An object written right there names its fields: JSON.stringify({ items: cart, coupon }) -> "Turns items (cart) and coupon into JSON text".
12784
+ { re: /^JSON\s*\.\s*stringify\s*\(\s*\{/, say: (m, c) => {
12785
+ const obj = inside(c, c.indexOf("{"));
12786
+ const fields = obj == null ? null : splitTop2(obj).filter((x) => x.trim()).map((x) => x.trim().match(/^([A-Za-z_$][\w$]*)(?:\s*:\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?))?$/));
12787
+ if (!fields?.length || fields.some((f) => !f)) return null;
12788
+ const said = fields.map((f) => f[2] && f[2] !== f[1] ? `${words5(f[1])} (${valueWords3(f[2])})` : words5(f[1]));
12789
+ return { says: `Turns ${said.length === 1 ? said[0] : `${said.slice(0, -1).join(", ")} and ${said.at(-1)}`} into JSON text`, does: "calculate" };
12790
+ } },
12762
12791
  { re: /^JSON\s*\.\s*stringify\s*\(\s*([^,]+)/, say: (m) => ({ says: `Turns ${valueWords3(m[1])} into JSON text`, does: "calculate" }) },
12763
12792
  { re: /^json\s*\.\s*(loads|load)\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords3(m[2])} as JSON`, does: "calculate" }) },
12764
12793
  { re: /^json\s*\.\s*(dumps|dump)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Turns ${valueWords3(m[2])} into JSON text`, does: "calculate" }) },
@@ -13034,9 +13063,9 @@ function sayCodeConditionInner(cond) {
13034
13063
  return `${possessiveWords(ty[2])} is ${ty[1] ? "not " : ""}${kinds.length > 1 ? `one of ${kinds.join(", ")}` : aWord(kinds[0])}`;
13035
13064
  }
13036
13065
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
13037
- const plural3 = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
13066
+ const plural3 = (w, call3) => !call3 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
13038
13067
  if (prop && plural3(words6(prop[3]), !!prop[4])) return `${words6(prop[2])} ${prop[1] ? "has no" : "has"} ${words6(prop[3])}`;
13039
- const yesNo2 = (w, call2) => /^(is|has|can|should|was) /.test(w) || !call2 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
13068
+ const yesNo2 = (w, call3) => /^(is|has|can|should|was) /.test(w) || !call3 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
13040
13069
  if (prop && yesNo2(words6(prop[3]), !!prop[4])) {
13041
13070
  const neg2 = !!prop[1];
13042
13071
  const w = words6(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
@@ -13047,19 +13076,22 @@ function sayCodeConditionInner(cond) {
13047
13076
  if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words6(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words6(pred[3]).replace(/^(not|no|non) /, "$1-")}`;
13048
13077
  c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`).replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
13049
13078
  c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
13050
- let call;
13051
- if (call = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) {
13052
- const neg2 = !!call[1] !== (call[2] === "isset");
13053
- const what = possessiveWords(call[3]);
13054
- if (call[2] === "is_null") return `${what} is ${call[1] ? "not " : ""}null`;
13055
- return call[2] === "isset" ? `${what} is ${call[1] ? "not " : ""}set` : `${what} is ${neg2 ? "not " : ""}empty`;
13056
- }
13057
- if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
13058
- return `${possessiveWords(call[3])} is ${call[1] ? "not " : ""}${words6(call[2])}`;
13059
- }
13060
- if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
13061
- const w = words6(call[2]);
13062
- if (!call[1]) return w;
13079
+ let call2;
13080
+ if (call2 = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) {
13081
+ const neg2 = !!call2[1] !== (call2[2] === "isset");
13082
+ const what = possessiveWords(call2[3]);
13083
+ if (call2[2] === "is_null") return `${what} is ${call2[1] ? "not " : ""}null`;
13084
+ return call2[2] === "isset" ? `${what} is ${call2[1] ? "not " : ""}set` : `${what} is ${neg2 ? "not " : ""}empty`;
13085
+ }
13086
+ if (call2 = c.match(/^(!|not\s+)?[Ss]tring\.IsNullOr(Empty|WhiteSpace)\(\s*([\w$.]+)\s*\)$/)) {
13087
+ return `${possessiveWords(call2[3])} is ${call2[1] ? "not " : ""}${call2[2] === "Empty" ? "empty" : "blank"}${call2[1] ? " and is set" : " or missing"}`;
13088
+ }
13089
+ if ((call2 = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call2[2])) {
13090
+ return `${possessiveWords(call2[3])} is ${call2[1] ? "not " : ""}${words6(call2[2])}`;
13091
+ }
13092
+ if (call2 = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
13093
+ const w = words6(call2[2]);
13094
+ if (!call2[1]) return w;
13063
13095
  return w.replace(/^(is|was|are|should|has|can|does) /, (m0, v) => ({ has: "does not have ", can: "cannot ", does: "does not " })[v] ?? `${v} not `);
13064
13096
  }
13065
13097
  const bare2 = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
@@ -13760,8 +13792,8 @@ function payloadWords(arg) {
13760
13792
  if (/^(["'`])(?:\\.|(?!\1)[^\\])*\1$/.test(a) && !/^`[^`]*\$\{/.test(a)) return a.length < 50 ? `"${a.replace(/^["'`]|["'`]$/g, "")}"` : "a message";
13761
13793
  if (/^["'`]/.test(a) || /["'`]\s*\+|\+\s*["'`]/.test(a)) return "text built from its parts";
13762
13794
  if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(a)) return possessiveWords(a);
13763
- const call = a.match(/^(?:await\s+)?([\w.]+)\s*\(/);
13764
- if (call) return `what ${words6(call[1].split(".").pop())} gives back`;
13795
+ const call2 = a.match(/^(?:await\s+)?([\w.]+)\s*\(/);
13796
+ if (call2) return `what ${words6(call2[1].split(".").pop())} gives back`;
13765
13797
  return "a value";
13766
13798
  }
13767
13799
  function callArgs(text2) {
@@ -14183,6 +14215,7 @@ function statementExpr(raw) {
14183
14215
  return parseStatement(text2, readingLanguage());
14184
14216
  }
14185
14217
  var codeExpr = (text2) => ({ kind: "code", text: String(text2 ?? "").replace(/\s+/g, " ").trim() });
14218
+ var callWithObject = (first) => /[(,]\s*\{\s*$/.test(first) && !/=>\s*\{\s*$/.test(first) && !bracketsClosed2(first.replace(/\{\s*$/, ""));
14186
14219
  function classifyWords(raw, { inner = 0 } = {}) {
14187
14220
  const text2 = String(raw).trim();
14188
14221
  let first = text2.split("\n")[0].trim();
@@ -14201,8 +14234,9 @@ function classifyWords(raw, { inner = 0 } = {}) {
14201
14234
  const rest2 = c2 > 0 ? text2.slice(c2 + 1).trim() : "";
14202
14235
  if (rest2 && !rest2.startsWith("{") && !text2.slice(c2 + 1).split("\n")[0].trim()) first = `${text2.slice(0, c2 + 1).replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")")} ${rest2.replace(/\s+/g, " ")}`.trim();
14203
14236
  }
14237
+ if (LANG === "csharp") first = first.replace(/^return\s+(?:Task|ValueTask)\.FromResult\((.*)\)\s*;?$/, "return $1;");
14204
14238
  if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text2.split("\n")[1] || "")) first = `return (${text2.split("\n")[1].trim()}`;
14205
- 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))) {
14239
+ 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) || callWithObject(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) || callWithObject(first))) {
14206
14240
  const lines = text2.split("\n");
14207
14241
  const joined2 = lines.map((l) => l.trim()).join(" ");
14208
14242
  if (!bracketsClosed2(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || "")) first = joined2;
@@ -17142,7 +17176,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
17142
17176
  var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
17143
17177
 
17144
17178
  // src/emit.mjs
17145
- var COMPILER_VERSION = "1.3.0";
17179
+ var COMPILER_VERSION = "1.4.0";
17146
17180
 
17147
17181
  // src/lift.mjs
17148
17182
  var IR_SCHEMA_VERSION = "0.1.0";
@@ -20526,7 +20560,7 @@ function sayValue2(toks, plain = false) {
20526
20560
  }
20527
20561
  if (first.length === 1 && (first[0].t === "var" || first[0].t === "type")) {
20528
20562
  const members = [];
20529
- let k = 1, call = null;
20563
+ let k = 1, call2 = null;
20530
20564
  let index = null;
20531
20565
  while (k < g.length) {
20532
20566
  if (g[k][0].text === "[" && g[k].length > 2) {
@@ -20541,7 +20575,7 @@ function sayValue2(toks, plain = false) {
20541
20575
  const m = g[k + 1]?.[0];
20542
20576
  if (!m || m.t !== "word") break;
20543
20577
  if (g[k + 2]?.[0].text === "(") {
20544
- call = m.text;
20578
+ call2 = m.text;
20545
20579
  k += 3;
20546
20580
  break;
20547
20581
  }
@@ -20554,7 +20588,7 @@ function sayValue2(toks, plain = false) {
20554
20588
  k += 2;
20555
20589
  }
20556
20590
  const owner = first[0].t === "var" ? varWords2(first[0].name) : `the ${first[0].name.split(".").pop()}`;
20557
- if (index != null && (k !== g.length || call)) return null;
20591
+ if (index != null && (k !== g.length || call2)) return null;
20558
20592
  if (index != null) {
20559
20593
  const of = chainWords(owner, members);
20560
20594
  if (index.key != null) return possessive(of, index.key);
@@ -20564,11 +20598,11 @@ function sayValue2(toks, plain = false) {
20564
20598
  if (of === "the inputs" && index.n < 10) return `the ${ORD[index.n]} input`;
20565
20599
  return `the item at index ${index.n} of ${of}`;
20566
20600
  }
20567
- if (k === g.length && first[0].t === "type" && !call && members.length) return `the ${words7(members[members.length - 1])} (${first[0].name.split(".").pop()})`;
20568
- if (k === g.length && first[0].t === "var" && !call) return chainWords(varWords2(first[0].name), members);
20569
- if (k === g.length && call) {
20570
- if (/^new$/i.test(call) && first[0].t === "type") return `a new ${first[0].name.replace(/\[.*$/, "").split(".").pop()}`;
20571
- return `the result of ${words7(call)}${first[0].t === "var" ? ` on ${chainWords(varWords2(first[0].name), members)}` : ""}`;
20601
+ if (k === g.length && first[0].t === "type" && !call2 && members.length) return `the ${words7(members[members.length - 1])} (${first[0].name.split(".").pop()})`;
20602
+ if (k === g.length && first[0].t === "var" && !call2) return chainWords(varWords2(first[0].name), members);
20603
+ if (k === g.length && call2) {
20604
+ if (/^new$/i.test(call2) && first[0].t === "type") return `a new ${first[0].name.replace(/\[.*$/, "").split(".").pop()}`;
20605
+ return `the result of ${words7(call2)}${first[0].t === "var" ? ` on ${chainWords(varWords2(first[0].name), members)}` : ""}`;
20572
20606
  }
20573
20607
  }
20574
20608
  const AR = { "+": "plus", "-": "minus", "*": "times", "/": "divided by", "%": "remainder after dividing by" };
@@ -20663,11 +20697,11 @@ function condWords3(toks, neg2) {
20663
20697
  }
20664
20698
  return parts;
20665
20699
  };
20666
- for (const [names, join2, flip] of [[["or", "xor"], " or ", " and "], [["and"], " and ", " or "]]) {
20700
+ for (const [names, join3, flip] of [[["or", "xor"], " or ", " and "], [["and"], " and ", " or "]]) {
20667
20701
  const parts = split(names);
20668
20702
  if (parts.length > 1) {
20669
20703
  const said = parts.map((p) => condWords3(p.flat(), neg2));
20670
- return said.some((x) => !x) ? null : said.join(neg2 ? flip : join2);
20704
+ return said.some((x) => !x) ? null : said.join(neg2 ? flip : join3);
20671
20705
  }
20672
20706
  }
20673
20707
  if (g[0].length === 1 && (g[0][0].t === "op" && opName(g[0][0]) === "not" || g[0][0].text === "!")) return condWords3(g.slice(1).flat(), !neg2);
@@ -21864,7 +21898,7 @@ function powershellReading(src, file = "") {
21864
21898
  }
21865
21899
  function psThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
21866
21900
  const { things } = powershellReading(src, file);
21867
- const norm2 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
21901
+ const norm3 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
21868
21902
  const kind = (t) => {
21869
21903
  const x = String(t ?? "").toLowerCase();
21870
21904
  if (!x) return null;
@@ -21880,7 +21914,7 @@ function psThings(src, file, { words: w, kindWords: kindWords3, startValue: star
21880
21914
  lines: t.lines,
21881
21915
  ...t.doc ? { doc: t.doc } : {},
21882
21916
  choices: t.choices,
21883
- knows: t.knows.map((k) => ({ name: k.name, label: w(k.name), kind: kind(k.type), start: k.start == null ? null : typeof k.start === "object" ? k.start.given ? "given when it starts" : `${startValue2(norm2(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm2(k.start)), line: k.line }))
21917
+ knows: t.knows.map((k) => ({ name: k.name, label: w(k.name), kind: kind(k.type), start: k.start == null ? null : typeof k.start === "object" ? k.start.given ? "given when it starts" : `${startValue2(norm3(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm3(k.start)), line: k.line }))
21884
21918
  }));
21885
21919
  }
21886
21920
 
@@ -22224,8 +22258,8 @@ function sayValue3(list3) {
22224
22258
  const owner = sayValue3(g.slice(0, -1).flat());
22225
22259
  if (owner) return `an item of ${owner}`;
22226
22260
  }
22227
- const call = callOf(v);
22228
- if (call) return callNoun(call) ?? (callVerb(call) ? `the result of ${gerund(callVerb(call))}` : `the result of ${rWords(call.name)}`);
22261
+ const call2 = callOf(v);
22262
+ if (call2) return callNoun(call2) ?? (callVerb(call2) ? `the result of ${gerund(callVerb(call2))}` : `the result of ${rWords(call2.name)}`);
22229
22263
  if (g.length === 1 && isOp(g[0][0], "(")) return sayValue3(g[0].slice(1, -1));
22230
22264
  if (isId(v[0], "function") || isOp(v[0], "\\")) return "a small function";
22231
22265
  return null;
@@ -22510,7 +22544,7 @@ function condWords4(list3, neg2, preCall = null) {
22510
22544
  const v = at02(list3);
22511
22545
  if (!v.length && !preCall) return null;
22512
22546
  const g = groups2(v);
22513
- for (const [ops, join2, flip] of [[["||", "|"], " or ", " and "], [["&&", "&"], " and ", " or "]]) {
22547
+ for (const [ops, join3, flip] of [[["||", "|"], " or ", " and "], [["&&", "&"], " and ", " or "]]) {
22514
22548
  const parts = [[]];
22515
22549
  for (const x of g) {
22516
22550
  if (x.length === 1 && x[0].t === "op" && ops.includes(x[0].text)) parts.push([]);
@@ -22519,7 +22553,7 @@ function condWords4(list3, neg2, preCall = null) {
22519
22553
  if (parts.length > 1) {
22520
22554
  if (neg2) return null;
22521
22555
  const said = parts.map((p) => condWords4(p, neg2));
22522
- return said.some((s) => !s || /^not: /.test(s)) ? null : said.join(join2);
22556
+ return said.some((s) => !s || /^not: /.test(s)) ? null : said.join(join3);
22523
22557
  }
22524
22558
  }
22525
22559
  if (!preCall && isOp(g[0]?.[0], "!")) return condWords4(v.slice(1), !neg2);
@@ -22535,11 +22569,11 @@ function condWords4(list3, neg2, preCall = null) {
22535
22569
  }
22536
22570
  }
22537
22571
  }
22538
- const call = preCall ?? callOf(v);
22539
- if (call) {
22540
- const a0 = call.args[0] ? sayValue3(call.args[0].toks) : null;
22572
+ const call2 = preCall ?? callOf(v);
22573
+ if (call2) {
22574
+ const a0 = call2.args[0] ? sayValue3(call2.args[0].toks) : null;
22541
22575
  const yes = (p, n) => neg2 ? n : p;
22542
- switch (call.bare) {
22576
+ switch (call2.bare) {
22543
22577
  // NULL, not "empty": an empty text "" is a different thing in R.
22544
22578
  case "is.null":
22545
22579
  case "is_null":
@@ -22553,7 +22587,7 @@ function condWords4(list3, neg2, preCall = null) {
22553
22587
  case "dir.exists":
22554
22588
  return `the folder ${a0} ${yes("exists", "does not exist")}`;
22555
22589
  case "exists": {
22556
- const where = call.args.find((x) => x.name === "envir" || x.name === "where") ?? call.args.filter((x) => !x.name)[1];
22590
+ const where = call2.args.find((x) => x.name === "envir" || x.name === "where") ?? call2.args.filter((x) => !x.name)[1];
22557
22591
  return `${a0} ${yes("exists", "does not exist")}${where ? ` in ${sayValue3(where.toks) ?? "an environment"}` : ""}`;
22558
22592
  }
22559
22593
  case "length":
@@ -22561,7 +22595,7 @@ function condWords4(list3, neg2, preCall = null) {
22561
22595
  case "NROW":
22562
22596
  case "ncol":
22563
22597
  case "nchar":
22564
- return `${callNoun(call)} is ${yes("not 0", "0")}`;
22598
+ return `${callNoun(call2)} is ${yes("not 0", "0")}`;
22565
22599
  case "nzchar":
22566
22600
  return `${a0} is ${yes("not empty", "empty")}`;
22567
22601
  case "isTRUE":
@@ -22570,20 +22604,20 @@ function condWords4(list3, neg2, preCall = null) {
22570
22604
  return `${a0} is ${yes("no", "not no")}`;
22571
22605
  case "inherits":
22572
22606
  case "is":
22573
- return `${a0} is ${yes("", "not ")}a ${call.args[1] ? at02(call.args[1].toks)[0]?.value ?? sayValue3(call.args[1].toks) : "kind"}`;
22607
+ return `${a0} is ${yes("", "not ")}a ${call2.args[1] ? at02(call2.args[1].toks)[0]?.value ?? sayValue3(call2.args[1].toks) : "kind"}`;
22574
22608
  case "identical":
22575
- return `${a0} is ${yes("", "not ")}${call.args[1] ? sayValue3(call.args[1].toks) : "?"}`;
22609
+ return `${a0} is ${yes("", "not ")}${call2.args[1] ? sayValue3(call2.args[1].toks) : "?"}`;
22576
22610
  case "interactive":
22577
22611
  return `it is ${yes("", "not ")}running with a person at the keyboard`;
22578
22612
  case "requireNamespace":
22579
- return `the ${at02(call.args[0]?.toks ?? [])[0]?.value ?? "needed"} package is ${yes("installed", "not installed")}`;
22613
+ return `the ${at02(call2.args[0]?.toks ?? [])[0]?.value ?? "needed"} package is ${yes("installed", "not installed")}`;
22580
22614
  case "any":
22581
- return `${yes("any", "none")} of ${a0 ?? "them"}${call.args[0] ? "" : ""} ${neg2 ? "holds" : "holds"}`.replace(/ +/g, " ");
22615
+ return `${yes("any", "none")} of ${a0 ?? "them"}${call2.args[0] ? "" : ""} ${neg2 ? "holds" : "holds"}`.replace(/ +/g, " ");
22582
22616
  case "all":
22583
22617
  return `${yes("all", "not all")} of ${a0 ?? "them"} hold`;
22584
22618
  default:
22585
- if (KIND_IS[call.bare] && call.args.length === 1) return `${a0} is ${yes("", "not ")}${KIND_IS[call.bare]}`;
22586
- return `${yes("", "not: ")}${rWords(call.bare)}${call.args.length ? ` (${call.args.map((x) => x.name ? `${rWords(x.name)} = ${sayValue3(x.toks) ?? "\u2026"}` : sayValue3(x.toks) ?? "\u2026").join(", ")})` : ""}`;
22619
+ if (KIND_IS[call2.bare] && call2.args.length === 1) return `${a0} is ${yes("", "not ")}${KIND_IS[call2.bare]}`;
22620
+ return `${yes("", "not: ")}${rWords(call2.bare)}${call2.args.length ? ` (${call2.args.map((x) => x.name ? `${rWords(x.name)} = ${sayValue3(x.toks) ?? "\u2026"}` : sayValue3(x.toks) ?? "\u2026").join(", ")})` : ""}`;
22587
22621
  }
22588
22622
  }
22589
22623
  const val = sayValue3(v);
@@ -22676,13 +22710,13 @@ var fixedOf2 = (list3) => {
22676
22710
  if (v.length === 1 && v[0].t === "num" && /^\d+(\.\d+)?L?$/.test(v[0].text)) return v[0].text.replace(/L$/, "");
22677
22711
  if (v.length === 2 && isOp(v[0], "-") && v[1].t === "num") return `-${v[1].text.replace(/L$/, "")}`;
22678
22712
  if (v.length === 1 && v[0].t === "id" && /^(TRUE|FALSE)$/.test(v[0].text)) return v[0].text.toLowerCase();
22679
- const call = callOf(v);
22680
- if (call && (call.bare === "return" || call.bare === "invisible") && call.args.length === 1) return fixedOf2(call.args[0].toks);
22713
+ const call2 = callOf(v);
22714
+ if (call2 && (call2.bare === "return" || call2.bare === "invisible") && call2.args.length === 1) return fixedOf2(call2.args[0].toks);
22681
22715
  return null;
22682
22716
  };
22683
22717
  var colsOf = (args) => list2(args.map((a) => a.name ? rWords(a.name) : sayValue3(a.toks) ?? "\u2026").slice(0, 6));
22684
- function verbStep(call) {
22685
- const { bare: bare2, args } = call;
22718
+ function verbStep(call2) {
22719
+ const { bare: bare2, args } = call2;
22686
22720
  const plain = args.filter((a) => !a.name);
22687
22721
  switch (bare2) {
22688
22722
  case "filter":
@@ -22765,9 +22799,9 @@ function verbStep(call) {
22765
22799
  case "data.frame":
22766
22800
  return { kind: "set", says: "Turns it into a table" };
22767
22801
  default: {
22768
- const verb = callVerb({ ...call, args: [{ name: null, toks: [] }, ...args] });
22802
+ const verb = callVerb({ ...call2, args: [{ name: null, toks: [] }, ...args] });
22769
22803
  if (verb) return { kind: "call", says: verb.replace(/ \?/g, "") };
22770
- const noun = callNoun(call);
22804
+ const noun = callNoun(call2);
22771
22805
  if (noun) return { kind: "set", says: `Works out ${noun}` };
22772
22806
  return { kind: "call", says: `Calls ${rWords(bare2)}`, callee: bare2 };
22773
22807
  }
@@ -22861,17 +22895,17 @@ function makeReader2(src) {
22861
22895
  }
22862
22896
  function returnStep(list3, s, e) {
22863
22897
  const v = at02(list3);
22864
- const call = callOf(v);
22865
- if (call && (call.bare === "return" || call.bare === "invisible") && call.args.length <= 1) {
22866
- if (!call.args.length || !at02(call.args[0].toks).length) return { kind: "return", says: "Stops here", ...base2(s, e) };
22867
- return returnStep(call.args[0].toks, s, e);
22898
+ const call2 = callOf(v);
22899
+ if (call2 && (call2.bare === "return" || call2.bare === "invisible") && call2.args.length <= 1) {
22900
+ if (!call2.args.length || !at02(call2.args[0].toks).length) return { kind: "return", says: "Stops here", ...base2(s, e) };
22901
+ return returnStep(call2.args[0].toks, s, e);
22868
22902
  }
22869
22903
  const pipe = pipeline(v);
22870
22904
  if (pipe) return null;
22871
22905
  const said = sayValue3(v);
22872
22906
  if (said) return { kind: "return", says: `Returns ${said}`, ...base2(s, e) };
22873
- if (call) {
22874
- const verb = callVerb(call);
22907
+ if (call2) {
22908
+ const verb = callVerb(call2);
22875
22909
  if (verb) return { kind: "return", says: `Returns the result of ${gerund(verb)}`, ...base2(s, e) };
22876
22910
  }
22877
22911
  return { kind: "return", says: "Returns a computed value", restates: true, ...base2(s, e) };
@@ -22966,11 +23000,11 @@ function makeReader2(src) {
22966
23000
  const inAt = inner.findIndex((x2) => isId(x2, "in"));
22967
23001
  const x = inner[0]?.text ?? "item";
22968
23002
  const over = inner.slice(inAt + 1);
22969
- const call = callOf(over);
23003
+ const call2 = callOf(over);
22970
23004
  const og = groups2(over);
22971
23005
  let says;
22972
- if (call?.bare === "seq_along") says = `For each position ${rWords(x)} in ${sayValue3(call.args[0]?.toks ?? []) ?? "the list"}`;
22973
- else if (call?.bare === "seq_len") says = `Counts ${rWords(x)} from 1 to ${sayValue3(call.args[0]?.toks ?? []) ?? "n"}`;
23006
+ if (call2?.bare === "seq_along") says = `For each position ${rWords(x)} in ${sayValue3(call2.args[0]?.toks ?? []) ?? "the list"}`;
23007
+ else if (call2?.bare === "seq_len") says = `Counts ${rWords(x)} from 1 to ${sayValue3(call2.args[0]?.toks ?? []) ?? "n"}`;
22974
23008
  else if (og.length === 3 && isOp(og[1][0], ":")) says = `Counts ${rWords(x)} from ${sayValue3(og[0]) ?? "?"} to ${sayValue3(og[2]) ?? "?"}`;
22975
23009
  else says = `For each ${rWords(x)} in ${sayValue3(over) ?? "the list"}`;
22976
23010
  const kids2 = stepsOfBody(open.match + 1, e, { ...ctx, last: false });
@@ -23029,14 +23063,14 @@ function makeReader2(src) {
23029
23063
  return ctx.fn ? [{ kind: "set", says: `Defines a helper, ${rWords(lv[0].text)}`, ...base2(s, e, head(s, e)) }] : [];
23030
23064
  }
23031
23065
  const rv = at02(rhs);
23032
- const call = callOf(rv);
23033
- if (call && /^(R6Class|setRefClass|setClass)$/.test(call.bare)) {
23034
- defineThing(lv[0]?.text ?? "", call, s, e);
23066
+ const call2 = callOf(rv);
23067
+ if (call2 && /^(R6Class|setRefClass|setClass)$/.test(call2.bare)) {
23068
+ defineThing(lv[0]?.text ?? "", call2, s, e);
23035
23069
  return [];
23036
23070
  }
23037
- if (call && call.bare === "tryCatch") return [tryStep(call, s, e, ctx, target)];
23038
- if (call && /^(lapply|sapply|vapply|map|map_chr|map_dbl|map_int|map_lgl|map_dfr|purrr::map|Map|mapply)$/.test(call.bare)) {
23039
- const l = loopOfApply(call, s, e, ctx);
23071
+ if (call2 && call2.bare === "tryCatch") return [tryStep(call2, s, e, ctx, target)];
23072
+ if (call2 && /^(lapply|sapply|vapply|map|map_chr|map_dbl|map_int|map_lgl|map_dfr|purrr::map|Map|mapply)$/.test(call2.bare)) {
23073
+ const l = loopOfApply(call2, s, e, ctx);
23040
23074
  if (l) return [{ ...l, says: `${l.says}, keeping the answers as ${target}` }];
23041
23075
  }
23042
23076
  if (isId(rv[0], "if")) {
@@ -23050,17 +23084,17 @@ function makeReader2(src) {
23050
23084
  if (pipe) return [{ kind: "set", says: `Works out ${target}, step by step`, ...base2(s, e, head(s, e)), children: pipelineSteps(pipe, s, e) }];
23051
23085
  if (lv.length >= 3 && isId(lv[0], "self") && isOp(lv[1], "$") && rv.length === 1 && rv[0].t === "id" && rv[0].text === lv[2].text) return [{ kind: "set", says: `Keeps the ${rWords(rv[0].text)} it is given`, ...base2(s, e) }];
23052
23086
  if (lv.length === 1 && rv.length === 1 && rv[0].t === "id" && ctx.fn && rv[0].text === lv[0].text) return [{ kind: "set", says: `Keeps the ${rWords(rv[0].text)} it is given`, ...base2(s, e) }];
23053
- if (call) {
23054
- if (call.bare === "switch") {
23055
- const st = switchStep(call, s, e, { ...ctx, last: true });
23087
+ if (call2) {
23088
+ if (call2.bare === "switch") {
23089
+ const st = switchStep(call2, s, e, { ...ctx, last: true });
23056
23090
  giveValue2(st, target);
23057
23091
  return [st];
23058
23092
  }
23059
- const verb = callVerb(call);
23060
- if (verb) return [{ kind: "call", says: `${verb}, keeping it as ${target}`, callee: call.bare, ...base2(s, e) }];
23061
- const noun = callNoun(call);
23093
+ const verb = callVerb(call2);
23094
+ if (verb) return [{ kind: "call", says: `${verb}, keeping it as ${target}`, callee: call2.bare, ...base2(s, e) }];
23095
+ const noun = callNoun(call2);
23062
23096
  if (noun) return [{ kind: "set", says: noun === "an empty list" || noun === "an empty table" ? `Starts ${target} as ${noun}` : `Sets ${target} to ${noun}`, ...base2(s, e) }];
23063
- return [{ kind: "set", says: `Works out ${target} from ${rWords(call.bare)}`, callee: call.bare, ...base2(s, e) }];
23097
+ return [{ kind: "set", says: `Works out ${target} from ${rWords(call2.bare)}`, callee: call2.bare, ...base2(s, e) }];
23064
23098
  }
23065
23099
  const val = sayValue3(rv);
23066
23100
  return [{ kind: "set", says: val ? `Sets ${target} to ${val}` : `Works out ${target}`, ...val ? {} : { restates: true }, ...base2(s, e) }];
@@ -23079,8 +23113,8 @@ function makeReader2(src) {
23079
23113
  };
23080
23114
  fix([step]);
23081
23115
  }
23082
- function loopOfApply(call, s, e, ctx) {
23083
- const [xs, f] = call.args.filter((a) => !a.name || a.name === "X" || a.name === "FUN" || a.name === ".x" || a.name === ".f");
23116
+ function loopOfApply(call2, s, e, ctx) {
23117
+ const [xs, f] = call2.args.filter((a) => !a.name || a.name === "X" || a.name === "FUN" || a.name === ".x" || a.name === ".f");
23084
23118
  if (!xs || !f) return null;
23085
23119
  const fv = fnValue(f.toks);
23086
23120
  const what = sayValue3(xs.toks) ?? "the list";
@@ -23091,15 +23125,15 @@ function makeReader2(src) {
23091
23125
  const kids2 = stepsOfBody(fv.from, fv.to, { ...ctx, last: true, fn: true });
23092
23126
  return { kind: "loop", says: `For each ${rWords(fv.params[0]?.name ?? "item")} in ${what}`, ...base2(s, e, head(s, e)), ...kids2.length ? { children: kids2 } : {} };
23093
23127
  }
23094
- function tryStep(call, s, e, ctx, target = null) {
23128
+ function tryStep(call2, s, e, ctx, target = null) {
23095
23129
  const step = { kind: "try", says: `Tries these steps and handles any error${target ? ` (the answer becomes ${target})` : ""}`, ...base2(s, e, head(s, e)) };
23096
- const expr = call.args.find((a) => !a.name || a.name === "expr");
23130
+ const expr = call2.args.find((a) => !a.name || a.name === "expr");
23097
23131
  if (expr && at02(expr.toks).length) {
23098
23132
  const r = range(at02(expr.toks));
23099
23133
  const kids2 = stepsOfBody(r[0], r[1], { ...ctx, last: !!target || ctx.last });
23100
23134
  if (kids2.length) step.children = kids2;
23101
23135
  }
23102
- for (const a of call.args.filter((x) => x.name && x.name !== "expr")) {
23136
+ for (const a of call2.args.filter((x) => x.name && x.name !== "expr")) {
23103
23137
  const fv = fnValue(a.toks);
23104
23138
  const r = at02(a.toks).length ? range(at02(a.toks)) : null;
23105
23139
  if (a.name === "finally") {
@@ -23114,8 +23148,8 @@ function makeReader2(src) {
23114
23148
  }
23115
23149
  return step;
23116
23150
  }
23117
- function switchStep(call, s, e, ctx) {
23118
- const [subject, ...rest2] = call.args;
23151
+ function switchStep(call2, s, e, ctx) {
23152
+ const [subject, ...rest2] = call2.args;
23119
23153
  const arms = [];
23120
23154
  let pending = [];
23121
23155
  for (const a of rest2) {
@@ -23139,9 +23173,9 @@ function makeReader2(src) {
23139
23173
  if (ctx.last) steps.push({ kind: "return", says: "Returns the result", ...base2(s, e) });
23140
23174
  return steps;
23141
23175
  }
23142
- const call = callOf(v);
23143
- if (call) {
23144
- const { bare: bare2, args } = call;
23176
+ const call2 = callOf(v);
23177
+ if (call2) {
23178
+ const { bare: bare2, args } = call2;
23145
23179
  const a0 = args[0] ? sayValue3(args[0].toks) : null;
23146
23180
  if (bare2 === "stop_input_type") {
23147
23181
  const what = at02(args[1]?.toks ?? [])[0];
@@ -23170,7 +23204,7 @@ function makeReader2(src) {
23170
23204
  return [{ kind: "check", says: `Checks that ${c.every(Boolean) ? c.join(" and ") : "its conditions hold"} (stops with an error if not)`, ...base2(s, e) }];
23171
23205
  }
23172
23206
  if (/^(library|require|requireNamespace|suppressPackageStartupMessages|suppressMessages)$/.test(bare2)) {
23173
- const inner = bare2.startsWith("suppress") ? callOf(at02(args[0]?.toks ?? [])) : call;
23207
+ const inner = bare2.startsWith("suppress") ? callOf(at02(args[0]?.toks ?? [])) : call2;
23174
23208
  if (inner && /^(library|require)$/.test(inner.bare)) {
23175
23209
  const p = at02(inner.args[0]?.toks ?? [])[0];
23176
23210
  return [{ kind: "set", says: `Loads the ${p?.value ?? p?.text ?? "?"} package`, ...base2(s, e) }];
@@ -23178,7 +23212,7 @@ function makeReader2(src) {
23178
23212
  if (!inner) return [{ kind: "call", says: "Runs it quietly", ...base2(s, e) }];
23179
23213
  }
23180
23214
  if (bare2 === "source") return [{ kind: "call", says: `Runs the R file ${a0 ?? "?"}`, ...base2(s, e) }];
23181
- if (bare2 === "tryCatch" || bare2 === "withCallingHandlers") return [tryStep(call, s, e, ctx)];
23215
+ if (bare2 === "tryCatch" || bare2 === "withCallingHandlers") return [tryStep(call2, s, e, ctx)];
23182
23216
  if (bare2 === "try") {
23183
23217
  const r = args[0] && at02(args[0].toks).length ? range(at02(args[0].toks)) : null;
23184
23218
  const kids2 = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
@@ -23189,9 +23223,9 @@ function makeReader2(src) {
23189
23223
  const kids2 = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
23190
23224
  return [{ kind: "call", says: "At the end, even if something fails, it runs these steps", ...base2(s, e, head(s, e)), ...kids2.length ? { children: kids2, nested: true } : {} }];
23191
23225
  }
23192
- if (bare2 === "switch") return [switchStep(call, s, e, ctx)];
23226
+ if (bare2 === "switch") return [switchStep(call2, s, e, ctx)];
23193
23227
  if (/^(lapply|sapply|vapply|map|walk|map_chr|map_dbl|map_int|map_lgl|map_dfr|Map|mapply|purrr::walk)$/.test(bare2)) {
23194
- const l = loopOfApply(call, s, e, ctx);
23228
+ const l = loopOfApply(call2, s, e, ctx);
23195
23229
  if (l) return [l];
23196
23230
  }
23197
23231
  if (bare2 === "test_that") {
@@ -23217,7 +23251,7 @@ function makeReader2(src) {
23217
23251
  const r = returnStep(v, s, e);
23218
23252
  if (r && !r.restates) return [r];
23219
23253
  }
23220
- const verb = callVerb(call);
23254
+ const verb = callVerb(call2);
23221
23255
  if (verb) return [{ kind: "call", says: verb, callee: bare2, ...base2(s, e) }];
23222
23256
  if (ctx.last) {
23223
23257
  const r = returnStep(v, s, e);
@@ -23232,9 +23266,9 @@ function makeReader2(src) {
23232
23266
  const val = sayValue3(v);
23233
23267
  return [val ? { kind: "call", says: `Works out ${val}`, ...base2(s, e) } : { kind: "other", says: code3(s, e), ...base2(s, e) }];
23234
23268
  }
23235
- function defineThing(name, call, s, e) {
23269
+ function defineThing(name, call2, s, e) {
23236
23270
  const lines = [lineAt4(toks[s].at), lineAt4(toks[e - 1].end - 1)];
23237
- const className = at02(call.args[0]?.toks ?? [])[0]?.value ?? at02(call.args.find((a) => a.name === "Classname")?.toks ?? [])[0]?.value ?? name;
23271
+ const className = at02(call2.args[0]?.toks ?? [])[0]?.value ?? at02(call2.args.find((a) => a.name === "Classname")?.toks ?? [])[0]?.value ?? name;
23238
23272
  const { doc } = docAbove5(s);
23239
23273
  const thing = { kind: "record", name: className || name, lines, ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
23240
23274
  const listArgs = (a) => {
@@ -23280,18 +23314,18 @@ function makeReader2(src) {
23280
23314
  }
23281
23315
  }
23282
23316
  };
23283
- if (call.bare === "R6Class") {
23317
+ if (call2.bare === "R6Class") {
23284
23318
  for (const part of ["public", "private", "active"]) {
23285
- const args = listArgs(call.args.find((a) => a.name === part));
23319
+ const args = listArgs(call2.args.find((a) => a.name === part));
23286
23320
  knowsFrom(args, false);
23287
23321
  methodsFrom(args);
23288
23322
  }
23289
- } else if (call.bare === "setRefClass") {
23290
- knowsFrom(listArgs(call.args.find((a) => a.name === "fields")), true);
23291
- methodsFrom(listArgs(call.args.find((a) => a.name === "methods")));
23323
+ } else if (call2.bare === "setRefClass") {
23324
+ knowsFrom(listArgs(call2.args.find((a) => a.name === "fields")), true);
23325
+ methodsFrom(listArgs(call2.args.find((a) => a.name === "methods")));
23292
23326
  } else {
23293
- knowsFrom(listArgs(call.args.find((a) => a.name === "representation" || a.name === "slots") ?? call.args.find((a, k) => k === 1 && !a.name)), true);
23294
- for (const p of listArgs(call.args.find((a) => a.name === "prototype")) || []) {
23327
+ knowsFrom(listArgs(call2.args.find((a) => a.name === "representation" || a.name === "slots") ?? call2.args.find((a, k) => k === 1 && !a.name)), true);
23328
+ for (const p of listArgs(call2.args.find((a) => a.name === "prototype")) || []) {
23295
23329
  const k = thing.knows.find((q) => q.name === p.name);
23296
23330
  if (k) k.start = at02(p.toks).map((x) => x.text).join("");
23297
23331
  }
@@ -23374,12 +23408,12 @@ function decisionOf2(r, fv) {
23374
23408
  }
23375
23409
  if (!isLast) return null;
23376
23410
  const v = at02(toks.slice(s, e));
23377
- const call = callOf(v);
23378
- if (call?.bare === "switch") {
23379
- const subj = condJs2(call.args[0]?.toks ?? []);
23411
+ const call2 = callOf(v);
23412
+ if (call2?.bare === "switch") {
23413
+ const subj = condJs2(call2.args[0]?.toks ?? []);
23380
23414
  if (!subj || /\s/.test(subj)) return null;
23381
23415
  let pending = [];
23382
- for (const a of call.args.slice(1)) {
23416
+ for (const a of call2.args.slice(1)) {
23383
23417
  const vt = at02(a.toks);
23384
23418
  if (a.name && !vt.length) {
23385
23419
  pending.push(a.name);
@@ -23411,10 +23445,10 @@ function rReading(src, file = "") {
23411
23445
  for (const [s, e] of splitStatements2(r.toks, 0, r.toks.length)) {
23412
23446
  const v = at02(r.toks.slice(s, e));
23413
23447
  const steps = r.statement(s, e, {});
23414
- const call = callOf(v);
23448
+ const call2 = callOf(v);
23415
23449
  const assign = groups2(v).findIndex((x) => x.length === 1 && x[0].t === "op" && /^(<-|=|<<-)$/.test(x[0].text));
23416
23450
  const rhs = assign > 0 ? callOf(groups2(v).slice(assign + 1).flat()) : null;
23417
- const isDef = call && DEFINITION.test(call.bare) || rhs && DEFINITION.test(rhs.bare) || !steps.length;
23451
+ const isDef = call2 && DEFINITION.test(call2.bare) || rhs && DEFINITION.test(rhs.bare) || !steps.length;
23418
23452
  if (!isDef) real = true;
23419
23453
  topSteps.push(...steps);
23420
23454
  }
@@ -23441,7 +23475,7 @@ function rReading(src, file = "") {
23441
23475
  return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
23442
23476
  }
23443
23477
  function rThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
23444
- const norm2 = (v) => String(v ?? "").trim().replace(/^(?:list|c|character|numeric|integer|logical|vector)\(\s*(?:0)?\s*\)$/, "[]").replace(/^NULL$/, "null").replace(/^NA$/, "null").replace(/^TRUE$/, "true").replace(/^FALSE$/, "false").replace(/^(\d+)L$/, "$1").replace(/^'(.*)'$/, '"$1"');
23478
+ const norm3 = (v) => String(v ?? "").trim().replace(/^(?:list|c|character|numeric|integer|logical|vector)\(\s*(?:0)?\s*\)$/, "[]").replace(/^NULL$/, "null").replace(/^NA$/, "null").replace(/^TRUE$/, "true").replace(/^FALSE$/, "false").replace(/^(\d+)L$/, "$1").replace(/^'(.*)'$/, '"$1"');
23445
23479
  return rReading(src, file).things.map((t) => ({
23446
23480
  kind: t.kind,
23447
23481
  name: t.name,
@@ -23450,7 +23484,7 @@ function rThings(src, file, { words: w, kindWords: kindWords3, startValue: start
23450
23484
  ...t.doc ? { doc: t.doc } : {},
23451
23485
  choices: t.choices,
23452
23486
  memberRanges: t.memberRanges,
23453
- knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ? kindWords3(k.type) : null, start: k.start == null || k.start === "" ? null : typeof k.start === "object" ? k.start.param == null ? "given when it starts" : `${startValue2(norm2(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm2(k.start)), line: k.line }))
23487
+ knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ? kindWords3(k.type) : null, start: k.start == null || k.start === "" ? null : typeof k.start === "object" ? k.start.param == null ? "given when it starts" : `${startValue2(norm3(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm3(k.start)), line: k.line }))
23454
23488
  }));
23455
23489
  }
23456
23490
 
@@ -23548,6 +23582,36 @@ function matchClose(src, open) {
23548
23582
  return -1;
23549
23583
  }
23550
23584
  var READING_RUST = false;
23585
+ function textRanges(src) {
23586
+ const flags2 = new Uint8Array(src.length + 1);
23587
+ for (let i = 0; i < src.length; i++) {
23588
+ const c = src[i];
23589
+ if (c === "/" && src[i + 1] === "/") {
23590
+ const e = src.indexOf("\n", i);
23591
+ const end = e < 0 ? src.length : e;
23592
+ flags2.fill(1, i, end);
23593
+ i = end;
23594
+ continue;
23595
+ }
23596
+ if (c === "/" && src[i + 1] === "*") {
23597
+ const e = src.indexOf("*/", i + 2);
23598
+ const end = e < 0 ? src.length : e + 2;
23599
+ flags2.fill(1, i, end);
23600
+ i = end - 1;
23601
+ continue;
23602
+ }
23603
+ if (c === '"' || c === "'") {
23604
+ let end;
23605
+ if (c === '"' && src[i - 1] === "@" || c === '"' && src[i - 1] === "$" && src[i - 2] === "@") {
23606
+ end = i + 1;
23607
+ while (end < src.length && !(src[end] === '"' && src[end + 1] !== '"')) end += src[end] === '"' ? 2 : 1;
23608
+ } else end = skipString2(src, i);
23609
+ flags2.fill(1, i, Math.min(src.length, end + 1));
23610
+ i = end;
23611
+ }
23612
+ }
23613
+ return flags2;
23614
+ }
23551
23615
  function skipString2(src, i) {
23552
23616
  const q = src[i];
23553
23617
  if (q === '"' && src[i + 1] === '"' && src[i + 2] === '"') {
@@ -23776,6 +23840,7 @@ function findFunctions(src, language) {
23776
23840
  patterns.javascript = patterns.typescript;
23777
23841
  patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
23778
23842
  const seen = /* @__PURE__ */ new Set();
23843
+ const inText = language === "csharp" || language === "java" ? textRanges(src) : null;
23779
23844
  for (const re of patterns[language] || []) {
23780
23845
  let m;
23781
23846
  re.lastIndex = 0;
@@ -23783,6 +23848,7 @@ function findFunctions(src, language) {
23783
23848
  const name = m[1];
23784
23849
  const open = src.indexOf("(", m.index + m[0].length - 1);
23785
23850
  if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
23851
+ if (inText && (inText[m.index + m[0].lastIndexOf(name, m[0].length - 1)] || language === "csharp" && name === "async")) continue;
23786
23852
  const close = matchClose(src, open);
23787
23853
  if (close < 0) continue;
23788
23854
  const after = src.slice(close + 1, close + 1 + 4e3);
@@ -23837,7 +23903,7 @@ function findFunctions(src, language) {
23837
23903
  fns.push({ name: `${m[1].toUpperCase()} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: m[1].toUpperCase(), path: m[2] } });
23838
23904
  }
23839
23905
  }
23840
- const routeRes = language === "php" ? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g] : language === "go" ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g] : language === "typescript" || language === "javascript" ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g] : [];
23906
+ const routeRes = language === "php" ? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g] : language === "go" ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g] : language === "csharp" ? [/\b\w+\.Map(Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"\s*,\s*(?:async\s*)?\(/g] : language === "typescript" || language === "javascript" ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g] : [];
23841
23907
  for (const re of routeRes) {
23842
23908
  let m;
23843
23909
  while (m = re.exec(src)) {
@@ -23848,7 +23914,7 @@ function findFunctions(src, language) {
23848
23914
  const brace = src.indexOf("{", close);
23849
23915
  if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) {
23850
23916
  const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
23851
- if (!(language === "typescript" || language === "javascript") || !arrow || src[close + 1 + arrow[0].length] === "{") continue;
23917
+ if (!(language === "typescript" || language === "javascript" || language === "csharp") || !arrow || src[close + 1 + arrow[0].length] === "{") continue;
23852
23918
  const from = close + 1 + arrow[0].length;
23853
23919
  let depth = 0, end = from, q = null;
23854
23920
  for (; end < src.length; end++) {
@@ -24604,6 +24670,15 @@ function annotateRoutes(fns, src) {
24604
24670
  for (const fn of fns) {
24605
24671
  if (fn.route) continue;
24606
24672
  const above = fn.decorators ? [...fn.decorators].reverse() : lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
24673
+ const std = /^do_(GET|POST|PUT|PATCH|DELETE|HEAD)$/.exec(fn.name ?? "");
24674
+ const stdBody = typeof fn.body === "string" ? fn.body : Array.isArray(fn.pyBody) ? fn.pyBody.map((x) => x.text).join("\n") : null;
24675
+ if (std && stdBody) {
24676
+ const paths = new Set([...stdBody.matchAll(/\bself\.path\s*(?:==|!=)\s*['"](\/[^'"]*)['"]/g)].map((x) => x[1]));
24677
+ if (paths.size === 1) {
24678
+ fn.route = { method: std[1], path: [...paths][0] };
24679
+ continue;
24680
+ }
24681
+ }
24607
24682
  for (const l of above) {
24608
24683
  let m;
24609
24684
  if (m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i)) {
@@ -26811,10 +26886,10 @@ function plainFromReading(item2) {
26811
26886
  };
26812
26887
  for (const r of item2.rules) {
26813
26888
  const when = r.when.trim();
26814
- const join2 = / or /.test(when) ? "any" : "all";
26889
+ const join3 = / or /.test(when) ? "any" : "all";
26815
26890
  if (/ or /.test(when) && / and /.test(when)) return null;
26816
26891
  const conditions = [];
26817
- for (const part of when.split(join2 === "all" ? " and " : " or ")) {
26892
+ for (const part of when.split(join3 === "all" ? " and " : " or ")) {
26818
26893
  const t = part.trim();
26819
26894
  let m;
26820
26895
  const input2 = (id) => inputs.find((i) => i.id === id);
@@ -26838,7 +26913,7 @@ function plainFromReading(item2) {
26838
26913
  } else return null;
26839
26914
  }
26840
26915
  if (!outcome2(r.result)) return null;
26841
- model.rules.push({ outcome: r.result, join: join2, conditions });
26916
+ model.rules.push({ outcome: r.result, join: join3, conditions });
26842
26917
  }
26843
26918
  if (!outcome2(item2.otherwise.result)) return null;
26844
26919
  model.otherwise = item2.otherwise.result;
@@ -27249,11 +27324,11 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
27249
27324
  return { type: "block", kind: m[1], head: (m[2] ?? "").trim(), kids: body2, line };
27250
27325
  };
27251
27326
  const nodes = parseNodes(null, false);
27252
- const join2 = (list3) => {
27327
+ const join3 = (list3) => {
27253
27328
  const out = [];
27254
27329
  for (const n of list3) {
27255
27330
  if (n.type === "el") {
27256
- n.kids = join2(n.kids);
27331
+ n.kids = join3(n.kids);
27257
27332
  out.push(n);
27258
27333
  continue;
27259
27334
  }
@@ -27261,7 +27336,7 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
27261
27336
  out.push(n);
27262
27337
  continue;
27263
27338
  }
27264
- n.kids = join2(n.kids);
27339
+ n.kids = join3(n.kids);
27265
27340
  const prev = out[out.length - 1];
27266
27341
  if (n.kind === "else" && prev?.type === "cond") {
27267
27342
  let tail = prev;
@@ -27287,7 +27362,7 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
27287
27362
  }
27288
27363
  return out;
27289
27364
  };
27290
- return join2(nodes);
27365
+ return join3(nodes);
27291
27366
  }
27292
27367
  var CONTAINERS = /* @__PURE__ */ new Set(["div", "span", "section", "main", "article", "aside", "Fragment", "React.Fragment", "ng-container", "ng-template", "template", "body", "html"]);
27293
27368
  var INLINE = /* @__PURE__ */ new Set(["strong", "em", "b", "i", "small", "code", "mark", "u", "sup", "sub", "abbr", "time"]);
@@ -28244,11 +28319,18 @@ function cDocAbove(src, idx) {
28244
28319
  return docAbove4(src, idx);
28245
28320
  }
28246
28321
  function ownLevel(body2) {
28247
- let depth = 0, own = "";
28248
- for (const c of body2) {
28249
- if (c === "{") depth++;
28322
+ let depth = 0, own = "", start = 0;
28323
+ for (let i = 0; i < body2.length; i++) {
28324
+ const c = body2[i];
28325
+ if (c === "{") {
28326
+ if (depth === 0) start = i;
28327
+ depth++;
28328
+ }
28250
28329
  if (depth === 0) own += c;
28251
- if (c === "}") depth--;
28330
+ if (c === "}") {
28331
+ depth--;
28332
+ if (depth === 0 && /(?:=|\bnew\b[\w.<>,[\] ?]*(?:\([^()]*\))?)\s*$/.test(own) && body2.slice(start + 1, i).trim()) own = `${own.replace(/\s+$/, "")} {\u2026}`;
28333
+ }
28252
28334
  }
28253
28335
  return own;
28254
28336
  }
@@ -28273,7 +28355,11 @@ function goDoc(src, at2, name) {
28273
28355
  return t.charAt(0).toUpperCase() + t.slice(1);
28274
28356
  }
28275
28357
  function makeThingReaders({ words: words11, kindWords: kindWords3, startValue: startValue2 }) {
28276
- const know = (name, type, start, params, line = null) => ({ name, label: words11(name.replace(/^[_$]+|_$/g, "")), kind: type ? kindWords3(type) : null, start: start != null && start !== "" ? startValue2(start, params) : null, line });
28358
+ const know = (name, type, start, params, line = null) => {
28359
+ const kind = type ? kindWords3(type) : null;
28360
+ const said = start != null && start !== "" ? /^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? "") ? "worked out when it starts" : startValue2(start, params) : null;
28361
+ return { name, label: words11(name.replace(/^[_$]+|_$/g, "")), kind, start: said, line };
28362
+ };
28277
28363
  function curlyThings(src, file, language) {
28278
28364
  const lineAt4 = lineFinder5(src);
28279
28365
  const out = [];
@@ -28342,6 +28428,7 @@ function makeThingReaders({ words: words11, kindWords: kindWords3, startValue: s
28342
28428
  thing.knows.push(know(f[2], f[1], f[3], params));
28343
28429
  }
28344
28430
  }
28431
+ thing.knows = thing.knows.filter((k, i, all) => all.findIndex((x) => x.label === k.label) === i);
28345
28432
  const ctorRe = language === "php" ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === "kotlin" ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
28346
28433
  const ctor = body2.match(ctorRe);
28347
28434
  if (ctor) {
@@ -28707,8 +28794,8 @@ function makeThingReaders({ words: words11, kindWords: kindWords3, startValue: s
28707
28794
  const head = mem.head.replace(/^(?:(?:public|private|protected)\s*:\s*)+/, "").replace(/\[\[[^\]]*\]\]\s*/g, "").trim();
28708
28795
  if (!head || /^(?:using|friend|typedef|static_assert|template|enum|class|struct|union|namespace|static|constexpr\s+static|inline\s+static|Q_OBJECT)\b/.test(head)) continue;
28709
28796
  const sig = head.replace(/<[^<>]*(?:<[^<>]*>[^<>]*)*>/g, "<>");
28710
- const call = sig.split(/=(?!=)/)[0];
28711
- if (/\(/.test(call) && !/\(\s*\*\s*\w+\s*\)\s*\(/.test(call)) {
28797
+ const call2 = sig.split(/=(?!=)/)[0];
28798
+ if (/\(/.test(call2) && !/\(\s*\*\s*\w+\s*\)\s*\(/.test(call2)) {
28712
28799
  methods = true;
28713
28800
  const ctor = head.match(new RegExp(`^(?:explicit\\s+|constexpr\\s+|inline\\s+)*${name}\\s*\\(([^)]*)\\)\\s*(?:noexcept\\s*)?(?::\\s*([\\s\\S]+))?$`));
28714
28801
  if (ctor) cppCtor(ctor[1], ctor[2], mem.block, params, inits);
@@ -29178,9 +29265,9 @@ function segsMatch(a, b) {
29178
29265
  return exact;
29179
29266
  }
29180
29267
  var HTTP_SAYS = /^Sends an? ([A-Z]+) request to /;
29181
- function urlArg(call) {
29182
- const args = call.args || [];
29183
- const path = calleePath(call.callee) || [];
29268
+ function urlArg(call2) {
29269
+ const args = call2.args || [];
29270
+ const path = calleePath(call2.callee) || [];
29184
29271
  const last = path.at(-1) || "";
29185
29272
  if (/^NewRequest(WithContext)?$/.test(last)) return args[last.endsWith("Context") ? 2 : 1];
29186
29273
  if (args[0]?.kind === "object") {
@@ -29191,8 +29278,8 @@ function urlArg(call) {
29191
29278
  return args[0];
29192
29279
  }
29193
29280
  function httpOfCode(calls) {
29194
- for (const call of calls) {
29195
- const path = calleePath(call.callee) || [];
29281
+ for (const call2 of calls) {
29282
+ const path = calleePath(call2.callee) || [];
29196
29283
  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()];
29197
29284
  }
29198
29285
  return null;
@@ -29727,14 +29814,14 @@ function linkSystem(model, files) {
29727
29814
  if (!calls.length) continue;
29728
29815
  const http = HTTP_SAYS.exec(nd.text || "") || (nd.explained === false ? httpOfCode(calls) : null);
29729
29816
  let httpDone = false;
29730
- for (const call of calls) {
29731
- const path = calleePath(call.callee);
29817
+ for (const call2 of calls) {
29818
+ const path = calleePath(call2.callee);
29732
29819
  if (!path) continue;
29733
29820
  stats.calls++;
29734
29821
  if (http && !httpDone && /^(fetch|get|post|put|patch|delete|head|request|Get|Post|Put|Patch|Delete|Head|NewRequest|NewRequestWithContext|\w+Async|\w+ForObject|\w+ForEntity|exchange)$/.test(path.at(-1))) {
29735
29822
  httpDone = true;
29736
29823
  const method = http[1];
29737
- const u = urlOf(urlArg(call));
29824
+ const u = urlOf(urlArg(call2));
29738
29825
  const service = u.path ? `${method} ${u.path}` : `${method} request`;
29739
29826
  if (!u.segs) {
29740
29827
  notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: service, why: u.why });
@@ -29752,8 +29839,8 @@ function linkSystem(model, files) {
29752
29839
  }
29753
29840
  const last = path.at(-1);
29754
29841
  const queue = path.length === 2 && /^(add|addBulk)$/.test(last) ? queueNames.get(`${m.file}|${path[0]}`) : null;
29755
- if (queue || EVENT_PUBLISH.test(last) && call.args?.[0]?.kind === "literal" && call.args[0].type === "text") {
29756
- const name = queue ?? String(call.args[0].value);
29842
+ if (queue || EVENT_PUBLISH.test(last) && call2.args?.[0]?.kind === "literal" && call2.args[0].type === "text") {
29843
+ const name = queue ?? String(call2.args[0].value);
29757
29844
  if (GENERIC_EVENTS.has(name)) continue;
29758
29845
  const ls = (listeners.get(name) || []).filter((x) => x.member.id !== m.id);
29759
29846
  for (const x of ls) {
@@ -29763,12 +29850,12 @@ function linkSystem(model, files) {
29763
29850
  if (!ls.length && (queue || /^(publish|publishEvent|sendToQueue|enqueue|basic_publish|produce)$/.test(last))) notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: `${queue ? "message on" : "event"} ${name}`, why: `nothing in this repo listens for ${name}` });
29764
29851
  if (ls.length) continue;
29765
29852
  }
29766
- let p = path, isNew = !!call.new, task = false;
29853
+ let p = path, isNew = !!call2.new, task = false;
29767
29854
  if (p.length >= 2 && /^(delay|apply_async|send|enqueue|perform_async|perform_later)$/.test(last) && langOf.get(m.file) !== "go") {
29768
29855
  p = p.slice(0, -1);
29769
29856
  task = /^(delay|apply_async|perform_async|perform_later)$/.test(last);
29770
29857
  }
29771
- argc = (call.args || []).length;
29858
+ argc = (call2.args || []).length;
29772
29859
  const r = resolve2(m.file, p, isNew, m);
29773
29860
  if (r.member && r.member.id !== m.id) {
29774
29861
  const cross = r.member.file !== m.file;
@@ -29786,6 +29873,2901 @@ function linkSystem(model, files) {
29786
29873
  return model;
29787
29874
  }
29788
29875
 
29876
+ // src/flow/ts-parse.mjs
29877
+ var ParseError2 = class extends Error {
29878
+ constructor(message2, line) {
29879
+ super(message2);
29880
+ this.line = line;
29881
+ }
29882
+ };
29883
+ var PUNCT5 = [
29884
+ ">>>=",
29885
+ "...",
29886
+ "===",
29887
+ "!==",
29888
+ "**=",
29889
+ "<<=",
29890
+ ">>=",
29891
+ ">>>",
29892
+ "&&=",
29893
+ "||=",
29894
+ "??=",
29895
+ "=>",
29896
+ "==",
29897
+ "!=",
29898
+ "<=",
29899
+ ">=",
29900
+ "&&",
29901
+ "||",
29902
+ "??",
29903
+ "?.",
29904
+ "++",
29905
+ "--",
29906
+ "+=",
29907
+ "-=",
29908
+ "*=",
29909
+ "/=",
29910
+ "%=",
29911
+ "&=",
29912
+ "|=",
29913
+ "^=",
29914
+ "**",
29915
+ "<<",
29916
+ ">>",
29917
+ "{",
29918
+ "}",
29919
+ "(",
29920
+ ")",
29921
+ "[",
29922
+ "]",
29923
+ ";",
29924
+ ",",
29925
+ "<",
29926
+ ">",
29927
+ "+",
29928
+ "-",
29929
+ "*",
29930
+ "/",
29931
+ "%",
29932
+ "&",
29933
+ "|",
29934
+ "^",
29935
+ "!",
29936
+ "~",
29937
+ "?",
29938
+ ":",
29939
+ "=",
29940
+ ".",
29941
+ "@",
29942
+ "#"
29943
+ ];
29944
+ var KEYWORDS_BEFORE_REGEX = /* @__PURE__ */ new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
29945
+ function tokenize5(src) {
29946
+ const out = [];
29947
+ let i = 0, line = 1, nl = false;
29948
+ const n = src.length;
29949
+ const prevAllowsRegex = () => {
29950
+ const p = out[out.length - 1];
29951
+ if (!p) return true;
29952
+ if (p.t === "num" || p.t === "str" || p.t === "tpl" || p.t === "re") return false;
29953
+ if (p.t === "id") return KEYWORDS_BEFORE_REGEX.has(p.v);
29954
+ return !(p.v === ")" || p.v === "]" || p.v === "}");
29955
+ };
29956
+ const push = (t, v, extra) => {
29957
+ out.push({ t, v, line, nl, ...extra });
29958
+ nl = false;
29959
+ };
29960
+ while (i < n) {
29961
+ const c = src[i];
29962
+ if (c === "\n") {
29963
+ line++;
29964
+ nl = true;
29965
+ i++;
29966
+ continue;
29967
+ }
29968
+ if (c === " " || c === " " || c === "\r" || c === "\f" || c === "\v" || c === "\uFEFF" || c === "\xA0") {
29969
+ i++;
29970
+ continue;
29971
+ }
29972
+ if (c === "/" && src[i + 1] === "/") {
29973
+ while (i < n && src[i] !== "\n") i++;
29974
+ continue;
29975
+ }
29976
+ if (c === "/" && src[i + 1] === "*") {
29977
+ const end = src.indexOf("*/", i + 2);
29978
+ const stop = end < 0 ? n : end + 2;
29979
+ for (let k = i; k < stop; k++) if (src[k] === "\n") {
29980
+ line++;
29981
+ nl = true;
29982
+ }
29983
+ i = stop;
29984
+ continue;
29985
+ }
29986
+ if (/[A-Za-z_$À-￿]/.test(c)) {
29987
+ let j = i + 1;
29988
+ while (j < n && /[\w$À-￿]/.test(src[j])) j++;
29989
+ push("id", src.slice(i, j));
29990
+ i = j;
29991
+ continue;
29992
+ }
29993
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(src[i + 1] ?? "")) {
29994
+ let j = i + 1;
29995
+ while (j < n && /[\w.]/.test(src[j])) {
29996
+ if ((src[j] === "e" || src[j] === "E") && (src[j + 1] === "-" || src[j + 1] === "+")) j++;
29997
+ j++;
29998
+ }
29999
+ push("num", src.slice(i, j));
30000
+ i = j;
30001
+ continue;
30002
+ }
30003
+ if (c === '"' || c === "'") {
30004
+ let j = i + 1, v = "";
30005
+ while (j < n && src[j] !== c) {
30006
+ if (src[j] === "\\") {
30007
+ v += src[j + 1] ?? "";
30008
+ j += 2;
30009
+ continue;
30010
+ }
30011
+ if (src[j] === "\n") break;
30012
+ v += src[j++];
30013
+ }
30014
+ push("str", v);
30015
+ i = j + 1;
30016
+ continue;
30017
+ }
30018
+ if (c === "`") {
30019
+ const startLine = line;
30020
+ const parts = [];
30021
+ let j = i + 1, text2 = "";
30022
+ while (j < n && src[j] !== "`") {
30023
+ if (src[j] === "\\") {
30024
+ text2 += src[j + 1] ?? "";
30025
+ j += 2;
30026
+ continue;
30027
+ }
30028
+ if (src[j] === "$" && src[j + 1] === "{") {
30029
+ let depth = 1, k = j + 2;
30030
+ while (k < n && depth) {
30031
+ const ch = src[k];
30032
+ if (ch === "{") depth++;
30033
+ else if (ch === "}") depth--;
30034
+ else if (ch === '"' || ch === "'" || ch === "`") {
30035
+ const q = ch;
30036
+ k++;
30037
+ while (k < n && src[k] !== q) {
30038
+ if (src[k] === "\\") k++;
30039
+ k++;
30040
+ }
30041
+ } else if (ch === "\n") line++;
30042
+ if (depth) k++;
30043
+ }
30044
+ parts.push({ text: text2 });
30045
+ parts.push({ expr: src.slice(j + 2, k), line });
30046
+ text2 = "";
30047
+ j = k + 1;
30048
+ continue;
30049
+ }
30050
+ if (src[j] === "\n") line++;
30051
+ text2 += src[j++];
30052
+ }
30053
+ parts.push({ text: text2 });
30054
+ out.push({ t: "tpl", v: parts, line: startLine, nl });
30055
+ nl = false;
30056
+ i = j + 1;
30057
+ continue;
30058
+ }
30059
+ if (c === "/" && prevAllowsRegex()) {
30060
+ let j = i + 1, inClass = false;
30061
+ while (j < n && src[j] !== "\n") {
30062
+ if (src[j] === "\\") {
30063
+ j += 2;
30064
+ continue;
30065
+ }
30066
+ if (src[j] === "[") inClass = true;
30067
+ else if (src[j] === "]") inClass = false;
30068
+ else if (src[j] === "/" && !inClass) break;
30069
+ j++;
30070
+ }
30071
+ j++;
30072
+ while (j < n && /[a-z]/i.test(src[j])) j++;
30073
+ push("re", src.slice(i, j));
30074
+ i = j;
30075
+ continue;
30076
+ }
30077
+ const p = PUNCT5.find((x) => src.startsWith(x, i));
30078
+ if (!p) throw new ParseError2(`an unexpected character "${c}"`, line);
30079
+ push("p", p);
30080
+ i += p.length;
30081
+ }
30082
+ out.push({ t: "eof", v: "", line, nl: true });
30083
+ return out;
30084
+ }
30085
+ function parse3(src) {
30086
+ const toks = tokenize5(src);
30087
+ let pos = 0;
30088
+ const peek = (k = 0) => toks[Math.min(pos + k, toks.length - 1)];
30089
+ const at2 = (v, k = 0) => {
30090
+ const t = peek(k);
30091
+ return (t.t === "p" || t.t === "id") && t.v === v;
30092
+ };
30093
+ const next = () => {
30094
+ if (pos >= toks.length - 1 && toks[pos]?.t === "eof") throw new ParseError2("the file ends in the middle of something", toks[toks.length - 1].line);
30095
+ return toks[pos++];
30096
+ };
30097
+ const fail2 = (what) => {
30098
+ throw new ParseError2(`${what} (found "${typeof peek().v === "string" ? peek().v : "a template"}")`, peek().line);
30099
+ };
30100
+ const eat = (v) => {
30101
+ if (!at2(v)) fail2(`expected "${v}"`);
30102
+ return next();
30103
+ };
30104
+ const opt2 = (v) => at2(v) ? next() : null;
30105
+ const semi = () => {
30106
+ if (opt2(";")) return;
30107
+ if (at2("}") || peek().t === "eof" || peek().nl) return;
30108
+ fail2("expected the end of a statement");
30109
+ };
30110
+ const skipBalanced2 = () => {
30111
+ const open = next().v;
30112
+ const close = { "(": ")", "[": "]", "{": "}", "<": ">" }[open];
30113
+ let depth = 1;
30114
+ while (depth && peek().t !== "eof") {
30115
+ const t = next();
30116
+ if (t.t !== "p") continue;
30117
+ if (t.v === open) depth++;
30118
+ else if (t.v === close) depth--;
30119
+ else if (open === "<" && t.v === ">>") depth -= 2;
30120
+ else if (open === "<" && t.v === ">>>") depth -= 3;
30121
+ else if (open === "<" && t.v === "=>") {
30122
+ }
30123
+ }
30124
+ };
30125
+ const skipType = (stops = [",", ")", "=", ";", "{", "}", "]", "=>"]) => {
30126
+ let guard = 0;
30127
+ const stopSet = new Set(stops);
30128
+ for (; ; ) {
30129
+ if (++guard > 1e4) fail2("a type Thunder cannot follow");
30130
+ const t = peek();
30131
+ if (t.t === "eof") return;
30132
+ if (t.t === "p" && (t.v === "(" || t.v === "[" || t.v === "{" || t.v === "<")) {
30133
+ if (t.v === "{" && stopSet.has("{") && guard > 1) return;
30134
+ skipBalanced2();
30135
+ if (at2("=>") && t.v === "(" && !stopSet.has("=>")) {
30136
+ next();
30137
+ continue;
30138
+ }
30139
+ continue;
30140
+ }
30141
+ if (t.t === "p" && (t.v === "|" || t.v === "&" || t.v === "." || t.v === "?" || t.v === ":" && !stopSet.has(":"))) {
30142
+ if (t.v === "?" && stopSet.has("?")) return;
30143
+ next();
30144
+ continue;
30145
+ }
30146
+ if (t.t === "p" && t.v === "=>") {
30147
+ if (stopSet.has("=>")) return;
30148
+ next();
30149
+ continue;
30150
+ }
30151
+ if (t.t === "id" || t.t === "str" || t.t === "num" || t.t === "tpl") {
30152
+ if (t.t === "id" && guard > 1 && t.nl && !["extends", "keyof", "typeof", "infer", "is", "readonly", "unique"].includes(t.v)) {
30153
+ const prev = toks[pos - 1];
30154
+ if (!(prev.t === "p" && (prev.v === "|" || prev.v === "&" || prev.v === ":" || prev.v === "." || prev.v === "=>" || prev.v === "?"))) return;
30155
+ }
30156
+ next();
30157
+ continue;
30158
+ }
30159
+ if (t.t === "p" && t.v === "-" && peek(1).t === "num") {
30160
+ next();
30161
+ next();
30162
+ continue;
30163
+ }
30164
+ if (stopSet.has(t.v)) return;
30165
+ return;
30166
+ }
30167
+ };
30168
+ const program = () => {
30169
+ const body2 = [];
30170
+ while (peek().t !== "eof") {
30171
+ const s = statement2();
30172
+ if (s) body2.push(s);
30173
+ }
30174
+ return { type: "Program", body: body2 };
30175
+ };
30176
+ const block = () => {
30177
+ const line = eat("{").line;
30178
+ const body2 = [];
30179
+ while (!at2("}")) {
30180
+ if (peek().t === "eof") fail2('expected "}"');
30181
+ const s = statement2();
30182
+ if (s) body2.push(s);
30183
+ }
30184
+ next();
30185
+ return { type: "Block", body: body2, line };
30186
+ };
30187
+ const isTypeDecl = () => at2("type") && peek(1).t === "id" && (at2("=", 2) || at2("<", 2)) || at2("interface") && peek(1).t === "id" || at2("declare") && !peek(1).nl || at2("enum") && peek(1).t === "id" || at2("const") && at2("enum", 1) || at2("abstract") && at2("class", 1) || at2("namespace") && peek(1).t === "id" && at2("{", 2) || at2("module") && peek(1).t === "str";
30188
+ const skipTypeDecl = () => {
30189
+ const line = peek().line;
30190
+ if (at2("abstract")) {
30191
+ next();
30192
+ return classDecl();
30193
+ }
30194
+ if (at2("declare")) {
30195
+ next();
30196
+ }
30197
+ if (at2("const")) next();
30198
+ if (at2("enum")) {
30199
+ next();
30200
+ next();
30201
+ skipBalanced2();
30202
+ return { type: "Empty", line };
30203
+ }
30204
+ if (at2("interface")) {
30205
+ next();
30206
+ next();
30207
+ if (at2("<")) skipBalanced2();
30208
+ while (!at2("{")) next();
30209
+ skipBalanced2();
30210
+ return { type: "Empty", line };
30211
+ }
30212
+ if (at2("namespace") || at2("module")) {
30213
+ next();
30214
+ next();
30215
+ skipBalanced2();
30216
+ return { type: "Empty", line };
30217
+ }
30218
+ if (at2("type")) {
30219
+ next();
30220
+ next();
30221
+ if (at2("<")) skipBalanced2();
30222
+ eat("=");
30223
+ skipType([";"]);
30224
+ semi();
30225
+ return { type: "Empty", line };
30226
+ }
30227
+ while (!at2(";") && !peek().nl && peek().t !== "eof") {
30228
+ if (at2("{") || at2("(")) skipBalanced2();
30229
+ else next();
30230
+ }
30231
+ opt2(";");
30232
+ return { type: "Empty", line };
30233
+ };
30234
+ const decorators = () => {
30235
+ while (at2("@")) {
30236
+ next();
30237
+ next();
30238
+ while (at2(".")) {
30239
+ next();
30240
+ next();
30241
+ }
30242
+ if (at2("(")) skipBalanced2();
30243
+ }
30244
+ };
30245
+ const statement2 = () => {
30246
+ const t = peek();
30247
+ const line = t.line;
30248
+ decorators();
30249
+ if (at2(";")) {
30250
+ next();
30251
+ return null;
30252
+ }
30253
+ if (at2("{")) return block();
30254
+ if (isTypeDecl()) return skipTypeDecl();
30255
+ if (at2("import") && !at2("(", 1) && !at2(".", 1)) return importDecl();
30256
+ if (at2("export")) return exportDecl();
30257
+ if (at2("const") || at2("let") || at2("var") || at2("using") && peek(1).t === "id" && !peek(1).nl) {
30258
+ const d = varDecl();
30259
+ semi();
30260
+ return d;
30261
+ }
30262
+ if (at2("function") || at2("async") && at2("function", 1) && !peek(1).nl) return functionDecl();
30263
+ if (at2("class")) return classDecl();
30264
+ if (at2("return")) {
30265
+ next();
30266
+ const arg = at2(";") || at2("}") || peek().nl || peek().t === "eof" ? null : expression();
30267
+ semi();
30268
+ return { type: "Return", arg, line };
30269
+ }
30270
+ if (at2("throw")) {
30271
+ next();
30272
+ const arg = expression();
30273
+ semi();
30274
+ return { type: "Throw", arg, line };
30275
+ }
30276
+ if (at2("if")) {
30277
+ next();
30278
+ eat("(");
30279
+ const test = expression();
30280
+ eat(")");
30281
+ const cons = statement2();
30282
+ const alt = opt2("else") ? statement2() : null;
30283
+ return { type: "If", test, cons, alt, line };
30284
+ }
30285
+ if (at2("try")) {
30286
+ next();
30287
+ const body2 = block();
30288
+ let param = null, handler = null, finalizer = null;
30289
+ if (opt2("catch")) {
30290
+ if (opt2("(")) {
30291
+ param = pattern2();
30292
+ if (opt2(":")) skipType([")"]);
30293
+ eat(")");
30294
+ }
30295
+ handler = block();
30296
+ }
30297
+ if (opt2("finally")) finalizer = block();
30298
+ return { type: "Try", body: body2, param, handler, finalizer, line };
30299
+ }
30300
+ if (at2("for")) {
30301
+ next();
30302
+ opt2("await");
30303
+ eat("(");
30304
+ let init = null, iter = null, kind = "for";
30305
+ if (at2("const") || at2("let") || at2("var")) {
30306
+ const k = next().v;
30307
+ const id = pattern2();
30308
+ if (opt2(":")) skipType([";", "=", "of", "in"]);
30309
+ if (at2("of") || at2("in")) {
30310
+ kind = next().v;
30311
+ iter = expression();
30312
+ init = { type: "Var", kind: k, decls: [{ id, init: null, line }], line };
30313
+ } else {
30314
+ const decls = [{ id, init: opt2("=") ? assign() : null, line }];
30315
+ while (opt2(",")) {
30316
+ const id2 = pattern2();
30317
+ decls.push({ id: id2, init: opt2("=") ? assign() : null, line });
30318
+ }
30319
+ init = { type: "Var", kind: k, decls, line };
30320
+ }
30321
+ } else if (!at2(";")) {
30322
+ const e = expression(true);
30323
+ if (at2("of") || at2("in")) {
30324
+ kind = next().v;
30325
+ iter = expression();
30326
+ init = { type: "Expr", expr: e, line };
30327
+ } else init = { type: "Expr", expr: e, line };
30328
+ }
30329
+ let test = null, update = null;
30330
+ if (kind === "for") {
30331
+ eat(";");
30332
+ if (!at2(";")) test = expression();
30333
+ eat(";");
30334
+ if (!at2(")")) update = expression();
30335
+ }
30336
+ eat(")");
30337
+ const body2 = statement2();
30338
+ return { type: "Loop", kind, init, iter, test, update, body: body2, line };
30339
+ }
30340
+ if (at2("while")) {
30341
+ next();
30342
+ eat("(");
30343
+ const test = expression();
30344
+ eat(")");
30345
+ const body2 = statement2();
30346
+ return { type: "Loop", kind: "while", test, body: body2, line };
30347
+ }
30348
+ if (at2("do")) {
30349
+ next();
30350
+ const body2 = statement2();
30351
+ eat("while");
30352
+ eat("(");
30353
+ const test = expression();
30354
+ eat(")");
30355
+ opt2(";");
30356
+ return { type: "Loop", kind: "do", test, body: body2, line };
30357
+ }
30358
+ if (at2("switch")) {
30359
+ next();
30360
+ eat("(");
30361
+ const disc = expression();
30362
+ eat(")");
30363
+ eat("{");
30364
+ const cases = [];
30365
+ while (!at2("}")) {
30366
+ let test = null;
30367
+ if (opt2("default")) eat(":");
30368
+ else {
30369
+ eat("case");
30370
+ test = expression();
30371
+ eat(":");
30372
+ }
30373
+ const body2 = [];
30374
+ while (!at2("case") && !at2("default") && !at2("}")) {
30375
+ const s = statement2();
30376
+ if (s) body2.push(s);
30377
+ }
30378
+ cases.push({ test, body: body2 });
30379
+ }
30380
+ next();
30381
+ return { type: "Switch", disc, cases, line };
30382
+ }
30383
+ if (at2("break") || at2("continue")) {
30384
+ next();
30385
+ if (peek().t === "id" && !peek().nl) next();
30386
+ semi();
30387
+ return { type: "Jump", line };
30388
+ }
30389
+ if (t.t === "id" && at2(":", 1) && !["default", "case"].includes(t.v)) {
30390
+ next();
30391
+ next();
30392
+ return statement2();
30393
+ }
30394
+ const expr = expression();
30395
+ semi();
30396
+ return { type: "Expr", expr, line };
30397
+ };
30398
+ const importDecl = () => {
30399
+ const line = next().line;
30400
+ if (at2("type") && !at2(",", 1) && !at2("from", 1)) next();
30401
+ const names = [];
30402
+ if (peek().t === "str") {
30403
+ next();
30404
+ semi();
30405
+ return { type: "Import", from: null, names, line };
30406
+ }
30407
+ if (peek().t === "id" && !at2("{") && !at2("*")) {
30408
+ names.push({ imported: "default", local: next().v });
30409
+ opt2(",");
30410
+ }
30411
+ if (opt2("*")) {
30412
+ eat("as");
30413
+ names.push({ imported: "*", local: next().v });
30414
+ }
30415
+ if (opt2("{")) {
30416
+ while (!at2("}")) {
30417
+ if (at2("type") && peek(1).t === "id" && !at2(",", 1) && !at2("}", 1) && !at2("as", 1)) next();
30418
+ const imported = next().v;
30419
+ const local = opt2("as") ? next().v : imported;
30420
+ names.push({ imported, local });
30421
+ if (!opt2(",")) break;
30422
+ }
30423
+ eat("}");
30424
+ }
30425
+ eat("from");
30426
+ const from = next().v;
30427
+ if (at2("assert") || at2("with")) {
30428
+ next();
30429
+ skipBalanced2();
30430
+ }
30431
+ semi();
30432
+ return { type: "Import", from, names, line };
30433
+ };
30434
+ const exportDecl = () => {
30435
+ const line = next().line;
30436
+ if (at2("type") && (at2("{", 1) || at2("*", 1))) next();
30437
+ if (opt2("default")) {
30438
+ if (at2("function") || at2("async") && at2("function", 1)) {
30439
+ const f = functionDecl(true);
30440
+ return { type: "Export", decl: f, isDefault: true, line };
30441
+ }
30442
+ if (at2("class")) {
30443
+ const c = classDecl(true);
30444
+ return { type: "Export", decl: c, isDefault: true, line };
30445
+ }
30446
+ const expr = assign();
30447
+ semi();
30448
+ return { type: "Export", expr, isDefault: true, line };
30449
+ }
30450
+ if (at2("{") || at2("*")) {
30451
+ const names = [];
30452
+ if (opt2("*")) {
30453
+ if (opt2("as")) names.push({ local: "*", exported: next().v });
30454
+ } else {
30455
+ next();
30456
+ while (!at2("}")) {
30457
+ if (at2("type") && peek(1).t === "id" && !at2(",", 1) && !at2("}", 1)) next();
30458
+ const local = next().v;
30459
+ const exported = opt2("as") ? next().v : local;
30460
+ names.push({ local, exported });
30461
+ if (!opt2(",")) break;
30462
+ }
30463
+ eat("}");
30464
+ }
30465
+ const from = opt2("from") ? next().v : null;
30466
+ semi();
30467
+ return { type: "Export", names, from, line };
30468
+ }
30469
+ if (at2("=")) {
30470
+ next();
30471
+ assign();
30472
+ semi();
30473
+ return { type: "Empty", line };
30474
+ }
30475
+ const decl2 = statement2();
30476
+ return { type: "Export", decl: decl2, line };
30477
+ };
30478
+ const varDecl = () => {
30479
+ const line = peek().line;
30480
+ const kind = next().v;
30481
+ const decls = [];
30482
+ do {
30483
+ const dline = peek().line;
30484
+ const id = pattern2();
30485
+ if (opt2("!")) {
30486
+ }
30487
+ if (opt2(":")) skipType([",", "=", ";", "}"]);
30488
+ const init = opt2("=") ? assign() : null;
30489
+ decls.push({ id, init, line: dline });
30490
+ } while (opt2(","));
30491
+ return { type: "Var", kind, decls, line };
30492
+ };
30493
+ const pattern2 = () => {
30494
+ const line = peek().line;
30495
+ if (at2("{")) {
30496
+ next();
30497
+ const props = [];
30498
+ while (!at2("}")) {
30499
+ if (opt2("...")) {
30500
+ props.push({ rest: pattern2() });
30501
+ opt2(",");
30502
+ continue;
30503
+ }
30504
+ let key;
30505
+ if (at2("[")) {
30506
+ next();
30507
+ key = { computed: expression() };
30508
+ eat("]");
30509
+ } else key = next().v;
30510
+ let value;
30511
+ if (opt2(":")) value = pattern2();
30512
+ else value = { type: "Id", name: typeof key === "string" ? key : "?", line };
30513
+ if (opt2("=")) value = { type: "Default", target: value, value: assign(), line };
30514
+ props.push({ key, value });
30515
+ if (!opt2(",")) break;
30516
+ }
30517
+ eat("}");
30518
+ return { type: "ObjPat", props, line };
30519
+ }
30520
+ if (at2("[")) {
30521
+ next();
30522
+ const elems = [];
30523
+ while (!at2("]")) {
30524
+ if (at2(",")) {
30525
+ next();
30526
+ elems.push(null);
30527
+ continue;
30528
+ }
30529
+ if (opt2("...")) {
30530
+ elems.push({ type: "Rest", arg: pattern2(), line });
30531
+ opt2(",");
30532
+ continue;
30533
+ }
30534
+ let p = pattern2();
30535
+ if (opt2("=")) p = { type: "Default", target: p, value: assign(), line };
30536
+ elems.push(p);
30537
+ if (!opt2(",")) break;
30538
+ }
30539
+ eat("]");
30540
+ return { type: "ArrPat", elems, line };
30541
+ }
30542
+ const t = next();
30543
+ if (t.t !== "id") {
30544
+ pos--;
30545
+ fail2("expected a name");
30546
+ }
30547
+ return { type: "Id", name: t.v, line: t.line };
30548
+ };
30549
+ const params = () => {
30550
+ eat("(");
30551
+ const ps = [];
30552
+ while (!at2(")")) {
30553
+ decorators();
30554
+ while (["public", "private", "protected", "readonly", "override"].includes(peek().v) && peek(1).t === "id") next();
30555
+ if (opt2("...")) {
30556
+ const p2 = pattern2();
30557
+ if (opt2("?")) {
30558
+ }
30559
+ if (opt2(":")) skipType([",", ")", "="]);
30560
+ ps.push({ type: "Rest", arg: p2 });
30561
+ opt2(",");
30562
+ continue;
30563
+ }
30564
+ let p = pattern2();
30565
+ opt2("?");
30566
+ if (opt2(":")) skipType([",", ")", "="]);
30567
+ if (opt2("=")) p = { type: "Default", target: p, value: assign(), line: p.line };
30568
+ ps.push(p);
30569
+ if (!opt2(",")) break;
30570
+ }
30571
+ eat(")");
30572
+ return ps;
30573
+ };
30574
+ const functionBody = () => at2("{") ? block() : null;
30575
+ const functionDecl = (allowAnonymous = false) => {
30576
+ const line = peek().line;
30577
+ const isAsync = !!opt2("async");
30578
+ eat("function");
30579
+ opt2("*");
30580
+ let name = null;
30581
+ if (peek().t === "id" && !at2("(")) name = next().v;
30582
+ else if (!allowAnonymous) fail2("expected a function name");
30583
+ if (at2("<")) skipBalanced2();
30584
+ const ps = params();
30585
+ if (opt2(":")) skipType(["{", ";"]);
30586
+ const body2 = functionBody();
30587
+ if (!body2) {
30588
+ opt2(";");
30589
+ return { type: "Empty", line };
30590
+ }
30591
+ return { type: "Function", name, params: ps, body: body2, isAsync, line };
30592
+ };
30593
+ const classDecl = (allowAnonymous = false) => {
30594
+ const line = eat("class").line;
30595
+ let name = null;
30596
+ if (peek().t === "id" && !at2("extends") && !at2("implements") && !at2("{")) name = next().v;
30597
+ else if (!allowAnonymous) {
30598
+ }
30599
+ if (at2("<")) skipBalanced2();
30600
+ let superClass = null;
30601
+ if (opt2("extends")) {
30602
+ superClass = postfix(primary());
30603
+ if (at2("<")) skipBalanced2();
30604
+ }
30605
+ if (opt2("implements")) {
30606
+ while (!at2("{")) next();
30607
+ }
30608
+ eat("{");
30609
+ const members = [];
30610
+ while (!at2("}")) {
30611
+ if (opt2(";")) continue;
30612
+ decorators();
30613
+ let isStatic = false;
30614
+ const mline = peek().line;
30615
+ while (["public", "private", "protected", "readonly", "static", "abstract", "override", "declare", "accessor"].includes(peek().v) && !at2("(", 1) && !at2("=", 1) && !at2(":", 1) && !at2(";", 1) && !at2("?", 1)) {
30616
+ if (next().v === "static") isStatic = true;
30617
+ }
30618
+ if (at2("static") && at2("{", 1)) {
30619
+ next();
30620
+ block();
30621
+ continue;
30622
+ }
30623
+ const isAsync = at2("async") && !at2("(", 1) && !peek(1).nl ? !!next() : false;
30624
+ opt2("*");
30625
+ let kind = "method";
30626
+ if ((at2("get") || at2("set")) && !at2("(", 1) && !at2("=", 1) && !at2(":", 1)) {
30627
+ kind = next().v;
30628
+ }
30629
+ let key;
30630
+ if (at2("[")) {
30631
+ next();
30632
+ expression();
30633
+ eat("]");
30634
+ key = "[computed]";
30635
+ } else if (at2("#")) {
30636
+ next();
30637
+ key = "#" + next().v;
30638
+ } else key = next().v;
30639
+ opt2("?");
30640
+ opt2("!");
30641
+ if (at2("(") || at2("<")) {
30642
+ if (at2("<")) skipBalanced2();
30643
+ const ps = params();
30644
+ if (opt2(":")) skipType(["{", ";"]);
30645
+ const body2 = functionBody();
30646
+ if (!body2) {
30647
+ opt2(";");
30648
+ continue;
30649
+ }
30650
+ members.push({ kind, key, isStatic, fn: { type: "Arrow", params: ps, body: body2, isAsync, line: mline, isMethod: true, name: key }, line: mline });
30651
+ } else {
30652
+ if (opt2(":")) skipType(["=", ";", "}"]);
30653
+ const value = opt2("=") ? assign() : null;
30654
+ semi();
30655
+ members.push({ kind: "field", key, isStatic, value, line: mline });
30656
+ }
30657
+ }
30658
+ eat("}");
30659
+ return { type: "Class", name, superClass, members, line };
30660
+ };
30661
+ const expression = (noIn = false) => {
30662
+ const line = peek().line;
30663
+ const first = assign(noIn);
30664
+ if (!at2(",")) return first;
30665
+ const list3 = [first];
30666
+ while (opt2(",")) list3.push(assign(noIn));
30667
+ return { type: "Seq", list: list3, line };
30668
+ };
30669
+ const isArrowAhead = () => {
30670
+ let k = pos;
30671
+ if (toks[k].v === "async" && toks[k].t === "id") k++;
30672
+ if (toks[k].t === "p" && toks[k].v === "<") {
30673
+ let d = 0;
30674
+ for (; k < toks.length; k++) {
30675
+ if (toks[k].v === "<") d++;
30676
+ else if (toks[k].v === ">") {
30677
+ d--;
30678
+ if (!d) {
30679
+ k++;
30680
+ break;
30681
+ }
30682
+ } else if (toks[k].t === "eof") return false;
30683
+ }
30684
+ }
30685
+ if (toks[k].t === "id" && toks[k + 1]?.v === "=>") return true;
30686
+ if (!(toks[k].t === "p" && toks[k].v === "(")) return false;
30687
+ let depth = 0;
30688
+ for (; k < toks.length; k++) {
30689
+ const t = toks[k];
30690
+ if (t.t !== "p") continue;
30691
+ if (t.v === "(" || t.v === "[" || t.v === "{") depth++;
30692
+ else if (t.v === ")" || t.v === "]" || t.v === "}") {
30693
+ depth--;
30694
+ if (!depth) break;
30695
+ }
30696
+ if (t.t === "eof") return false;
30697
+ }
30698
+ const after = toks[k + 1];
30699
+ if (!after) return false;
30700
+ if (after.t === "p" && after.v === "=>") return true;
30701
+ if (after.t === "p" && after.v === ":") {
30702
+ let d = 0;
30703
+ for (let j = k + 2; j < toks.length && j < k + 200; j++) {
30704
+ const t = toks[j];
30705
+ if (t.t === "p" && (t.v === "(" || t.v === "[" || t.v === "{" || t.v === "<")) d++;
30706
+ else if (t.t === "p" && (t.v === ")" || t.v === "]" || t.v === "}" || t.v === ">")) {
30707
+ d--;
30708
+ if (d < 0) return false;
30709
+ } else if (t.t === "p" && t.v === "=>" && d === 0) return true;
30710
+ else if (t.t === "p" && (t.v === ";" || t.v === "," || t.v === "=") && d === 0) return false;
30711
+ else if (t.t === "eof") return false;
30712
+ }
30713
+ }
30714
+ return false;
30715
+ };
30716
+ const arrow = () => {
30717
+ const line = peek().line;
30718
+ const isAsync = at2("async") && !at2("=>", 1) ? !!next() : false;
30719
+ if (at2("<")) skipBalanced2();
30720
+ let ps;
30721
+ if (peek().t === "id" && at2("=>", 1)) ps = [{ type: "Id", name: next().v, line }];
30722
+ else {
30723
+ ps = params();
30724
+ if (opt2(":")) skipType(["=>"]);
30725
+ }
30726
+ eat("=>");
30727
+ const body2 = at2("{") ? block() : assign();
30728
+ return { type: "Arrow", params: ps, body: body2, isAsync, line };
30729
+ };
30730
+ const ASSIGN_OPS2 = /* @__PURE__ */ new Set(["=", "+=", "-=", "*=", "/=", "%=", "**=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "&&=", "||=", "??="]);
30731
+ const assign = (noIn = false) => {
30732
+ if ((at2("(") || at2("<") || peek().t === "id" && at2("=>", 1) || at2("async") && (at2("(", 1) || peek(1).t === "id" || at2("<", 1))) && isArrowAhead()) return arrow();
30733
+ if (at2("yield")) {
30734
+ const line2 = next().line;
30735
+ opt2("*");
30736
+ const arg = at2(")") || at2("]") || at2("}") || at2(",") || at2(";") || peek().nl ? null : assign(noIn);
30737
+ return { type: "Await", arg, line: line2 };
30738
+ }
30739
+ const line = peek().line;
30740
+ const left = conditional(noIn);
30741
+ if (peek().t === "p" && ASSIGN_OPS2.has(peek().v)) {
30742
+ const op = next().v;
30743
+ const right = assign(noIn);
30744
+ return { type: "Assign", op, left, right, line };
30745
+ }
30746
+ return left;
30747
+ };
30748
+ const conditional = (noIn) => {
30749
+ const line = peek().line;
30750
+ const test = binary(0, noIn);
30751
+ if (!at2("?")) return test;
30752
+ next();
30753
+ const cons = assign();
30754
+ eat(":");
30755
+ const alt = assign(noIn);
30756
+ return { type: "Cond", test, cons, alt, line };
30757
+ };
30758
+ const PREC3 = {
30759
+ "??": 1,
30760
+ "||": 2,
30761
+ "&&": 3,
30762
+ "|": 4,
30763
+ "^": 5,
30764
+ "&": 6,
30765
+ "==": 7,
30766
+ "!=": 7,
30767
+ "===": 7,
30768
+ "!==": 7,
30769
+ "<": 8,
30770
+ ">": 8,
30771
+ "<=": 8,
30772
+ ">=": 8,
30773
+ instanceof: 8,
30774
+ in: 8,
30775
+ "<<": 9,
30776
+ ">>": 9,
30777
+ ">>>": 9,
30778
+ "+": 10,
30779
+ "-": 10,
30780
+ "*": 11,
30781
+ "/": 11,
30782
+ "%": 11,
30783
+ "**": 12
30784
+ };
30785
+ const binary = (minPrec, noIn) => {
30786
+ let left = unary();
30787
+ for (; ; ) {
30788
+ const t = peek();
30789
+ if (t.t === "id" && (t.v === "as" || t.v === "satisfies") && !t.nl) {
30790
+ next();
30791
+ if (at2("const")) next();
30792
+ else skipType([",", ")", "]", ";", "}", "=", "?", ":", "&&", "||", "??", "=>"]);
30793
+ continue;
30794
+ }
30795
+ const op = t.t === "p" || t.t === "id" && (t.v === "instanceof" || t.v === "in" && !noIn) ? t.v : null;
30796
+ const prec = op != null ? PREC3[op] : void 0;
30797
+ if (prec === void 0 || prec < minPrec) return left;
30798
+ next();
30799
+ const right = binary(op === "**" ? prec : prec + 1, noIn);
30800
+ left = { type: op === "&&" || op === "||" || op === "??" ? "Logic" : "Bin", op, left, right, line: t.line };
30801
+ }
30802
+ };
30803
+ const unary = () => {
30804
+ const t = peek();
30805
+ if (t.t === "p" && ["!", "-", "+", "~"].includes(t.v)) {
30806
+ next();
30807
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
30808
+ }
30809
+ if (t.t === "p" && (t.v === "++" || t.v === "--")) {
30810
+ next();
30811
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
30812
+ }
30813
+ if (t.t === "id" && (t.v === "typeof" || t.v === "void" || t.v === "delete")) {
30814
+ next();
30815
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
30816
+ }
30817
+ if (t.t === "id" && t.v === "await" && !(at2("(", 1) && false)) {
30818
+ const n2 = peek(1);
30819
+ if (!(n2.t === "p" && [")", "]", "}", ",", ";", "=", "."].includes(n2.v))) {
30820
+ next();
30821
+ return { type: "Await", arg: unary(), line: t.line };
30822
+ }
30823
+ }
30824
+ if (t.t === "p" && t.v === "<" && !isArrowAhead()) {
30825
+ skipBalanced2();
30826
+ return unary();
30827
+ }
30828
+ return postfix(primary());
30829
+ };
30830
+ const args = () => {
30831
+ eat("(");
30832
+ const list3 = [];
30833
+ while (!at2(")")) {
30834
+ if (opt2("...")) list3.push({ type: "Spread", arg: assign(), line: peek().line });
30835
+ else list3.push(assign());
30836
+ if (!opt2(",")) break;
30837
+ }
30838
+ eat(")");
30839
+ return list3;
30840
+ };
30841
+ const genericCallAhead = () => {
30842
+ if (!at2("<")) return false;
30843
+ let d = 0, k = pos;
30844
+ for (; k < toks.length && k < pos + 80; k++) {
30845
+ const t = toks[k];
30846
+ if (t.t === "p" && t.v === "<") d++;
30847
+ else if (t.t === "p" && t.v === ">") {
30848
+ d--;
30849
+ if (!d) break;
30850
+ } else if (t.t === "p" && t.v === ">>") {
30851
+ d -= 2;
30852
+ if (d <= 0) break;
30853
+ } else if (t.t === "p" && ![",", ".", "|", "&", "[", "]", "{", "}", ":", "?", "(", ")", "=>", ";"].includes(t.v)) return false;
30854
+ else if (t.t === "eof") return false;
30855
+ }
30856
+ return toks[k + 1]?.t === "p" && (toks[k + 1].v === "(" || toks[k + 1].v === "`");
30857
+ };
30858
+ const postfix = (expr) => {
30859
+ for (; ; ) {
30860
+ const t = peek();
30861
+ if (t.t === "p" && t.v === ".") {
30862
+ next();
30863
+ const name = at2("#") ? (next(), "#" + next().v) : next().v;
30864
+ expr = { type: "Member", object: expr, prop: name, line: t.line };
30865
+ continue;
30866
+ }
30867
+ if (t.t === "p" && t.v === "?.") {
30868
+ next();
30869
+ if (at2("(")) {
30870
+ expr = { type: "Call", callee: expr, args: args(), optional: true, line: t.line };
30871
+ continue;
30872
+ }
30873
+ if (at2("[")) {
30874
+ next();
30875
+ const p = expression();
30876
+ eat("]");
30877
+ expr = { type: "Member", object: expr, computed: p, prop: p.type === "Lit" ? String(p.value) : null, optional: true, line: t.line };
30878
+ continue;
30879
+ }
30880
+ expr = { type: "Member", object: expr, prop: next().v, optional: true, line: t.line };
30881
+ continue;
30882
+ }
30883
+ if (t.t === "p" && t.v === "[" && !t.nl) {
30884
+ next();
30885
+ const p = expression();
30886
+ eat("]");
30887
+ expr = { type: "Member", object: expr, computed: p, prop: p.type === "Lit" ? String(p.value) : null, line: t.line };
30888
+ continue;
30889
+ }
30890
+ if (t.t === "p" && t.v === "(") {
30891
+ if (t.nl && false) break;
30892
+ expr = { type: "Call", callee: expr, args: args(), line: t.line };
30893
+ continue;
30894
+ }
30895
+ if (t.t === "p" && t.v === "<" && genericCallAhead()) {
30896
+ skipBalanced2();
30897
+ continue;
30898
+ }
30899
+ if (t.t === "tpl") {
30900
+ next();
30901
+ expr = { type: "Tagged", tag: expr, tpl: tplNode(t), line: t.line };
30902
+ continue;
30903
+ }
30904
+ if (t.t === "p" && t.v === "!" && !t.nl && !at2("=", 1) && !at2("==", 1)) {
30905
+ next();
30906
+ continue;
30907
+ }
30908
+ if (t.t === "p" && (t.v === "++" || t.v === "--") && !t.nl) {
30909
+ next();
30910
+ expr = { type: "Unary", op: t.v, arg: expr, line: t.line };
30911
+ continue;
30912
+ }
30913
+ return expr;
30914
+ }
30915
+ };
30916
+ const tplNode = (t) => {
30917
+ const parts = t.v.map((p) => {
30918
+ if (p.expr == null) return { text: p.text };
30919
+ let e;
30920
+ try {
30921
+ e = parseExpressionAt(p.expr, p.line);
30922
+ } catch {
30923
+ e = { type: "Unknown", line: p.line };
30924
+ }
30925
+ return { expr: e };
30926
+ });
30927
+ return { type: "Tpl", parts, line: t.line };
30928
+ };
30929
+ const objectLiteral = () => {
30930
+ const line = eat("{").line;
30931
+ const props = [];
30932
+ while (!at2("}")) {
30933
+ const pline = peek().line;
30934
+ if (opt2("...")) {
30935
+ props.push({ spread: assign(), line: pline });
30936
+ if (!opt2(",")) break;
30937
+ continue;
30938
+ }
30939
+ let isAsync = false, kind = "init";
30940
+ if (at2("async") && !at2(",", 1) && !at2(":", 1) && !at2("(", 1) && !at2("}", 1)) {
30941
+ next();
30942
+ isAsync = true;
30943
+ }
30944
+ opt2("*");
30945
+ if ((at2("get") || at2("set")) && !at2(",", 1) && !at2(":", 1) && !at2("(", 1) && !at2("}", 1)) kind = next().v;
30946
+ let key, computed = null;
30947
+ if (at2("[")) {
30948
+ next();
30949
+ computed = assign();
30950
+ eat("]");
30951
+ key = computed.type === "Lit" ? String(computed.value) : null;
30952
+ } else {
30953
+ const kt = next();
30954
+ key = kt.t === "num" ? kt.v : kt.v;
30955
+ }
30956
+ if (at2("(") || at2("<")) {
30957
+ if (at2("<")) skipBalanced2();
30958
+ const ps = params();
30959
+ if (opt2(":")) skipType(["{"]);
30960
+ const body2 = block();
30961
+ props.push({ key, value: { type: "Arrow", params: ps, body: body2, isAsync, line: pline, isMethod: true, name: key }, method: true, kind, line: pline });
30962
+ } else if (opt2(":")) props.push({ key, computed, value: assign(), line: pline });
30963
+ else if (at2("=")) {
30964
+ next();
30965
+ props.push({ key, value: { type: "Id", name: key, line: pline }, shorthand: true, line: pline, dflt: assign() });
30966
+ } else props.push({ key, value: { type: "Id", name: key, line: pline }, shorthand: true, line: pline });
30967
+ if (!opt2(",")) break;
30968
+ }
30969
+ eat("}");
30970
+ return { type: "Obj", props, line };
30971
+ };
30972
+ const primary = () => {
30973
+ const t = peek();
30974
+ const line = t.line;
30975
+ if (t.t === "num") {
30976
+ next();
30977
+ return { type: "Lit", value: Number(t.v.replace(/_/g, "")), raw: t.v, line };
30978
+ }
30979
+ if (t.t === "str") {
30980
+ next();
30981
+ return { type: "Lit", value: t.v, line };
30982
+ }
30983
+ if (t.t === "tpl") {
30984
+ next();
30985
+ return tplNode(t);
30986
+ }
30987
+ if (t.t === "re") {
30988
+ next();
30989
+ return { type: "Lit", value: t.v, regex: true, line };
30990
+ }
30991
+ if (t.t === "p") {
30992
+ if (t.v === "(") {
30993
+ next();
30994
+ const e = expression();
30995
+ eat(")");
30996
+ return { ...e, paren: true };
30997
+ }
30998
+ if (t.v === "[") {
30999
+ next();
31000
+ const elems = [];
31001
+ while (!at2("]")) {
31002
+ if (at2(",")) {
31003
+ next();
31004
+ elems.push(null);
31005
+ continue;
31006
+ }
31007
+ if (opt2("...")) elems.push({ type: "Spread", arg: assign(), line });
31008
+ else elems.push(assign());
31009
+ if (!opt2(",")) break;
31010
+ }
31011
+ eat("]");
31012
+ return { type: "Arr", elems, line };
31013
+ }
31014
+ if (t.v === "{") return objectLiteral();
31015
+ if (t.v === "#") {
31016
+ next();
31017
+ next();
31018
+ return { type: "Id", name: "#private", line };
31019
+ }
31020
+ if (t.v === "@") {
31021
+ decorators();
31022
+ return primary();
31023
+ }
31024
+ fail2("an expression Thunder cannot read");
31025
+ }
31026
+ if (t.t === "id") {
31027
+ if (t.v === "function" || t.v === "async" && at2("function", 1)) {
31028
+ const f = functionDecl(true);
31029
+ return { type: "Arrow", params: f.params, body: f.body, isAsync: f.isAsync, line, name: f.name };
31030
+ }
31031
+ if (t.v === "class") {
31032
+ const c = classDecl(true);
31033
+ return { ...c, type: "ClassExpr" };
31034
+ }
31035
+ if (t.v === "new") {
31036
+ next();
31037
+ if (at2(".")) {
31038
+ next();
31039
+ next();
31040
+ return { type: "Id", name: "new.target", line };
31041
+ }
31042
+ let callee2 = primary();
31043
+ while (at2(".") || at2("[")) {
31044
+ if (opt2(".")) callee2 = { type: "Member", object: callee2, prop: next().v, line };
31045
+ else {
31046
+ next();
31047
+ const p = expression();
31048
+ eat("]");
31049
+ callee2 = { type: "Member", object: callee2, computed: p, line };
31050
+ }
31051
+ }
31052
+ if (at2("<") && genericCallAhead()) skipBalanced2();
31053
+ const a = at2("(") ? args() : [];
31054
+ return { type: "New", callee: callee2, args: a, line };
31055
+ }
31056
+ if (t.v === "this") {
31057
+ next();
31058
+ return { type: "This", line };
31059
+ }
31060
+ if (t.v === "super") {
31061
+ next();
31062
+ return { type: "Id", name: "super", line };
31063
+ }
31064
+ if (t.v === "true" || t.v === "false") {
31065
+ next();
31066
+ return { type: "Lit", value: t.v === "true", line };
31067
+ }
31068
+ if (t.v === "null") {
31069
+ next();
31070
+ return { type: "Lit", value: null, line };
31071
+ }
31072
+ if (t.v === "undefined") {
31073
+ next();
31074
+ return { type: "Lit", value: void 0, line };
31075
+ }
31076
+ if (t.v === "import" && at2("(", 1)) {
31077
+ next();
31078
+ const a = args();
31079
+ return { type: "Call", callee: { type: "Id", name: "import", line }, args: a, line };
31080
+ }
31081
+ if (t.v === "import" && at2(".", 1)) {
31082
+ next();
31083
+ next();
31084
+ next();
31085
+ return { type: "Id", name: "import.meta", line };
31086
+ }
31087
+ next();
31088
+ return { type: "Id", name: t.v, line };
31089
+ }
31090
+ fail2("an expression Thunder cannot read");
31091
+ };
31092
+ return { program, expressionOnly: () => {
31093
+ const e = expression();
31094
+ return e;
31095
+ } };
31096
+ }
31097
+ function parseExpressionAt(src, line) {
31098
+ const p = parse3(src);
31099
+ const e = p.expressionOnly();
31100
+ const shift = (n) => {
31101
+ if (!n || typeof n !== "object") return;
31102
+ if (typeof n.line === "number") n.line += line - 1;
31103
+ for (const v of Object.values(n)) {
31104
+ if (Array.isArray(v)) v.forEach(shift);
31105
+ else if (v && typeof v === "object") shift(v);
31106
+ }
31107
+ };
31108
+ shift(e);
31109
+ return e;
31110
+ }
31111
+ function parseProgram(src) {
31112
+ return parse3(src).program();
31113
+ }
31114
+
31115
+ // src/flow/access.mjs
31116
+ var ACCESS_SCHEMA = "thunder-access-v1";
31117
+ var CODE_FILE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i;
31118
+ var METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "del", "all", "options", "head"]);
31119
+ var OWNER_FIELD = /^(tenant|org|organization|organisation|account|workspace|team|company|owner|user|customer|member|created_?by|author|merchant|client|shop|store|household|family|school|clinic)(_?id|Id|ID|_?ids|Ids)?$/i;
31120
+ var IDENTITY_FN = /^(get|require|current|fetch|load|validate|verify|ensure|read)?(Current)?(User|Session|ServerSession|Auth|Identity|Principal|Viewer|Me|Account|Member|Caller|Token|Claims)(FromRequest|OrThrow|FromToken|FromCookie|FromHeader)?$/;
31121
+ var IDENTITY_FN_EXACT = /* @__PURE__ */ new Set(["auth", "getAuth", "currentUser", "getServerSession", "getSession", "getUser", "requireUser", "requireSession", "verifyToken", "verifySession", "validateRequest", "getKindeServerSession", "useSession"]);
31122
+ var AUTH_MIDDLEWARE = /auth|authenticate|authenticated|requireUser|requireLogin|loggedIn|isLoggedIn|signedIn|protect|ensureUser|verifyToken|verifyJwt|jwt|passport|session|clerk|bearer/i;
31123
+ var ROLE_FN = /^(require|assert|ensure|check|is|has)(Admin|SuperAdmin|Staff|Role|Roles|Permission|Permissions|Scope|Scopes)$/;
31124
+ var GUARDISH = /assert|ensure|check|verify|authori[sz]e|^can[A-Z]|^can$|guard|permit|allow|policy|access|own|belongs|scope|forbid/i;
31125
+ var BENIGN_MIDDLEWARE = /^(json|urlencoded|raw|text|static|cors|helmet|morgan|compression|cookieParser|bodyParser|csrf|csurf|timeout|requestId|express\.json|express\.urlencoded|express\.static)$|validat|schema|zValidator|upload|multer|ratelimit|rateLimit|limiter|logger|logging|cache|metrics|trace|tracing/i;
31126
+ var MAYBE_GUARD_MIDDLEWARE = /authori[sz]|permi|polic|access|owner|ownership|guard|can[A-Z]|tenant|scope/i;
31127
+ var CLONE = "structuredClone";
31128
+ var BUF = "Buffer";
31129
+ var PASS_THROUGH = /* @__PURE__ */ new Set(["String", "Number", "Boolean", "BigInt", "parseInt", "parseFloat", "decodeURIComponent", "encodeURIComponent", "Array", "Object", CLONE]);
31130
+ var PASS_THROUGH_MEMBERS = /* @__PURE__ */ new Set(["JSON.parse", "JSON.stringify", "Object.assign", "Object.keys", "Object.values", "Object.entries", "Object.fromEntries", "Array.from", "Array.isArray", "Promise.all", "Promise.allSettled", "Promise.resolve", "Number.parseInt", "Number.parseFloat", "Math.max", "Math.min"]);
31131
+ var PRISMA_READ = /* @__PURE__ */ new Set(["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "count", "aggregate", "groupBy"]);
31132
+ var PRISMA_WRITE = /* @__PURE__ */ new Set(["update", "updateMany", "delete", "deleteMany", "upsert"]);
31133
+ var PRISMA_ALL = /* @__PURE__ */ new Set([...PRISMA_READ, ...PRISMA_WRITE, "create", "createMany"]);
31134
+ var MONGOOSE_OPS = /* @__PURE__ */ new Map([["findById", "read"], ["findOne", "read"], ["find", "read"], ["findByIdAndUpdate", "write"], ["findOneAndUpdate", "write"], ["findByIdAndDelete", "write"], ["findOneAndDelete", "write"], ["findByIdAndRemove", "write"], ["deleteOne", "write"], ["updateOne", "write"], ["deleteMany", "write"], ["updateMany", "write"], ["countDocuments", "read"]]);
31135
+ var DB_NAMES = /^(prisma|db|database|tx|trx|knex|pool|pg|sql|conn|connection|orm|drizzle|client|dbClient|prismaClient)$/;
31136
+ var DB_FACTORIES = /^(PrismaClient|drizzle|knex|Knex|Pool|Client|postgres|createPool|createConnection|createClient|neon|Kysely)$/;
31137
+ var NEXT_EXITS = /* @__PURE__ */ new Set(["notFound", "redirect", "permanentRedirect", "forbidden", "unauthorized"]);
31138
+ var MAX_DEPTH = 5;
31139
+ var LOOKUP_NAME = /^(get|find|load|fetch|read|query|select|lookup|retrieve|search|list|show)([A-Z_]|$)|By[A-Z]|ById$|OrFail$|OrThrow$/;
31140
+ var LOOKUP_OWNER = /repo|repository|store|service|dao|model|db|database|client|api|prisma|orm|collection|table|manager|provider/i;
31141
+ var NOT_DATA_PACKAGE = /^(node:|path$|fs$|fs\/promises$|child_process$|os$|url$|crypto$|util$|zlib$|stream$|events$|buffer$|querystring$|http$|https$|net$|readline$|process$)/;
31142
+ var MAX_WORK = 4e4;
31143
+ var DATA = ["input", "ident", "recs", "unknown", "recFields"];
31144
+ var uniq = (a, b) => {
31145
+ if (!a?.length) return b;
31146
+ if (!b?.length) return a;
31147
+ const out = [...a];
31148
+ for (const x of b) if (!out.includes(x)) out.push(x);
31149
+ return out;
31150
+ };
31151
+ function join2(a, b) {
31152
+ if (!a) return b ?? {};
31153
+ if (!b) return a;
31154
+ const out = { ...a };
31155
+ for (const k of DATA) {
31156
+ const u = uniq(a[k], b[k]);
31157
+ if (u?.length) out[k] = u;
31158
+ }
31159
+ for (const [k, v] of Object.entries(b)) {
31160
+ if (DATA.includes(k)) continue;
31161
+ if (k === "obj" && a.obj) {
31162
+ const m = new Map(a.obj);
31163
+ for (const [pk, pv] of b.obj) m.set(pk, join2(m.get(pk), pv));
31164
+ out.obj = m;
31165
+ continue;
31166
+ }
31167
+ if (k === "lit") {
31168
+ if (a.lit !== b.lit) delete out.lit;
31169
+ continue;
31170
+ }
31171
+ if (out[k] === void 0) out[k] = v;
31172
+ }
31173
+ if ("lit" in a && !("lit" in b)) delete out.lit;
31174
+ return out;
31175
+ }
31176
+ var joinAll = (vals) => vals.reduce((acc, v) => join2(acc, v), null) ?? {};
31177
+ var dataOf = (v) => {
31178
+ const out = {};
31179
+ for (const k of DATA) if (v?.[k]?.length) out[k] = v[k];
31180
+ return out;
31181
+ };
31182
+ var hasData = (v) => DATA.some((k) => v?.[k]?.length);
31183
+ var Scope = class {
31184
+ constructor(parent = null, vars = /* @__PURE__ */ new Map()) {
31185
+ this.parent = parent;
31186
+ this.vars = vars;
31187
+ }
31188
+ find(name) {
31189
+ for (let s = this; s; s = s.parent) if (s.vars.has(name)) return s;
31190
+ return null;
31191
+ }
31192
+ get(name) {
31193
+ const s = this.find(name);
31194
+ return s ? s.vars.get(name) : void 0;
31195
+ }
31196
+ set(name, v) {
31197
+ const s = this.find(name) ?? this;
31198
+ s.vars.set(name, v);
31199
+ }
31200
+ declare(name, v) {
31201
+ this.vars.set(name, v);
31202
+ }
31203
+ };
31204
+ function cloneScope(s, memo = /* @__PURE__ */ new Map()) {
31205
+ if (!s || s.module) return s;
31206
+ if (memo.has(s)) return memo.get(s);
31207
+ const c = new Scope(cloneScope(s.parent, memo), new Map(s.vars));
31208
+ memo.set(s, c);
31209
+ return c;
31210
+ }
31211
+ function mergeScope(a, b) {
31212
+ for (let x = a, y = b; x && y && !x.module; x = x.parent, y = y.parent) {
31213
+ for (const [k, v] of y.vars) x.vars.set(k, join2(x.vars.get(k), v));
31214
+ }
31215
+ return a;
31216
+ }
31217
+ function newState(scope, frame) {
31218
+ return { scope, frame, guards: /* @__PURE__ */ new Map(), role: null, identity: null, unresolved: [], exited: null, calledNext: false, req: /* @__PURE__ */ new Map() };
31219
+ }
31220
+ function cloneState(s) {
31221
+ return { ...s, scope: cloneScope(s.scope), guards: new Map(s.guards), unresolved: [...s.unresolved], req: new Map(s.req) };
31222
+ }
31223
+ function mergeStates(a, b) {
31224
+ if (a.exited && b.exited) return a;
31225
+ if (a.exited) return b;
31226
+ if (b.exited) return a;
31227
+ const out = { ...a, scope: mergeScope(a.scope, b.scope) };
31228
+ out.guards = new Map([...a.guards].filter(([k]) => b.guards.has(k)));
31229
+ out.role = a.role && b.role ? a.role : null;
31230
+ out.identity = a.identity ?? b.identity;
31231
+ out.unresolved = uniq(a.unresolved, b.unresolved) ?? [];
31232
+ out.calledNext = a.calledNext || b.calledNext;
31233
+ out.req = new Map(a.req);
31234
+ for (const [k, v] of b.req) out.req.set(k, join2(out.req.get(k), v));
31235
+ return out;
31236
+ }
31237
+ var norm = (p) => {
31238
+ const parts = [];
31239
+ for (const seg of p.replace(/\\/g, "/").split("/")) {
31240
+ if (seg === "..") parts.pop();
31241
+ else if (seg !== "." && seg !== "") parts.push(seg);
31242
+ }
31243
+ return (p.startsWith("/") ? "/" : "") + parts.join("/");
31244
+ };
31245
+ var dirOf2 = (p) => {
31246
+ const q = p.replace(/\\/g, "/");
31247
+ return q.includes("/") ? q.replace(/\/[^/]*$/, "") || "/" : ".";
31248
+ };
31249
+ var Project = class {
31250
+ constructor(files) {
31251
+ this.files = /* @__PURE__ */ new Map();
31252
+ this.failures = [];
31253
+ for (const f of files) {
31254
+ if (!CODE_FILE.test(f.path) || /\.d\.[mc]?ts$/.test(f.path)) continue;
31255
+ const path = f.path.replace(/\\/g, "/");
31256
+ try {
31257
+ const ast = parseProgram(f.source);
31258
+ this.files.set(path, { path, ast, source: f.source, scope: null, exports: /* @__PURE__ */ new Map(), imports: /* @__PURE__ */ new Map(), bindings: /* @__PURE__ */ new Map() });
31259
+ } catch (e) {
31260
+ this.failures.push({ file: path, line: e.line ?? null, why: `Thunder could not read this file (${e.message}${e.line ? `, line ${e.line}` : ""})` });
31261
+ }
31262
+ }
31263
+ for (const m of this.files.values()) this.index(m);
31264
+ }
31265
+ index(m) {
31266
+ const scope = new Scope(null);
31267
+ scope.module = m;
31268
+ m.scope = scope;
31269
+ const bind2 = (name, b) => {
31270
+ m.bindings.set(name, b);
31271
+ };
31272
+ const visit = (s, exported, isDefault) => {
31273
+ if (!s) return;
31274
+ if (s.type === "Import") {
31275
+ for (const n of s.names) m.imports.set(n.local, { from: s.from, imported: n.imported });
31276
+ return;
31277
+ }
31278
+ if (s.type === "Export") {
31279
+ if (s.decl) {
31280
+ visit(s.decl, true, s.isDefault);
31281
+ return;
31282
+ }
31283
+ if (s.expr) {
31284
+ bind2("default", { kind: "expr", node: s.expr });
31285
+ m.exports.set("default", "default");
31286
+ return;
31287
+ }
31288
+ for (const n of s.names ?? []) {
31289
+ if (s.from) m.exports.set(n.exported, { reexport: s.from, name: n.local });
31290
+ else m.exports.set(n.exported, n.local);
31291
+ }
31292
+ return;
31293
+ }
31294
+ if (s.type === "Function") {
31295
+ const name = s.name ?? "default";
31296
+ bind2(name, { kind: "fn", node: s });
31297
+ if (exported) m.exports.set(isDefault ? "default" : name, name);
31298
+ return;
31299
+ }
31300
+ if (s.type === "Class") {
31301
+ const name = s.name ?? "default";
31302
+ bind2(name, { kind: "class", node: s });
31303
+ if (exported) m.exports.set(isDefault ? "default" : name, name);
31304
+ return;
31305
+ }
31306
+ if (s.type === "Var") {
31307
+ for (const d of s.decls) {
31308
+ if (d.id.type === "Id") {
31309
+ bind2(d.id.name, { kind: "var", node: d.init, line: d.line });
31310
+ if (exported) m.exports.set(d.id.name, d.id.name);
31311
+ } else for (const name of patternNames(d.id)) {
31312
+ bind2(name, { kind: "destructured", node: d.init, pattern: d.id, name });
31313
+ if (exported) m.exports.set(name, name);
31314
+ }
31315
+ }
31316
+ }
31317
+ };
31318
+ for (const s of m.ast.body) visit(s, false, false);
31319
+ }
31320
+ resolveModule(fromFile, spec) {
31321
+ if (!spec || !(spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("@/") || spec.startsWith("~/"))) return null;
31322
+ let base2;
31323
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
31324
+ const rest2 = spec.slice(2);
31325
+ for (const root of ["src/", "", "app/"]) {
31326
+ const hit = this.resolveModule("/x", `/${root}${rest2}`.replace(/^\//, "./"));
31327
+ if (hit) return hit;
31328
+ }
31329
+ for (const p of this.files.keys()) if (p.endsWith(`/${rest2}.ts`) || p.endsWith(`/${rest2}.tsx`) || p.endsWith(`/${rest2}/index.ts`)) return p;
31330
+ return null;
31331
+ }
31332
+ base2 = norm(`${dirOf2(fromFile)}/${spec}`);
31333
+ const stem = base2.replace(/\.(js|mjs|cjs|jsx)$/, "");
31334
+ for (const cand of [base2, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${stem}.js`, `${stem}.mjs`, `${stem}.jsx`, `${stem}/index.ts`, `${stem}/index.tsx`, `${stem}/index.js`]) {
31335
+ if (this.files.has(cand)) return cand;
31336
+ }
31337
+ return null;
31338
+ }
31339
+ };
31340
+ function patternNames(p) {
31341
+ if (!p) return [];
31342
+ if (p.type === "Id") return [p.name];
31343
+ if (p.type === "Default") return patternNames(p.target);
31344
+ if (p.type === "Rest") return patternNames(p.arg);
31345
+ if (p.type === "ObjPat") return p.props.flatMap((x) => x.rest ? patternNames(x.rest) : patternNames(x.value));
31346
+ if (p.type === "ArrPat") return p.elems.flatMap((x) => patternNames(x));
31347
+ return [];
31348
+ }
31349
+ function guardRec(st, rec, ev) {
31350
+ if (!st.guards.has(rec.id)) st.guards.set(rec.id, ev);
31351
+ if (rec.keyed?.value && !st.guards.has(`key:${rec.keyed.value}`)) st.guards.set(`key:${rec.keyed.value}`, ev);
31352
+ }
31353
+ var Analyzer = class {
31354
+ constructor(project) {
31355
+ this.p = project;
31356
+ this.work = 0;
31357
+ this.recCount = 0;
31358
+ this.moduleCache = /* @__PURE__ */ new Map();
31359
+ }
31360
+ // A module-level name, resolved through imports. Returns a value.
31361
+ moduleValue(file, name, line, seen = /* @__PURE__ */ new Set()) {
31362
+ const key = `${file}::${name}`;
31363
+ if (this.moduleCache.has(key)) return this.moduleCache.get(key);
31364
+ if (seen.has(key)) return {};
31365
+ seen.add(key);
31366
+ const m = this.p.files.get(file);
31367
+ let v;
31368
+ const b = m.bindings.get(name);
31369
+ if (b) v = this.bindingValue(m, name, b, seen);
31370
+ else if (m.imports.has(name)) {
31371
+ const imp = m.imports.get(name);
31372
+ const target = this.p.resolveModule(file, imp.from);
31373
+ if (target) {
31374
+ if (imp.imported === "*") v = { ns: target };
31375
+ else v = this.exportValue(target, imp.imported, seen) ?? { opaque: { why: `${name} is not exported by ${target}`, file, line } };
31376
+ } else {
31377
+ v = { opaque: { why: `${name} comes from ${imp.from}, outside these files`, file, line }, pkg: imp.from, pkgName: imp.imported === "default" ? name : imp.imported };
31378
+ if (/^@prisma\/client$|^drizzle-orm|^knex$|^pg$|^postgres$|^mysql2?|^@neondatabase|^kysely$/.test(imp.from) && DB_NAMES.test(name)) v.isDb = { label: name };
31379
+ }
31380
+ }
31381
+ this.moduleCache.set(key, v);
31382
+ return v;
31383
+ }
31384
+ exportValue(file, name, seen = /* @__PURE__ */ new Set()) {
31385
+ const m = this.p.files.get(file);
31386
+ if (!m) return null;
31387
+ const e = m.exports.get(name);
31388
+ if (e == null) {
31389
+ for (const [, x] of m.exports) if (x?.reexport && x.name === "*") {
31390
+ const t = this.p.resolveModule(file, x.reexport);
31391
+ const v = t && this.exportValue(t, name, seen);
31392
+ if (v) return v;
31393
+ }
31394
+ return null;
31395
+ }
31396
+ if (typeof e === "object" && e.reexport) {
31397
+ const t = this.p.resolveModule(file, e.reexport);
31398
+ return t ? this.exportValue(t, e.name, seen) : { opaque: { why: `${name} comes from ${e.reexport}, outside these files`, file } };
31399
+ }
31400
+ return this.moduleValue(file, e, null, seen);
31401
+ }
31402
+ bindingValue(m, name, b, seen) {
31403
+ if (b.kind === "fn") return { fn: { node: b.node, scope: m.scope, file: m.path, name } };
31404
+ if (b.kind === "class") return { cls: { node: b.node, scope: m.scope, file: m.path, name } };
31405
+ if (b.kind === "expr" || b.kind === "var" || b.kind === "destructured") {
31406
+ if (!b.node) return {};
31407
+ const st = newState(m.scope, { returns: [] });
31408
+ const v = this.expr(b.node, st, { file: m.path, depth: 0, route: null, module: true });
31409
+ if (b.kind === "destructured") {
31410
+ const sc = new Scope(null);
31411
+ this.bindPattern(b.pattern, v, sc, st, { file: m.path });
31412
+ return sc.get(b.name) ?? {};
31413
+ }
31414
+ const init = b.node.type === "Logic" ? b.node.right : b.node.type === "Await" ? b.node.arg : b.node;
31415
+ const initName = init.type === "Call" || init.type === "New" ? init.callee.type === "Id" ? init.callee.name : init.callee.prop : null;
31416
+ if (v.dbFactory || initName && DB_FACTORIES.test(initName)) return { isDb: { label: name } };
31417
+ if (b.kind === "var" && DB_NAMES.test(name) && !v.isDb && !hasData(v) && !v.fn && !v.obj && !v.instance) return { isDb: { label: name } };
31418
+ return v;
31419
+ }
31420
+ return {};
31421
+ }
31422
+ tick(ctx, line) {
31423
+ if (++this.work > MAX_WORK) throw Object.assign(new Error("limit"), { limit: true, file: ctx.file, line });
31424
+ }
31425
+ // ── Statements ──
31426
+ block(stmts, st, ctx) {
31427
+ for (const s of stmts) {
31428
+ if (st.exited) break;
31429
+ this.stmt(s, st, ctx);
31430
+ }
31431
+ }
31432
+ stmt(s, st, ctx) {
31433
+ if (!s) return;
31434
+ this.tick(ctx, s.line);
31435
+ switch (s.type) {
31436
+ case "Block": {
31437
+ st.scope = new Scope(st.scope);
31438
+ this.block(s.body, st, ctx);
31439
+ st.scope = st.scope.parent ?? st.scope;
31440
+ return;
31441
+ }
31442
+ case "Var":
31443
+ for (const d of s.decls) {
31444
+ const v = d.init ? this.expr(d.init, st, ctx) : {};
31445
+ this.bindPattern(d.id, v, st.scope, st, ctx, true);
31446
+ }
31447
+ return;
31448
+ case "Function":
31449
+ st.scope.declare(s.name, { fn: { node: s, scope: st.scope, file: ctx.file, name: s.name } });
31450
+ return;
31451
+ case "Class":
31452
+ st.scope.declare(s.name, { cls: { node: s, scope: st.scope, file: ctx.file, name: s.name } });
31453
+ return;
31454
+ case "Expr": {
31455
+ const v = this.expr(s.expr, st, ctx);
31456
+ if (v.exits) st.exited = "throw";
31457
+ return;
31458
+ }
31459
+ case "Return": {
31460
+ const v = s.arg ? this.expr(s.arg, st, ctx) : {};
31461
+ if (ctx.returnsSend && s.arg && !v.response && !v.isRes) this.sink("response", v, st, ctx, s.line, "gives it back as the response");
31462
+ st.frame.returns.push({ val: v, state: cloneState(st) });
31463
+ st.exited = "return";
31464
+ return;
31465
+ }
31466
+ case "Throw":
31467
+ if (s.arg) this.expr(s.arg, st, ctx);
31468
+ st.exited = "throw";
31469
+ return;
31470
+ case "If":
31471
+ return this.ifStmt(s, st, ctx);
31472
+ case "Try": {
31473
+ const before = cloneState(st);
31474
+ this.stmt(s.body, st, ctx);
31475
+ let after = st;
31476
+ if (s.handler) {
31477
+ const c = cloneState(before);
31478
+ if (s.param) this.bindPattern(s.param, {}, c.scope, c, ctx, true);
31479
+ this.stmt(s.handler, c, ctx);
31480
+ after = mergeStates(st, c);
31481
+ }
31482
+ Object.assign(st, after);
31483
+ if (s.finalizer) {
31484
+ const wasExited = st.exited;
31485
+ st.exited = null;
31486
+ this.stmt(s.finalizer, st, ctx);
31487
+ st.exited = st.exited ?? wasExited;
31488
+ }
31489
+ return;
31490
+ }
31491
+ case "Loop": {
31492
+ if (s.init) this.stmt(s.init, st, ctx);
31493
+ if (s.iter) {
31494
+ const it = this.expr(s.iter, st, ctx);
31495
+ if (s.init?.type === "Var") for (const d of s.init.decls) this.bindPattern(d.id, this.element(it), st.scope, st, ctx, true);
31496
+ }
31497
+ if (s.test) this.expr(s.test, st, ctx);
31498
+ const body2 = cloneState(st);
31499
+ this.stmt(s.body, body2, ctx);
31500
+ if (body2.exited) body2.exited = null;
31501
+ Object.assign(st, mergeStates(st, body2));
31502
+ return;
31503
+ }
31504
+ case "Switch": {
31505
+ this.expr(s.disc, st, ctx);
31506
+ let merged = null;
31507
+ let hasDefault = false;
31508
+ for (const c of s.cases) {
31509
+ if (!c.test) hasDefault = true;
31510
+ else this.expr(c.test, st, ctx);
31511
+ const cs = cloneState(st);
31512
+ this.block(c.body, cs, ctx);
31513
+ if (cs.exited === "return" || cs.exited === "throw") {
31514
+ merged = merged ?? null;
31515
+ if (!merged) merged = cs;
31516
+ else merged = mergeStates(merged, cs);
31517
+ continue;
31518
+ }
31519
+ cs.exited = null;
31520
+ merged = merged ? mergeStates(merged, cs) : cs;
31521
+ }
31522
+ if (!hasDefault) merged = merged ? mergeStates(merged, cloneState(st)) : st;
31523
+ Object.assign(st, merged ?? st);
31524
+ return;
31525
+ }
31526
+ case "Export":
31527
+ if (s.decl) this.stmt(s.decl, st, ctx);
31528
+ return;
31529
+ default:
31530
+ return;
31531
+ }
31532
+ }
31533
+ ifStmt(s, st, ctx) {
31534
+ const facts = this.testFacts(s.test, st, ctx);
31535
+ const cons = cloneState(st);
31536
+ const alt = cloneState(st);
31537
+ this.applyFacts(cons, facts.whenTrue);
31538
+ this.applyFacts(alt, facts.whenFalse);
31539
+ this.stmt(s.cons, cons, ctx);
31540
+ if (s.alt) this.stmt(s.alt, alt, ctx);
31541
+ Object.assign(st, mergeStates(cons, alt));
31542
+ if (cons.exited && alt.exited) st.exited = cons.exited === "return" || alt.exited === "return" ? "return" : "throw";
31543
+ }
31544
+ applyFacts(st, facts) {
31545
+ for (const f of facts) {
31546
+ if (f.kind === "guard") for (const r of f.recs) guardRec(st, r, f.ev);
31547
+ if (f.kind === "role" && !st.role) st.role = f.ev;
31548
+ if (f.kind === "unresolved") st.unresolved = uniq(st.unresolved, [f.ev]);
31549
+ }
31550
+ }
31551
+ /**
31552
+ * What a condition establishes: facts that hold when it is true, and when it is false. A comparison of a record's
31553
+ * owner field with the caller (invoice.tenantId !== user.tenantId) guards the record on the side where they match.
31554
+ */
31555
+ testFacts(t, st, ctx) {
31556
+ const none = { whenTrue: [], whenFalse: [] };
31557
+ if (!t) return none;
31558
+ if (t.paren) return this.testFacts({ ...t, paren: false }, st, ctx);
31559
+ if (t.type === "Unary" && t.op === "!") {
31560
+ const f = this.testFacts(t.arg, st, ctx);
31561
+ const v = this.expr(t.arg, cloneState(st), ctx);
31562
+ return { whenTrue: f.whenFalse, whenFalse: [...f.whenTrue, ...this.foundFacts(v, t.line)] };
31563
+ }
31564
+ if (t.type === "Logic" && t.op === "||") {
31565
+ const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
31566
+ return { whenTrue: [...a.whenTrue.filter((x) => x.kind === "unresolved"), ...b.whenTrue.filter((x) => x.kind === "unresolved")], whenFalse: [...a.whenFalse, ...b.whenFalse] };
31567
+ }
31568
+ if (t.type === "Logic" && t.op === "&&") {
31569
+ const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
31570
+ return { whenTrue: [...a.whenTrue, ...b.whenTrue], whenFalse: [...a.whenFalse.filter((x) => x.kind === "unresolved"), ...b.whenFalse.filter((x) => x.kind === "unresolved")] };
31571
+ }
31572
+ if (t.type === "Bin" && ["===", "==", "!==", "!="].includes(t.op)) {
31573
+ const scratch = cloneState(st);
31574
+ const l = this.expr(t.left, scratch, ctx), r = this.expr(t.right, scratch, ctx);
31575
+ const eq3 = t.op === "===" || t.op === "==";
31576
+ const g = this.ownerComparison(l, r, t.line, ctx) ?? this.ownerComparison(r, l, t.line, ctx);
31577
+ if (g) return eq3 ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] };
31578
+ const role = this.roleComparison(l, r, t.line, ctx) ?? this.roleComparison(r, l, t.line, ctx);
31579
+ if (role) return eq3 ? { whenTrue: [role], whenFalse: [] } : { whenTrue: [], whenFalse: [role] };
31580
+ const isNull = (v) => "lit" in v && (v.lit === null || v.lit === void 0);
31581
+ const recSide = isNull(r) ? l : isNull(l) ? r : null;
31582
+ if (recSide?.recs?.length) {
31583
+ const links = this.foundFacts(recSide, t.line);
31584
+ return eq3 ? { whenTrue: [], whenFalse: links } : { whenTrue: links, whenFalse: [] };
31585
+ }
31586
+ return none;
31587
+ }
31588
+ if (t.type === "Call") {
31589
+ const scratch = cloneState(st);
31590
+ const v = this.expr(t, scratch, ctx);
31591
+ if (v.predicate) return v.predicate;
31592
+ for (const u of scratch.unresolved) if (!st.unresolved.includes(u)) return { whenTrue: [{ kind: "unresolved", ev: u }], whenFalse: [{ kind: "unresolved", ev: u }] };
31593
+ return none;
31594
+ }
31595
+ if (t.type === "Member" || t.type === "Id") {
31596
+ const v = this.expr(t, cloneState(st), ctx);
31597
+ if (v.ident?.some((e) => /^(is)?(admin|superAdmin|staff|isAdmin|isSuperuser|superuser)$/i.test(e.field ?? ""))) return { whenTrue: [{ kind: "role", ev: { says: `only when ${v.ident[0].says} is true`, file: ctx.file, line: t.line } }], whenFalse: [] };
31598
+ if (v.predicate) return v.predicate;
31599
+ const links = this.foundFacts(v, t.line);
31600
+ if (links.length) return { whenTrue: links, whenFalse: [] };
31601
+ }
31602
+ return none;
31603
+ }
31604
+ /**
31605
+ * When a record turns out to exist: a lookup limited to the caller vouches for the records it was keyed by (links),
31606
+ * and for its own request key (a later update by the same id is then the caller's record too).
31607
+ */
31608
+ foundFacts(v, line) {
31609
+ const out = [];
31610
+ for (const rec of v.recs ?? []) {
31611
+ if (!rec.scoped) continue;
31612
+ const ev = { says: `stops unless ${rec.model ?? "the record"} is found for the caller (${rec.scoped.says})`, file: rec.file, line };
31613
+ if (rec.links?.length) out.push({ kind: "guard", recs: rec.links, ev });
31614
+ if (rec.keyed?.value) out.push({ kind: "guard", recs: [rec], ev });
31615
+ }
31616
+ return out;
31617
+ }
31618
+ ownerComparison(recSide, idSide, line, ctx) {
31619
+ const fields = (recSide.recFields ?? []).filter((f) => OWNER_FIELD.test(f.field) || f.field === "id" && false);
31620
+ if (!fields.length || !idSide.ident?.length) return null;
31621
+ if (idSide.input?.length) return null;
31622
+ const id = idSide.ident[0];
31623
+ return { kind: "guard", recs: fields.map((f) => f.rec), ev: { says: `compares ${fields[0].says} with ${id.says}`, file: ctx.file, line } };
31624
+ }
31625
+ roleComparison(a, b, line, ctx) {
31626
+ if (!a.ident?.some((e) => /^(role|roles|type|kind|permission|permissions|scope|isAdmin|accessLevel|level)$/i.test(e.field ?? ""))) return null;
31627
+ if (!("lit" in b) || typeof b.lit !== "string" || !/admin|staff|super|owner|support|internal|root/i.test(b.lit)) return null;
31628
+ return { kind: "role", ev: { says: `only when ${a.ident[0].says} is "${b.lit}"`, file: ctx.file, line } };
31629
+ }
31630
+ // ── Patterns ──
31631
+ bindPattern(p, v, scope, st, ctx, declare = false) {
31632
+ if (!p) return;
31633
+ const set = (name, val) => declare ? scope.declare(name, val) : scope.set(name, val);
31634
+ if (p.type === "Id") {
31635
+ set(p.name, v ?? {});
31636
+ return;
31637
+ }
31638
+ if (p.type === "Default") {
31639
+ const d = this.expr(p.value, st, ctx);
31640
+ this.bindPattern(p.target, join2(v, d), scope, st, ctx, declare);
31641
+ return;
31642
+ }
31643
+ if (p.type === "Rest") {
31644
+ this.bindPattern(p.arg, v, scope, st, ctx, declare);
31645
+ return;
31646
+ }
31647
+ if (p.type === "ObjPat") {
31648
+ for (const prop of p.props) {
31649
+ if (prop.rest) {
31650
+ this.bindPattern(prop.rest, v, scope, st, ctx, declare);
31651
+ continue;
31652
+ }
31653
+ const key = typeof prop.key === "string" ? prop.key : null;
31654
+ const mv = key ? this.member(v, key, st, ctx, p.line) : dataOf(v);
31655
+ this.bindPattern(prop.value, mv, scope, st, ctx, declare);
31656
+ }
31657
+ return;
31658
+ }
31659
+ if (p.type === "ArrPat") {
31660
+ p.elems.forEach((e, i) => {
31661
+ if (e) this.bindPattern(e, v?.arr?.[i] ?? this.element(v), scope, st, ctx, declare);
31662
+ });
31663
+ }
31664
+ }
31665
+ element(v) {
31666
+ if (!v) return {};
31667
+ const d = dataOf(v);
31668
+ if (v.arr) return join2(d, joinAll(v.arr));
31669
+ return d;
31670
+ }
31671
+ // ── Expressions ──
31672
+ expr(e, st, ctx) {
31673
+ if (!e) return {};
31674
+ this.tick(ctx, e.line);
31675
+ switch (e.type) {
31676
+ case "Lit":
31677
+ return { lit: e.value };
31678
+ case "Tpl": {
31679
+ const parts = e.parts.map((p) => p.expr ? this.expr(p.expr, st, ctx) : null);
31680
+ return { ...joinAll(parts.filter(Boolean).map(dataOf)), tpl: { parts: e.parts.map((p, i) => p.expr ? { val: parts[i] } : { text: p.text }) } };
31681
+ }
31682
+ case "Id":
31683
+ return this.lookup(e.name, st, ctx, e.line);
31684
+ case "This":
31685
+ return ctx.thisVal ?? {};
31686
+ case "Member": {
31687
+ const o = this.expr(e.object, st, ctx);
31688
+ if (e.computed && e.prop == null) {
31689
+ const k = this.expr(e.computed, st, ctx);
31690
+ if (typeof k.lit === "string" || typeof k.lit === "number") return this.member(o, String(k.lit), st, ctx, e.line);
31691
+ return join2(this.element(o), dataOf(k).input ? {} : {});
31692
+ }
31693
+ return this.member(o, e.prop, st, ctx, e.line);
31694
+ }
31695
+ case "Call":
31696
+ return this.call(e, st, ctx);
31697
+ case "New":
31698
+ return this.newExpr(e, st, ctx);
31699
+ case "Await":
31700
+ return e.arg ? this.expr(e.arg, st, ctx) : {};
31701
+ case "Arrow":
31702
+ return { fn: { node: e, scope: st.scope, file: ctx.file, name: e.name ?? null, thisVal: ctx.thisVal } };
31703
+ case "ClassExpr":
31704
+ return { cls: { node: e, scope: st.scope, file: ctx.file, name: e.name } };
31705
+ case "Obj": {
31706
+ const m = /* @__PURE__ */ new Map();
31707
+ let agg = {};
31708
+ for (const p of e.props) {
31709
+ if (p.spread) {
31710
+ const sv = this.expr(p.spread, st, ctx);
31711
+ if (sv.obj) for (const [k, v2] of sv.obj) m.set(k, v2);
31712
+ else m.set(`...${m.size}`, { ...sv, spreadUnknown: true });
31713
+ agg = join2(agg, dataOf(sv));
31714
+ continue;
31715
+ }
31716
+ if (p.computed && p.key == null) this.expr(p.computed, st, ctx);
31717
+ const v = this.expr(p.value, st, ctx);
31718
+ if (p.key != null) m.set(String(p.key), v);
31719
+ agg = join2(agg, dataOf(v));
31720
+ }
31721
+ return { ...agg, obj: m };
31722
+ }
31723
+ case "Arr": {
31724
+ const arr = e.elems.map((x) => x ? this.expr(x.type === "Spread" ? x.arg : x, st, ctx) : {});
31725
+ return { ...joinAll(arr.map(dataOf)), arr };
31726
+ }
31727
+ case "Spread":
31728
+ return this.expr(e.arg, st, ctx);
31729
+ case "Bin": {
31730
+ const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx);
31731
+ const out = join2(dataOf(l), dataOf(r));
31732
+ if (["===", "==", "!==", "!="].includes(e.op)) {
31733
+ const g = this.ownerComparison(l, r, e.line, ctx) ?? this.ownerComparison(r, l, e.line, ctx);
31734
+ if (g) {
31735
+ const eq3 = e.op === "===" || e.op === "==";
31736
+ return { predicate: eq3 ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] } };
31737
+ }
31738
+ }
31739
+ if (e.op === "+" && (l.tpl || r.tpl || typeof l.lit === "string" || typeof r.lit === "string")) out.concat = [l, r];
31740
+ return out;
31741
+ }
31742
+ case "Logic": {
31743
+ const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx);
31744
+ return join2(l, r);
31745
+ }
31746
+ case "Cond": {
31747
+ this.expr(e.test, st, ctx);
31748
+ return join2(this.expr(e.cons, st, ctx), this.expr(e.alt, st, ctx));
31749
+ }
31750
+ case "Unary": {
31751
+ const v = this.expr(e.arg, st, ctx);
31752
+ return e.op === "!" || e.op === "typeof" || e.op === "delete" || e.op === "void" ? {} : dataOf(v);
31753
+ }
31754
+ case "Assign":
31755
+ return this.assign(e, st, ctx);
31756
+ case "Seq": {
31757
+ let v = {};
31758
+ for (const x of e.list) v = this.expr(x, st, ctx);
31759
+ return v;
31760
+ }
31761
+ case "Tagged":
31762
+ return this.tagged(e, st, ctx);
31763
+ default:
31764
+ return {};
31765
+ }
31766
+ }
31767
+ lookup(name, st, ctx, line) {
31768
+ const v = st.scope.get(name);
31769
+ if (v !== void 0) return v;
31770
+ const m = this.p.files.get(ctx.file);
31771
+ if (m && (m.bindings.has(name) || m.imports.has(name))) return this.moduleValue(ctx.file, name, line);
31772
+ if (DB_NAMES.test(name)) return { isDb: { label: name } };
31773
+ return { global: name };
31774
+ }
31775
+ assign(e, st, ctx) {
31776
+ const v = this.expr(e.right, st, ctx);
31777
+ const val = e.op === "=" ? v : join2(this.expr(e.left, cloneState(st), ctx), v);
31778
+ if (e.left.type === "Id") st.scope.set(e.left.name, val);
31779
+ else if (e.left.type === "Member") {
31780
+ const o = this.expr(e.left.object, st, ctx);
31781
+ if ((o.isReq || o.isRes) && e.left.prop) st.req.set(e.left.prop, val);
31782
+ else if (o.obj && e.left.prop) o.obj.set(e.left.prop, val);
31783
+ else if (e.left.object.type === "Member" && e.left.object.prop === "locals") st.req.set(`locals.${e.left.prop}`, val);
31784
+ } else if (e.left.type === "ObjPat" || e.left.type === "Obj" || e.left.type === "Arr") {
31785
+ }
31786
+ return val;
31787
+ }
31788
+ member(o, prop, st, ctx, line) {
31789
+ if (!o) return {};
31790
+ if (prop == null) return dataOf(o);
31791
+ if (o.isReq) {
31792
+ if (st.req.has(prop)) return st.req.get(prop);
31793
+ if (["params", "query", "body", "headers", "cookies", "url", "originalUrl", "path", "hostname", "ip", "raw", "searchParams", "files", "file", "signedCookies"].includes(prop)) return { input: [{ says: `${o.isReq.name}.${prop}`, file: ctx.file, line }], inputObj: true, reqPart: prop };
31794
+ if (["user", "auth", "session", "currentUser", "principal", "identity", "claims", "tenant", "account", "member", "viewer", "jwt"].includes(prop)) return this.identity(`${o.isReq.name}.${prop}`, ctx, line, st);
31795
+ if (prop === "nextUrl") return { nextUrl: true, input: [{ says: `${o.isReq.name}.nextUrl`, file: ctx.file, line }] };
31796
+ if (prop === "json" || prop === "formData" || prop === "text") return { reqBodyFn: o.isReq.name };
31797
+ if (prop === "jwtVerify") return { identityFn: `${o.isReq.name}.jwtVerify()` };
31798
+ if (prop === "locals") return { locals: true, isReq: o.isReq };
31799
+ if (prop === "log" || prop === "server") return {};
31800
+ return {};
31801
+ }
31802
+ if (o.isRes) {
31803
+ if (prop === "locals") return { locals: true, isReq: { name: `${o.isRes.name}` } };
31804
+ return {};
31805
+ }
31806
+ if (o.locals) {
31807
+ if (st.req.has(`locals.${prop}`)) return st.req.get(`locals.${prop}`);
31808
+ if (/user|auth|session|account/i.test(prop)) return this.identity(`res.locals.${prop}`, ctx, line, st);
31809
+ return {};
31810
+ }
31811
+ if (o.nextUrl) {
31812
+ if (prop === "searchParams") return { input: o.input, searchParams: true };
31813
+ return { input: o.input };
31814
+ }
31815
+ if (o.isParams) return { input: [{ says: `params.${prop}`, file: ctx.file, line }] };
31816
+ if (o.ctx) {
31817
+ if (prop === "req") return { honoReq: true };
31818
+ if (prop === "var" || prop === "env") return { honoVar: prop };
31819
+ return { ctxMethod: prop, ctxVal: o };
31820
+ }
31821
+ if (o.honoReq) return { honoReqMethod: prop };
31822
+ if (o.honoVar) {
31823
+ if (o.honoVar === "env" && /DB|DATABASE/.test(prop)) return { isDb: { label: `c.env.${prop}` } };
31824
+ if (/user|auth|session|jwt|payload|account|tenant/i.test(prop)) return this.identity(`c.var.${prop}`, ctx, line, st);
31825
+ return {};
31826
+ }
31827
+ if (o.ns) return this.exportValue(o.ns, prop) ?? {};
31828
+ const out = {};
31829
+ if (o.input?.length) out.input = o.input.map((ev) => ({ ...ev, says: `${ev.says}.${prop}` }));
31830
+ if (o.ident?.length) out.ident = o.ident.map((ev) => ({ ...ev, says: `${ev.says}.${prop}`, field: prop }));
31831
+ if (o.recs?.length) {
31832
+ out.recs = o.recs;
31833
+ out.recFields = o.recs.map((rec) => ({ rec, field: prop, says: `${rec.var ?? rec.model ?? "the record"}.${prop}` }));
31834
+ }
31835
+ if (o.unknown?.length) out.unknown = o.unknown;
31836
+ if (o.obj?.has(prop)) return join2(o.obj.get(prop), {});
31837
+ if (o.obj && !hasData(out)) {
31838
+ for (const [k, v] of o.obj) if (k.startsWith("...") && v.spreadUnknown) return dataOf(v);
31839
+ }
31840
+ if (o.clientFor) return { ...out, dbMember: { client: { label: o.clientFor.says, scoped: o.clientFor }, prop } };
31841
+ if (o.isDb) {
31842
+ if (prop === "query") return { dbQuery: o.isDb };
31843
+ return { dbMember: { client: o.isDb, prop } };
31844
+ }
31845
+ if (o.dbQuery) return { drizzleRel: { client: o.dbQuery, table: prop } };
31846
+ if (o.dbMember) return { dbModelOp: { client: o.dbMember.client, model: o.dbMember.prop, op: prop } };
31847
+ if (o.drizzleRel) return { drizzleRelOp: { ...o.drizzleRel, op: prop } };
31848
+ if (o.cls && o.static !== false) {
31849
+ const mm = this.classMember(o.cls, prop, true);
31850
+ if (mm) return mm;
31851
+ }
31852
+ if (o.instance) {
31853
+ if (o.instance.fields?.has(prop)) return o.instance.fields.get(prop);
31854
+ const mm = this.classMember(o.instance.cls, prop, false, o);
31855
+ if (mm) return mm;
31856
+ }
31857
+ if (o.opaque) return { opaque: { ...o.opaque, why: o.opaque.why }, opaqueName: `${o.opaqueName ?? o.pkgName ?? "it"}.${prop}`, pkg: o.pkg, ...out };
31858
+ if (o.global) return { global: `${o.global}.${prop}`, ...out };
31859
+ if (o.fn && prop === "call") return o;
31860
+ return out;
31861
+ }
31862
+ classMember(cls, prop, isStatic, inst) {
31863
+ for (const m of cls.node.members) {
31864
+ if (m.key !== prop || !!m.isStatic !== isStatic) continue;
31865
+ if (m.fn) return { fn: { node: m.fn, scope: cls.scope, file: cls.file, name: `${cls.name}.${prop}`, thisVal: inst ?? { cls } } };
31866
+ }
31867
+ return null;
31868
+ }
31869
+ identity(says, ctx, line, st) {
31870
+ const ev = { says, file: ctx.file, line };
31871
+ if (st && !st.identity) st.identity = ev;
31872
+ return { ident: [{ ...ev, src: ev, field: null }] };
31873
+ }
31874
+ newExpr(e, st, ctx) {
31875
+ const c = this.expr(e.callee, st, ctx);
31876
+ const args = e.args.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
31877
+ const name = e.callee.type === "Id" ? e.callee.name : e.callee.prop;
31878
+ if (name && DB_FACTORIES.test(name)) return { dbFactory: true };
31879
+ if (name === "Response" || name === "NextResponse") {
31880
+ this.sink("response", args[0] ?? {}, st, ctx, e.line, `answers with new ${name}(\u2026)`, this.statusOf(args[1]));
31881
+ return { response: true };
31882
+ }
31883
+ if (name === "URL") return joinAll(args.map(dataOf));
31884
+ if (/^(Map|Set|WeakMap|WeakSet|URLSearchParams|Headers|FormData|Array)$/.test(name ?? "")) return { ...joinAll(args.map(dataOf)), collection: true };
31885
+ if (c.cls) {
31886
+ const fields = /* @__PURE__ */ new Map();
31887
+ const inst = { instance: { cls: c.cls, fields } };
31888
+ const ctor = c.cls.node.members.find((m) => m.key === "constructor" && m.fn);
31889
+ if (ctor) {
31890
+ ctor.fn.params.forEach((p, i) => {
31891
+ const id = p.type === "Default" ? p.target : p;
31892
+ if (id.type === "Id") fields.set(id.name, args[i] ?? {});
31893
+ });
31894
+ try {
31895
+ this.callFunction({ node: ctor.fn, scope: c.cls.scope, file: c.cls.file, name: `${c.cls.name}.constructor`, thisVal: inst }, args, st, ctx, e.line, inst);
31896
+ } catch (err) {
31897
+ if (err.limit) throw err;
31898
+ }
31899
+ }
31900
+ for (const m of c.cls.node.members) if (m.kind === "field" && m.value && !fields.has(m.key)) fields.set(m.key, this.expr(m.value, cloneState(st), { ...ctx, file: c.cls.file, thisVal: inst }));
31901
+ for (const [k, v] of fields) if (DB_NAMES.test(k) && !v.isDb && !hasData(v)) fields.set(k, { isDb: { label: `this.${k}` } });
31902
+ return inst;
31903
+ }
31904
+ return joinAll(args.map(dataOf));
31905
+ }
31906
+ statusOf(v) {
31907
+ if (!v?.obj) return null;
31908
+ const s = v.obj.get("status");
31909
+ return typeof s?.lit === "number" ? s.lit : null;
31910
+ }
31911
+ // ── Calls ──
31912
+ call(e, st, ctx) {
31913
+ const callee2 = e.callee;
31914
+ const line = e.line;
31915
+ const argNodes = e.args;
31916
+ const evalArgs = () => argNodes.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
31917
+ if (callee2.type === "Member") {
31918
+ const prop = callee2.prop;
31919
+ const o = this.expr(callee2.object, st, ctx);
31920
+ if (o.isRes) {
31921
+ if (prop === "status" || prop === "code" || prop === "type" || prop === "set" || prop === "header" || prop === "setHeader" || prop === "cookie" || prop === "clearCookie" || prop === "append" || prop === "vary" || prop === "location") {
31922
+ const a = evalArgs();
31923
+ return { isRes: { ...o.isRes, status: prop === "status" || prop === "code" ? typeof a[0]?.lit === "number" ? a[0].lit : o.isRes.status : o.isRes.status } };
31924
+ }
31925
+ if (["json", "send", "end", "jsonp", "render", "sendFile", "write", "redirect", "sendStatus", "download"].includes(prop)) {
31926
+ const a = evalArgs();
31927
+ const status = prop === "sendStatus" ? a[0]?.lit : o.isRes.status;
31928
+ const body2 = prop === "render" ? a[1] ?? {} : prop === "redirect" || prop === "sendStatus" ? {} : a[0] ?? {};
31929
+ this.sink("response", body2, st, ctx, line, `answers with ${o.isRes.name}.${prop}(\u2026)`, status);
31930
+ return { response: true, exits: typeof status === "number" && status >= 400 };
31931
+ }
31932
+ return {};
31933
+ }
31934
+ if (o.ctx) {
31935
+ const a = evalArgs();
31936
+ if (["json", "text", "html", "body", "newResponse"].includes(prop)) {
31937
+ this.sink("response", a[0] ?? {}, st, ctx, line, `answers with c.${prop}(\u2026)`, typeof a[1]?.lit === "number" ? a[1].lit : null);
31938
+ return { response: true };
31939
+ }
31940
+ if (prop === "get") {
31941
+ const k = a[0]?.lit;
31942
+ if (typeof k === "string" && st.req.has(`c:${k}`)) return st.req.get(`c:${k}`);
31943
+ if (typeof k === "string" && /user|auth|session|jwt|payload|account|tenant|claims/i.test(k)) return this.identity(`c.get("${k}")`, ctx, line, st);
31944
+ if (typeof k === "string" && /^db$|database|prisma/i.test(k)) return { isDb: { label: `c.get("${k}")` } };
31945
+ return {};
31946
+ }
31947
+ if (prop === "set") {
31948
+ if (typeof a[0]?.lit === "string") st.req.set(`c:${a[0].lit}`, a[1] ?? {});
31949
+ return {};
31950
+ }
31951
+ if (prop === "notFound") return { response: true, exits: true };
31952
+ return {};
31953
+ }
31954
+ if (o.honoReq) {
31955
+ const a = evalArgs();
31956
+ if (["param", "query", "queries", "json", "parseBody", "valid", "header", "formData", "text", "raw"].includes(prop)) return { input: [{ says: `c.req.${prop}(${typeof a[0]?.lit === "string" ? JSON.stringify(a[0].lit) : ""})`, file: ctx.file, line }] };
31957
+ return {};
31958
+ }
31959
+ if (o.reqBodyFn) {
31960
+ evalArgs();
31961
+ return { input: [{ says: `await ${o.reqBodyFn}.json()`, file: ctx.file, line }] };
31962
+ }
31963
+ if (o.identityFn) {
31964
+ evalArgs();
31965
+ return this.identity(o.identityFn, ctx, line, st);
31966
+ }
31967
+ if (o.searchParams) {
31968
+ const a = evalArgs();
31969
+ return { input: [{ says: `searchParams.${prop}(${typeof a[0]?.lit === "string" ? JSON.stringify(a[0].lit) : ""})`, file: ctx.file, line }] };
31970
+ }
31971
+ if ((o.global === "NextResponse" || o.global === "Response" || o.pkgName === "NextResponse") && prop === "json") {
31972
+ const a = evalArgs();
31973
+ const status = this.statusOf(a[1]);
31974
+ this.sink("response", a[0] ?? {}, st, ctx, line, `answers with ${o.global ?? o.pkgName}.json(\u2026)`, status);
31975
+ return { response: true, exits: typeof status === "number" && status >= 400 };
31976
+ }
31977
+ if ((o.global === "NextResponse" || o.pkgName === "NextResponse") && (prop === "redirect" || prop === "next" || prop === "rewrite")) {
31978
+ evalArgs();
31979
+ return { response: true };
31980
+ }
31981
+ if ((prop === "$transaction" || prop === "transaction") && o.isDb) {
31982
+ const a = evalArgs();
31983
+ if (a[0]?.fn) return this.callFunction(a[0].fn, [{ isDb: { label: "tx" } }], st, ctx, line);
31984
+ return joinAll(a.map(dataOf));
31985
+ }
31986
+ if (prop === "model" && (callee2.object.name === "mongoose" || o.pkg === "mongoose")) {
31987
+ const a = evalArgs();
31988
+ return { mongooseModel: { model: typeof a[0]?.lit === "string" ? a[0].lit : "a model" } };
31989
+ }
31990
+ if (o.isDb && prop === "query") return this.dbMethod({ client: o.isDb, prop }, argNodes, evalArgs, st, ctx, line);
31991
+ const fnVal = this.member(o, prop, st, ctx, line);
31992
+ if (fnVal.dbModelOp) return this.prismaOp(fnVal.dbModelOp, evalArgs(), st, ctx, line);
31993
+ if (fnVal.drizzleRelOp) return this.drizzleRel(fnVal.drizzleRelOp, evalArgs(), st, ctx, line);
31994
+ if (fnVal.dbMember) return this.dbMethod(fnVal.dbMember, argNodes, evalArgs, st, ctx, line);
31995
+ if (o.drizzle) return this.drizzleStep(o.drizzle, prop, evalArgs(), st, ctx, line, argNodes);
31996
+ if (o.knex) return this.knexStep(o.knex, prop, evalArgs(), st, ctx, line);
31997
+ if (o.mongooseModel && MONGOOSE_OPS.has(prop)) return this.mongooseOp(o.mongooseModel, prop, evalArgs(), st, ctx, line);
31998
+ if ((prop === "then" || prop === "catch" || prop === "finally") && argNodes.length) {
31999
+ const a = evalArgs();
32000
+ let out = dataOf(o);
32001
+ if (a[0]?.fn && prop === "then") out = join2(out, this.callFunction(a[0].fn, [dataOf(o)], st, ctx, line));
32002
+ return out;
32003
+ }
32004
+ const full = callee2.object.type === "Id" ? `${callee2.object.name}.${prop}` : null;
32005
+ if (full && PASS_THROUGH_MEMBERS.has(full)) {
32006
+ const a = evalArgs();
32007
+ return { ...joinAll(a.map(dataOf)), ...full === "Promise.all" && a[0]?.arr ? { arr: a[0].arr } : {} };
32008
+ }
32009
+ if (full === "jwt.verify" || full === "jose.jwtVerify") {
32010
+ evalArgs();
32011
+ return this.identity(`${full}()`, ctx, line, st);
32012
+ }
32013
+ if (fnVal.fn) return this.callFunction(fnVal.fn, evalArgs(), st, ctx, line, fnVal.fn.thisVal);
32014
+ if (/^(parse|safeParse|parseAsync|validate|validateSync|cast)$/.test(prop) && argNodes.length) {
32015
+ const a = evalArgs();
32016
+ return joinAll(a.map(dataOf));
32017
+ }
32018
+ if (o.collection) {
32019
+ const a = evalArgs();
32020
+ return join2(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf)));
32021
+ }
32022
+ if (hasData(o) && !o.opaque) {
32023
+ const a = evalArgs();
32024
+ if ((prop === "equals" || prop === "isEqual") && a[0]) {
32025
+ const g = this.ownerComparison(o, a[0], line, ctx) ?? this.ownerComparison(a[0], o, line, ctx);
32026
+ if (g) return { predicate: { whenTrue: [g], whenFalse: [] } };
32027
+ }
32028
+ if (prop === "includes" && a[0]) {
32029
+ const recSide = o.recFields?.length || o.recs?.length ? o : a[0].recFields?.length || a[0].recs?.length ? a[0] : null;
32030
+ const idSide = recSide === o ? a[0] : o;
32031
+ if (recSide && idSide?.ident?.length && !idSide.input?.length) {
32032
+ const recs = [.../* @__PURE__ */ new Set([...(recSide.recFields ?? []).map((f2) => f2.rec), ...recSide.recs ?? []])];
32033
+ return { predicate: { whenTrue: [{ kind: "guard", recs, ev: { says: `checks that ${idSide.ident[0].says} includes ${recSide.recFields?.[0]?.says ?? "the record"}`, file: ctx.file, line } }], whenFalse: [] } };
32034
+ }
32035
+ }
32036
+ if (["some", "find", "every", "findIndex", "findLast"].includes(prop) && a[0]?.fn) {
32037
+ const v = this.callFunction(a[0].fn, [this.element(o)], cloneState(st), ctx, line);
32038
+ if (v.predicate?.whenTrue?.length) return { predicate: { whenTrue: v.predicate.whenTrue, whenFalse: [] } };
32039
+ }
32040
+ if (prop === "includes" && o.ident?.some((x) => /^(roles|permissions|scopes|groups)$/i.test(x.field ?? "")) && typeof a[0]?.lit === "string" && /admin|staff|super|owner|support/i.test(a[0].lit)) {
32041
+ return { predicate: { whenTrue: [{ kind: "role", ev: { says: `only when ${o.ident[0].says} includes "${a[0].lit}"`, file: ctx.file, line } }], whenFalse: [] } };
32042
+ }
32043
+ return join2(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf)));
32044
+ }
32045
+ return this.unresolvedCall(fnVal.opaqueName ?? (callee2.object.type === "Id" ? `${callee2.object.name}.${prop}` : prop), o.opaque?.why ?? (o.global ? `${o.global}.${prop} is not defined in these files` : `${prop} could not be followed`), evalArgs(), st, ctx, line, o);
32046
+ }
32047
+ const name = callee2.type === "Id" ? callee2.name : null;
32048
+ const f = this.expr(callee2, st, ctx);
32049
+ if (name && NEXT_EXITS.has(name) && (f.pkg === "next/navigation" || f.global)) {
32050
+ evalArgs();
32051
+ return { exits: true };
32052
+ }
32053
+ if (name === "next") {
32054
+ evalArgs();
32055
+ st.calledNext = true;
32056
+ return {};
32057
+ }
32058
+ if (name === "model" && f.pkg === "mongoose") {
32059
+ const a = evalArgs();
32060
+ return { mongooseModel: { model: typeof a[0]?.lit === "string" ? a[0].lit : "a model" } };
32061
+ }
32062
+ if (f.reqNext) {
32063
+ const a = evalArgs();
32064
+ if (!a.length || a[0].lit === void 0) st.calledNext = true;
32065
+ else return { exits: true };
32066
+ return {};
32067
+ }
32068
+ if (f.knexRoot || f.isDb && argNodes.length === 1 && argNodes[0].type === "Lit" && typeof argNodes[0].value === "string") {
32069
+ const a = evalArgs();
32070
+ return { knex: { client: f.isDb ?? { label: name }, table: a[0]?.lit ?? null, conds: [], line, write: null } };
32071
+ }
32072
+ if (f.isDb && callee2.type === "Id" && argNodes.length && (argNodes[0].type === "Tpl" || argNodes[0].type === "Lit")) return this.rawSql(f.isDb, evalArgs(), st, ctx, line);
32073
+ if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !f.fn) {
32074
+ evalArgs();
32075
+ return this.identity(`${name}()`, ctx, line, st);
32076
+ }
32077
+ if (name && ROLE_FN.test(name) && !f.fn) {
32078
+ const a = evalArgs();
32079
+ if (!st.role) st.role = { says: `${name}(${typeof a[a.length - 1]?.lit === "string" ? JSON.stringify(a[a.length - 1].lit) : "\u2026"})`, file: ctx.file, line };
32080
+ return {};
32081
+ }
32082
+ if (f.fn) {
32083
+ const a = evalArgs();
32084
+ const v = this.callFunction(f.fn, a, st, ctx, line);
32085
+ if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !v.ident?.length) return { ...v, ...this.identity(`${name}()`, ctx, line, st) };
32086
+ return v;
32087
+ }
32088
+ if (f.cls) {
32089
+ evalArgs();
32090
+ return {};
32091
+ }
32092
+ if (name && PASS_THROUGH.has(name)) return joinAll(evalArgs().map(dataOf));
32093
+ if (f.isDb) return this.rawSql(f.isDb, evalArgs(), st, ctx, line);
32094
+ return this.unresolvedCall(name ?? "a function", f.opaque?.why ?? (name ? `${name} is not defined in these files` : "the function could not be followed"), evalArgs(), st, ctx, line, f);
32095
+ }
32096
+ /**
32097
+ * A call Thunder cannot follow. Its result is a value Thunder cannot see into when it was given request data. If it
32098
+ * also sees the record or the caller (or its name says it checks something), it might be an ownership check, so the
32099
+ * path becomes "cannot tell".
32100
+ */
32101
+ unresolvedCall(name, why, args, st, ctx, line, calleeVal) {
32102
+ const ev = { says: `${name}(\u2026)`, why, file: ctx.file, line };
32103
+ const fnArgs = args.filter((a) => a.fn);
32104
+ for (const a of fnArgs) {
32105
+ try {
32106
+ this.callFunction(a.fn, [], st, ctx, line);
32107
+ } catch (err) {
32108
+ if (err.limit) throw err;
32109
+ }
32110
+ }
32111
+ const data = args.filter((a) => !a.fn);
32112
+ const sawRecord = data.some((a) => a.recs?.length || a.recFields?.length);
32113
+ const sawCaller = data.some((a) => a.ident?.length);
32114
+ const sawInput = data.some((a) => a.input?.length || a.unknown?.length);
32115
+ const baseName = String(name).split(".").pop();
32116
+ if ((sawRecord || sawCaller) && (GUARDISH.test(baseName) || sawRecord && sawCaller)) st.unresolved = uniq(st.unresolved, [{ ...ev, says: `${name}(\u2026) might check who may see it` }]);
32117
+ const out = joinAll(data.map(dataOf));
32118
+ if (sawCaller && !GUARDISH.test(baseName)) out.clientFor = { says: `${name}(\u2026)`, file: ctx.file, line };
32119
+ const parts = String(name).split(".");
32120
+ const ownerName = parts.length > 1 ? parts[parts.length - 2] : "";
32121
+ const dataLike = name !== "fetch" && !NOT_DATA_PACKAGE.test(calleeVal?.pkg ?? "") && !["path", "fs", "os", "url", "crypto", "util", "process", "console", "JSON", "Math", "Date", BUF].includes(parts[0]) && (LOOKUP_NAME.test(baseName) || parts.length > 1 && LOOKUP_OWNER.test(ownerName) && !/^(set|add|log|emit|send|push|on|use)$/.test(baseName));
32122
+ if ((sawInput || calleeVal?.recs?.length) && dataLike) out.unknown = uniq(out.unknown, [{ ...ev, says: `${name}(\u2026)` }]);
32123
+ if (calleeVal && hasData(calleeVal)) return join2(out, dataOf(calleeVal));
32124
+ return out;
32125
+ }
32126
+ callFunction(fn, args, st, ctx, line, thisVal) {
32127
+ if ((ctx.depth ?? 0) >= MAX_DEPTH) {
32128
+ const ev = { says: `${fn.name ?? "a function"}(\u2026)`, why: `Thunder stops following calls ${MAX_DEPTH} deep`, file: ctx.file, line };
32129
+ if (args.some((a) => a.recs?.length || a.ident?.length)) st.unresolved = uniq(st.unresolved, [ev]);
32130
+ const out = joinAll(args.map(dataOf));
32131
+ if (args.some((a) => a.input?.length)) out.unknown = uniq(out.unknown, [ev]);
32132
+ return out;
32133
+ }
32134
+ const node = fn.node;
32135
+ const frame = { returns: [] };
32136
+ const inner = cloneState(st);
32137
+ inner.scope = new Scope(fn.scope);
32138
+ inner.frame = frame;
32139
+ inner.exited = null;
32140
+ const c2 = { ...ctx, file: fn.file, depth: (ctx.depth ?? 0) + 1, thisVal: thisVal ?? fn.thisVal ?? ctx.thisVal, returnsSend: false };
32141
+ (node.params ?? []).forEach((p, i) => {
32142
+ if (p.type === "Rest") this.bindPattern(p.arg, { arr: args.slice(i), ...joinAll(args.slice(i).map(dataOf)) }, inner.scope, inner, c2, true);
32143
+ else this.bindPattern(p, args[i] ?? {}, inner.scope, inner, c2, true);
32144
+ });
32145
+ if (node.body?.type === "Block") this.block(node.body.body, inner, c2);
32146
+ else if (node.body) {
32147
+ const v2 = this.expr(node.body, inner, c2);
32148
+ frame.returns.push({ val: v2, state: cloneState(inner) });
32149
+ inner.exited = "return";
32150
+ }
32151
+ const back = [...frame.returns.map((r) => r.state)];
32152
+ if (!inner.exited) back.push(inner);
32153
+ if (!back.length) {
32154
+ st.exited = "throw";
32155
+ return {};
32156
+ }
32157
+ const merged = back.reduce((a, b) => mergeStates(a, { ...b, exited: null }), { ...back[0], exited: null });
32158
+ st.guards = merged.guards;
32159
+ st.role = merged.role;
32160
+ st.identity = st.identity ?? merged.identity;
32161
+ st.unresolved = merged.unresolved;
32162
+ st.calledNext = st.calledNext || merged.calledNext;
32163
+ st.req = merged.req;
32164
+ const vals = frame.returns.map((r) => r.val);
32165
+ const v = joinAll(vals);
32166
+ if (frame.returns.length && node.body) {
32167
+ const preds = [];
32168
+ for (const r of frame.returns) if (r.pred) preds.push(r.pred);
32169
+ }
32170
+ const pred = this.predicateOf(node, args, c2, fn);
32171
+ if (pred) v.predicate = pred;
32172
+ return v;
32173
+ }
32174
+ // A function whose returned expression is a comparison: canRead(user, invoice) { return invoice.ownerId === user.id }.
32175
+ predicateOf(node, args, ctx, fn) {
32176
+ const rets = [];
32177
+ const collect = (s) => {
32178
+ if (!s) return;
32179
+ if (s.type === "Return" && s.arg) rets.push(s.arg);
32180
+ else if (s.type === "Block") s.body.forEach(collect);
32181
+ else if (s.type === "If") {
32182
+ collect(s.cons);
32183
+ collect(s.alt);
32184
+ }
32185
+ };
32186
+ if (node.body?.type === "Block") node.body.body.forEach(collect);
32187
+ else if (node.body) rets.push(node.body);
32188
+ if (rets.length !== 1) return null;
32189
+ const st = newState(new Scope(fn.scope), { returns: [] });
32190
+ (node.params ?? []).forEach((p, i) => this.bindPattern(p.type === "Rest" ? p.arg : p, args[i] ?? {}, st.scope, st, ctx, true));
32191
+ const f = this.testFacts(rets[0], st, ctx);
32192
+ return f.whenTrue.length || f.whenFalse.length ? f : null;
32193
+ }
32194
+ // ── Databases ──
32195
+ newRec(props) {
32196
+ this.recCount++;
32197
+ return { id: `r${this.recCount}`, ...props };
32198
+ }
32199
+ /** A where condition as conjuncts: { conj: [{ col, val }], or: [[…], …], nested: [...], unknown: why }. */
32200
+ whereFromObject(v) {
32201
+ const w = { conj: [], or: [], unknown: null };
32202
+ if (!v) return w;
32203
+ if (!v.obj) {
32204
+ if (hasData(v)) w.unknown = "the where condition is a value Thunder cannot see into";
32205
+ return w;
32206
+ }
32207
+ for (const [k, val] of v.obj) {
32208
+ if (k.startsWith("...")) {
32209
+ if (hasData(val) || val.opaque) w.unknown = "the where condition spreads a value Thunder cannot see into";
32210
+ continue;
32211
+ }
32212
+ if (k === "AND") {
32213
+ for (const x of val.arr ?? [val]) {
32214
+ const sub2 = this.whereFromObject(x);
32215
+ w.conj.push(...sub2.conj);
32216
+ w.or.push(...sub2.or);
32217
+ w.unknown = w.unknown ?? sub2.unknown;
32218
+ }
32219
+ continue;
32220
+ }
32221
+ if (k === "OR") {
32222
+ w.or.push((val.arr ?? [val]).map((x) => this.whereFromObject(x)));
32223
+ continue;
32224
+ }
32225
+ if (k === "NOT") continue;
32226
+ if (val.obj) {
32227
+ const sub2 = this.whereFromObject(val);
32228
+ if (sub2.conj.length || sub2.or.length) w.conj.push({ col: k, nested: sub2 });
32229
+ else w.conj.push({ col: k, val });
32230
+ continue;
32231
+ }
32232
+ w.conj.push({ col: k, val });
32233
+ }
32234
+ return w;
32235
+ }
32236
+ /** How a where condition limits a lookup: by the request (keyed), by the caller (scoped), or by the caller's identity. */
32237
+ judgeWhere(w) {
32238
+ const out = { keyed: null, scoped: null, byIdentity: null, unknown: w.unknown };
32239
+ const visit = (wh, path) => {
32240
+ for (const c of wh.conj) {
32241
+ if (c.nested) {
32242
+ visit(c.nested, [...path, c.col]);
32243
+ continue;
32244
+ }
32245
+ const v = c.val;
32246
+ if (v?.input?.length && !out.keyed) out.keyed = { says: `${[...path, c.col].join(".")} = ${v.input[0].says}`, value: v.input[0].says, file: v.input[0].file, line: v.input[0].line };
32247
+ if (v?.unknown?.length && !out.keyed && !out.unknown) out.unknown = `${[...path, c.col].join(".")} comes from ${v.unknown[0].says}, which Thunder cannot follow`;
32248
+ if (v?.ident?.length && !v.input?.length) {
32249
+ const ev = v.ident[0];
32250
+ const col = c.col;
32251
+ const ownerish = OWNER_FIELD.test(col) || OWNER_FIELD.test(ev.field ?? "") || path.some((p) => OWNER_FIELD.test(p));
32252
+ if (col === "id" && !path.length && (ev.field === "id" || ev.field == null || /Id$/.test(ev.field ?? ""))) {
32253
+ if (!out.byIdentity) out.byIdentity = { says: `${col} = ${ev.says}` };
32254
+ } else if (ownerish && !out.scoped) out.scoped = { says: `${[...path, col].join(".")} = ${ev.says}` };
32255
+ }
32256
+ if (v?.recFields?.length && !v.input?.length) out.fromRecord = uniq(out.fromRecord, v.recFields.map((f) => f.rec));
32257
+ }
32258
+ for (const group of wh.or) {
32259
+ const judged = group.map((g) => this.judgeWhere(g));
32260
+ if (!out.keyed) out.keyed = judged.find((j) => j.keyed)?.keyed ?? null;
32261
+ if (!out.scoped && judged.length && judged.every((j) => j.scoped)) out.scoped = judged[0].scoped;
32262
+ else if (judged.some((j) => j.scoped || j.byIdentity) && !out.unknown) out.unknown = `the where allows the caller's records (${(judged.find((j) => j.scoped) ?? judged.find((j) => j.byIdentity)).scoped?.says ?? "by identity"}) OR other ones; Thunder cannot tell whether those others are meant to be open`;
32263
+ if (!out.unknown) out.unknown = judged.find((j) => j.unknown)?.unknown ?? null;
32264
+ }
32265
+ };
32266
+ visit(w, []);
32267
+ return out;
32268
+ }
32269
+ makeLookup({ client, model, op, kind, where, st, ctx, line, varName }) {
32270
+ const j = this.judgeWhere(where);
32271
+ const rec = this.newRec({ model, op, kind, file: ctx.file, line, keyed: j.keyed, scoped: j.scoped, byIdentity: j.byIdentity, unknownWhere: j.unknown, client: client?.label, clientScoped: client?.scoped ?? null, var: varName });
32272
+ if (j.scoped && j.fromRecord?.length) rec.links = j.fromRecord;
32273
+ if (j.scoped && /OrThrow$/.test(op)) {
32274
+ const ev = { says: `${model}.${op} stops unless it belongs to the caller`, file: ctx.file, line };
32275
+ for (const r of j.fromRecord ?? []) guardRec(st, r, ev);
32276
+ if (j.keyed?.value) st.guards.set(`key:${j.keyed.value}`, ev);
32277
+ }
32278
+ if (kind === "change") this.sink("change", { recs: [rec] }, st, ctx, line, `${op === "delete" || /delete|del|remove/i.test(op) ? "deletes" : "changes"} ${model ?? "a record"}`);
32279
+ return { recs: [rec] };
32280
+ }
32281
+ prismaOp({ client, model, op }, args, st, ctx, line) {
32282
+ if (!PRISMA_ALL.has(op)) return this.unresolvedCall(`${client.label}.${model}.${op}`, `${op} is not a database call Thunder knows`, args, st, ctx, line);
32283
+ if (op === "create" || op === "createMany") return { recs: [this.newRec({ model, op, kind: "create", file: ctx.file, line })] };
32284
+ const opts = args[0];
32285
+ const where = this.whereFromObject(opts?.obj?.get("where"));
32286
+ if (opts && !opts.obj && hasData(opts)) where.unknown = "the query options are a value Thunder cannot see into";
32287
+ if (!opts?.obj?.has("where") && opts?.obj) {
32288
+ }
32289
+ const kind = PRISMA_WRITE.has(op) ? "change" : "read";
32290
+ return this.makeLookup({ client, model, op, kind, where, st, ctx, line });
32291
+ }
32292
+ dbMethod({ client, prop }, argNodes, evalArgs, st, ctx, line) {
32293
+ if (["query", "execute", "$queryRawUnsafe", "$executeRawUnsafe", "one", "oneOrNone", "many", "any", "none", "get", "all", "run", "prepare"].includes(prop) && argNodes.length && (argNodes[0].type === "Lit" || argNodes[0].type === "Tpl" || argNodes[0].type === "Id" || argNodes[0].type === "Bin")) {
32294
+ return this.rawSql(client, evalArgs(), st, ctx, line, prop.includes("execute") ? "change" : null);
32295
+ }
32296
+ const a = evalArgs();
32297
+ if (["select", "selectDistinct", "selectFrom"].includes(prop)) return { drizzle: { client, kind: "read", table: null, where: null, line } };
32298
+ if (prop === "update" || prop === "delete" || prop === "updateTable" || prop === "deleteFrom") return { drizzle: { client, kind: "change", op: prop, table: this.tableName(a[0], argNodes[0]), where: null, line } };
32299
+ if (prop === "insert" || prop === "insertInto") return { drizzle: { client, kind: "create", table: this.tableName(a[0], argNodes[0]), line } };
32300
+ if (prop === "$connect" || prop === "$disconnect" || prop === "end" || prop === "release" || prop === "connect") return {};
32301
+ return this.unresolvedCall(`${client.label}.${prop}`, `${client.label}.${prop} is not a database call Thunder knows`, a, st, ctx, line);
32302
+ }
32303
+ tableName(v, node) {
32304
+ if (!v) return null;
32305
+ if (typeof v.lit === "string") return v.lit;
32306
+ if (node?.type === "Id") return node.name;
32307
+ if (node?.type === "Member") return node.prop;
32308
+ return v.tableName ?? v.global ?? v.opaqueName ?? null;
32309
+ }
32310
+ // Drizzle conditions: eq(t.col, v), and(...), or(...), inArray(t.col, [...]).
32311
+ drizzleWhere(v) {
32312
+ const w = { conj: [], or: [], unknown: null };
32313
+ if (!v) return w;
32314
+ if (v.cond) {
32315
+ if (v.cond.op === "and") for (const x of v.cond.args) {
32316
+ const s = this.drizzleWhere(x);
32317
+ w.conj.push(...s.conj);
32318
+ w.or.push(...s.or);
32319
+ w.unknown = w.unknown ?? s.unknown;
32320
+ }
32321
+ else if (v.cond.op === "or") w.or.push(v.cond.args.map((x) => this.drizzleWhere(x)));
32322
+ else if (v.cond.op === "eq") w.conj.push({ col: v.cond.col, val: v.cond.val });
32323
+ else if (v.cond.op === "raw") {
32324
+ const s = v.cond.where;
32325
+ w.conj.push(...s.conj);
32326
+ w.or.push(...s.or);
32327
+ w.unknown = w.unknown ?? s.unknown;
32328
+ }
32329
+ return w;
32330
+ }
32331
+ if (v.obj) return this.whereFromObject(v);
32332
+ if (hasData(v)) w.unknown = "the where condition is a value Thunder cannot see into";
32333
+ return w;
32334
+ }
32335
+ drizzleStep(d, prop, args, st, ctx, line, argNodes = []) {
32336
+ if (prop === "from" || prop === "selectFrom") return { drizzle: { ...d, table: this.tableName(args[0], argNodes[0]) } };
32337
+ if (prop === "where") {
32338
+ const where = this.drizzleWhere(args[0]);
32339
+ const next = { ...d, where };
32340
+ if (d.kind === "change") return { ...this.makeLookup({ client: d.client, model: d.table, op: d.op ?? "update", kind: "change", where, st, ctx, line }), drizzle: { ...next, done: true } };
32341
+ return { drizzle: next, ...this.drizzleRec(next, st, ctx, line) };
32342
+ }
32343
+ if (["set", "values", "returning", "onConflictDoNothing", "onConflictDoUpdate"].includes(prop)) return { drizzle: d };
32344
+ if (["limit", "offset", "orderBy", "groupBy", "innerJoin", "leftJoin", "rightJoin", "fullJoin", "having", "execute", "all", "get", "then", "prepare", "selectAll", "executeTakeFirst", "executeTakeFirstOrThrow"].includes(prop)) {
32345
+ if (prop === "selectAll" || prop === "executeTakeFirst" || prop === "executeTakeFirstOrThrow" || prop === "execute") return { drizzle: d, ...this.drizzleRec(d, st, ctx, line) };
32346
+ return { drizzle: d, ...d.where ? this.drizzleRec(d, st, ctx, line) : {} };
32347
+ }
32348
+ return { drizzle: d };
32349
+ }
32350
+ drizzleRec(d, st, ctx, line) {
32351
+ if (d.kind !== "read") return {};
32352
+ if (d._rec) return { recs: [d._rec] };
32353
+ const v = this.makeLookup({ client: d.client, model: d.table, op: "select", kind: "read", where: d.where ?? { conj: [], or: [], unknown: null }, st, ctx, line: d.line ?? line });
32354
+ d._rec = v.recs[0];
32355
+ return v;
32356
+ }
32357
+ drizzleRel({ client, table, op }, args, st, ctx, line) {
32358
+ if (!["findFirst", "findMany"].includes(op)) return {};
32359
+ const opts = args[0];
32360
+ let whereVal = opts?.obj?.get("where");
32361
+ if (whereVal?.fn) {
32362
+ const ops = { obj: new Map(["eq", "and", "or", "inArray", "ne"].map((k) => [k, { global: k }])) };
32363
+ whereVal = this.callFunction(whereVal.fn, [{ table: { name: table }, tableName: table }, ops], st, ctx, line);
32364
+ }
32365
+ const where = this.drizzleWhere(whereVal);
32366
+ return this.makeLookup({ client, model: table, op, kind: "read", where, st, ctx, line });
32367
+ }
32368
+ knexStep(k, prop, args, st, ctx, line) {
32369
+ const addConds = () => {
32370
+ if (args.length === 1 && args[0].obj) {
32371
+ const w = this.whereFromObject(args[0]);
32372
+ return [...k.conds, ...w.conj];
32373
+ }
32374
+ if (args.length >= 2 && typeof args[0].lit === "string") return [...k.conds, { col: args[0].lit.split(".").pop(), val: args[args.length - 1] }];
32375
+ if (args[0]?.fn) return [...k.conds, { col: "?", val: { unknown: [{ says: "a where callback", file: ctx.file, line }] } }];
32376
+ return [...k.conds, { col: "?", val: dataOf(args[0] ?? {}) }];
32377
+ };
32378
+ if (prop === "where" || prop === "andWhere") return { knex: { ...k, conds: addConds() } };
32379
+ if (prop === "orWhere") return { knex: { ...k, hasOr: true } };
32380
+ if (["first", "select", "pluck", "then", "limit", "orderBy", "returning", "count", "join", "leftJoin", "innerJoin", "offset"].includes(prop)) {
32381
+ const where = { conj: k.conds, or: [], unknown: k.hasOr ? "the query has an OR Thunder does not judge" : null };
32382
+ if (k._rec) return { knex: k, recs: [k._rec] };
32383
+ const v = this.makeLookup({ client: k.client, model: k.table, op: prop, kind: "read", where, st, ctx, line });
32384
+ k._rec = v.recs[0];
32385
+ return { knex: k, ...v };
32386
+ }
32387
+ if (["update", "del", "delete", "increment", "decrement"].includes(prop)) {
32388
+ const where = { conj: k.conds, or: [], unknown: k.hasOr ? "the query has an OR Thunder does not judge" : null };
32389
+ return this.makeLookup({ client: k.client, model: k.table, op: prop, kind: "change", where, st, ctx, line });
32390
+ }
32391
+ if (prop === "insert") return {};
32392
+ return { knex: k };
32393
+ }
32394
+ mongooseOp({ model }, op, args, st, ctx, line) {
32395
+ const kind = MONGOOSE_OPS.get(op) === "write" ? "change" : "read";
32396
+ let where;
32397
+ if (/ById/.test(op)) where = { conj: [{ col: "_id", val: args[0] ?? {} }], or: [], unknown: null };
32398
+ else where = this.whereFromObject(args[0]);
32399
+ return this.makeLookup({ client: { label: model }, model, op, kind, where, st, ctx, line });
32400
+ }
32401
+ // Raw SQL from a string, a template, or sql`…`. Conditions after WHERE are read as col = value.
32402
+ rawSql(client, args, st, ctx, line, forceKind = null) {
32403
+ const q = args[0] ?? {};
32404
+ let text2 = null;
32405
+ const holes = [];
32406
+ if (typeof q.lit === "string") text2 = q.lit;
32407
+ else if (q.tpl) text2 = q.tpl.parts.map((p) => p.text != null ? p.text : (holes.push(p.val), `\0${holes.length - 1}\0`)).join("");
32408
+ else if (q.sqlText != null) {
32409
+ text2 = q.sqlText;
32410
+ holes.push(...q.sqlHoles);
32411
+ }
32412
+ const params = args[1]?.arr ?? args.slice(1);
32413
+ if (text2 == null) {
32414
+ const v = joinAll(args.map(dataOf));
32415
+ if (!hasData(v)) return {};
32416
+ const rec = this.newRec({ model: null, op: "sql", kind: "read", file: ctx.file, line, keyed: v.input?.[0] ? { says: v.input[0].says } : null, unknownWhere: "the SQL text is built at run time, so Thunder cannot read its WHERE" });
32417
+ return { recs: [rec] };
32418
+ }
32419
+ const kindWord = (text2.match(/^\s*(\w+)/)?.[1] ?? "").toUpperCase();
32420
+ const kind = forceKind ?? (kindWord === "UPDATE" || kindWord === "DELETE" ? "change" : kindWord === "INSERT" ? "create" : "read");
32421
+ if (kind === "create") return {};
32422
+ const table = text2.match(/\b(?:from|update|into)\s+["`[]?(\w+)/i)?.[1] ?? null;
32423
+ const whereText = text2.split(/\bwhere\b/i)[1]?.split(/\b(order\s+by|group\s+by|limit|returning|offset)\b/i)[0] ?? "";
32424
+ const where = { conj: [], or: [], unknown: null };
32425
+ if (/\bor\b/i.test(whereText)) where.unknown = "the WHERE has an OR Thunder does not judge";
32426
+ let qIndex = 0;
32427
+ const re = /([\w."`[\]]+)\s*=\s*(\$(\d+)|\?|:(\w+)|@(\w+)|\u0000(\d+)\u0000)/g;
32428
+ for (const m of whereText.matchAll(re)) {
32429
+ const col = m[1].replace(/["`[\]]/g, "").split(".").pop();
32430
+ let val = {};
32431
+ if (m[3]) val = params[Number(m[3]) - 1] ?? {};
32432
+ else if (m[2] === "?") val = params[qIndex++] ?? {};
32433
+ else if (m[6] != null) val = holes[Number(m[6])] ?? {};
32434
+ else if (m[4] || m[5]) {
32435
+ const o = params[0];
32436
+ val = o?.obj?.get(m[4] ?? m[5]) ?? {};
32437
+ }
32438
+ where.conj.push({ col, val });
32439
+ }
32440
+ return this.makeLookup({ client, model: table, op: "sql", kind, where, st, ctx, line });
32441
+ }
32442
+ tagged(e, st, ctx) {
32443
+ const tag = this.expr(e.tag, st, ctx);
32444
+ const parts = e.tpl.parts.map((p) => p.expr ? this.expr(p.expr, st, ctx) : null);
32445
+ const tplVal = { tpl: { parts: e.tpl.parts.map((p, i) => p.expr ? { val: parts[i] } : { text: p.text }) } };
32446
+ const name = e.tag.type === "Id" ? e.tag.name : e.tag.prop;
32447
+ if (tag.isDb || name === "sql" || /^\$(queryRaw|executeRaw)$/.test(name ?? "") || e.tag.type === "Member" && this.expr(e.tag.object, cloneState(st), ctx).isDb) {
32448
+ const text2 = e.tpl.parts.map((p, i) => p.expr ? `\0${i}\0` : p.text).join("");
32449
+ if (/^\s*(select|update|delete|insert|with)\b/i.test(text2)) return this.rawSql(tag.isDb ?? { label: name }, [tplVal], st, ctx, e.line, /^\$executeRaw$/.test(name ?? "") ? "change" : null);
32450
+ const holes = parts.map((p) => p ?? {});
32451
+ const conj = [];
32452
+ const re = /([\w."`]+)?\s*\u0000(\d+)\u0000\s*=\s*\u0000(\d+)\u0000|([\w."`]+)\s*=\s*\u0000(\d+)\u0000/g;
32453
+ for (const m of text2.matchAll(re)) {
32454
+ if (m[2] != null) {
32455
+ const hole = e.tpl.parts[Number(m[2])]?.expr;
32456
+ const r = holes[Number(m[3])];
32457
+ conj.push({ col: hole?.type === "Member" ? hole.prop : "?", val: r });
32458
+ } else conj.push({ col: m[4].replace(/["`]/g, "").split(".").pop(), val: holes[Number(m[5])] });
32459
+ }
32460
+ return { cond: { op: "raw", where: { conj, or: [], unknown: /\bor\b/i.test(text2) ? "the condition has an OR Thunder does not judge" : null } } };
32461
+ }
32462
+ return joinAll(parts.filter(Boolean).map(dataOf));
32463
+ }
32464
+ // ── Sinks ──
32465
+ sink(kind, val, st, ctx, line, says, status) {
32466
+ if (!ctx.route) return;
32467
+ if (typeof status === "number" && status >= 400 && kind === "response") return;
32468
+ ctx.route.sinks.push({ kind, val, state: cloneState(st), file: ctx.file, line, says });
32469
+ }
32470
+ };
32471
+ var DRIZZLE_OPS = /* @__PURE__ */ new Set(["eq", "and", "or", "inArray"]);
32472
+ var baseCall = Analyzer.prototype.call;
32473
+ Analyzer.prototype.call = function call(e, st, ctx) {
32474
+ if (e.callee.type === "Id" && DRIZZLE_OPS.has(e.callee.name)) {
32475
+ const f = this.lookup(e.callee.name, st, ctx, e.line);
32476
+ if (f.global || f.pkg?.startsWith("drizzle-orm") || f.opaque) {
32477
+ const args = e.args.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
32478
+ if (e.callee.name === "eq") return { cond: { op: "eq", col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
32479
+ if (e.callee.name === "inArray") return { cond: { op: "eq", col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
32480
+ return { cond: { op: e.callee.name, args }, ...joinAll(args.map(dataOf)) };
32481
+ }
32482
+ }
32483
+ return baseCall.call(this, e, st, ctx);
32484
+ };
32485
+ function columnOf(node, val) {
32486
+ if (node?.type === "Member" && node.prop) return node.prop;
32487
+ return val?.column ?? "?";
32488
+ }
32489
+ function walkAll(node, visit) {
32490
+ if (!node || typeof node !== "object") return;
32491
+ if (Array.isArray(node)) {
32492
+ for (const x of node) walkAll(x, visit);
32493
+ return;
32494
+ }
32495
+ if (node.type) visit(node);
32496
+ for (const [k, v] of Object.entries(node)) if (k !== "line" && v && typeof v === "object") walkAll(v, visit);
32497
+ }
32498
+ function nextRoutePath(file) {
32499
+ const m = file.match(/(?:^|\/)app\/(.*)\/route\.(?:ts|js|mts|tsx)$/);
32500
+ if (!m) return null;
32501
+ return "/" + m[1].split("/").filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@")).map((s) => s.replace(/^\[\.\.\.(.+)\]$/, "*$1").replace(/^\[(.+)\]$/, ":$1")).join("/");
32502
+ }
32503
+ function pagesApiPath(file) {
32504
+ const m = file.match(/(?:^|\/)pages\/(api\/.*)\.(?:ts|js)$/);
32505
+ if (!m) return null;
32506
+ return "/" + m[1].replace(/\/index$/, "").split("/").map((s) => s.replace(/^\[(.+)\]$/, ":$1")).join("/");
32507
+ }
32508
+ function findRoutes(project) {
32509
+ const routes = [];
32510
+ for (const m of project.files.values()) {
32511
+ const uses = [];
32512
+ walkAll(m.ast.body, (n) => {
32513
+ if (n.type !== "Call" || n.callee.type !== "Member") return;
32514
+ const prop = n.callee.prop;
32515
+ const recv = n.callee.object;
32516
+ const recvName = recv.type === "Id" ? recv.name : recv.type === "Member" ? recv.prop : null;
32517
+ if (prop === "use") {
32518
+ uses.push({ recv: recvName, line: n.line, args: n.args });
32519
+ return;
32520
+ }
32521
+ if (prop === "route" && n.args[0]?.type === "Obj") {
32522
+ const o = new Map(n.args[0].props.map((p) => [p.key, p.value]));
32523
+ const method = o.get("method"), url = o.get("url") ?? o.get("path"), handler2 = o.get("handler");
32524
+ if (url?.type === "Lit" && handler2) routes.push({ framework: "fastify", method: String(method?.value ?? "GET").toUpperCase(), path: url.value, file: m.path, line: n.line, handler: handler2, middleware: [o.get("preHandler"), o.get("onRequest"), o.get("preValidation")].filter(Boolean).flatMap((x) => x.type === "Arr" ? x.elems : [x]), recv: recvName });
32525
+ return;
32526
+ }
32527
+ if (!METHODS.has(prop) || !n.args.length) return;
32528
+ const first = n.args[0];
32529
+ const path = first.type === "Lit" && typeof first.value === "string" ? first.value : first.type === "Tpl" && first.parts.length === 1 ? first.parts[0].text : null;
32530
+ if (path == null || !(path.startsWith("/") || path === "" || path === "*")) return;
32531
+ if (n.args.length < 2) return;
32532
+ const handler = n.args[n.args.length - 1];
32533
+ const middle = n.args.slice(1, -1);
32534
+ const opts = middle.find((x) => x.type === "Obj");
32535
+ const mw = middle.filter((x) => x.type !== "Obj").flatMap((x) => x.type === "Arr" ? x.elems.filter(Boolean) : [x]);
32536
+ if (opts) {
32537
+ for (const p of opts.props) if (["preHandler", "onRequest", "preValidation"].includes(p.key)) mw.push(...p.value.type === "Arr" ? p.value.elems.filter(Boolean) : [p.value]);
32538
+ }
32539
+ const framework = handler.type === "Arrow" && handler.params.length === 1 && /^c$|^ctx$|^context$/.test(handler.params[0].name ?? "") ? "hono" : opts || /fastify|server|instance/i.test(recvName ?? "") ? "fastify" : "express";
32540
+ routes.push({ framework, method: prop === "del" ? "DELETE" : prop.toUpperCase(), path, file: m.path, line: n.line, handler, middleware: mw, recv: recvName });
32541
+ });
32542
+ for (const r of routes) if (r.file === m.path) r.uses = uses.filter((u) => u.recv === r.recv && u.line < r.line && (!u.args[0] || u.args[0].type !== "Lit" || r.path.startsWith(u.args[0].value)));
32543
+ const nextPath = nextRoutePath(m.path);
32544
+ if (nextPath) {
32545
+ for (const [exported, local] of m.exports) {
32546
+ if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(exported) || typeof local !== "string") continue;
32547
+ const b = m.bindings.get(local);
32548
+ if (!b) continue;
32549
+ const handler = b.kind === "fn" ? b.node : b.node;
32550
+ routes.push({ framework: "next", method: exported, path: nextPath, file: m.path, line: handler?.line ?? 1, handler, middleware: [], uses: [] });
32551
+ }
32552
+ }
32553
+ const apiPath = pagesApiPath(m.path);
32554
+ if (apiPath && m.exports.has("default")) {
32555
+ const local = m.exports.get("default");
32556
+ const b = typeof local === "string" ? m.bindings.get(local) : null;
32557
+ if (b?.node) routes.push({ framework: "next-pages", method: "ANY", path: apiPath, file: m.path, line: b.node.line ?? 1, handler: b.node, middleware: [], uses: [] });
32558
+ }
32559
+ }
32560
+ return routes;
32561
+ }
32562
+ function analyzeRoute(an, project, r) {
32563
+ const m = project.files.get(r.file);
32564
+ const route = { sinks: [] };
32565
+ const ctx = { file: r.file, depth: 0, route, returnsSend: false };
32566
+ const st = newState(new Scope(m.scope), { returns: [] });
32567
+ const notes = [];
32568
+ const reqName = (fn) => {
32569
+ const p = fn?.params?.[0];
32570
+ return p?.type === "Id" ? p.name : "req";
32571
+ };
32572
+ const handlerVal = r.handler.type === "Arrow" || r.handler.type === "Function" ? { fn: { node: r.handler, scope: st.scope, file: r.file, name: "the handler" } } : an.expr(r.handler, st, ctx);
32573
+ let handlerFn = handlerVal.fn ?? null;
32574
+ let wrapperName = null;
32575
+ if (!handlerFn && r.handler.type === "Call") {
32576
+ const inner = r.handler.args.find((a) => a.type === "Arrow") ?? null;
32577
+ const calleeName = r.handler.callee.type === "Id" ? r.handler.callee.name : r.handler.callee.prop;
32578
+ wrapperName = calleeName;
32579
+ if (inner) handlerFn = { node: inner, scope: st.scope, file: r.file, name: "the handler" };
32580
+ else if (r.handler.args[0]) {
32581
+ const v = an.expr(r.handler.args[0], st, ctx);
32582
+ handlerFn = v.fn ?? null;
32583
+ }
32584
+ }
32585
+ if (!handlerFn) return { verdict: null, paths: [], identity: null, why: `the handler (${r.handler.type === "Id" ? r.handler.name : "an expression"}) could not be found in these files`, stopped: true };
32586
+ const node = handlerFn.node;
32587
+ const fw = r.framework;
32588
+ const args = [];
32589
+ if (fw === "hono") args.push({ ctx: true });
32590
+ else if (fw === "next") {
32591
+ args.push({ isReq: { name: reqName(node) } });
32592
+ args.push({ obj: /* @__PURE__ */ new Map([["params", { isParams: true }]]), isParamsCtx: true });
32593
+ } else {
32594
+ args.push({ isReq: { name: reqName(node) } });
32595
+ const resP = node.params?.[1];
32596
+ args.push({ isRes: { name: resP?.type === "Id" ? resP.name : "res", status: null } });
32597
+ args.push({ reqNext: true });
32598
+ }
32599
+ if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName) && !MAYBE_GUARD_MIDDLEWARE.test(wrapperName)) {
32600
+ const usual = fw === "hono" ? 1 : fw === "next" ? 2 : 3;
32601
+ for (let i = usual; i < (node.params?.length ?? 0); i++) args[i] = { ident: [{ says: `the caller from ${wrapperName}`, file: r.file, line: r.line, field: null }] };
32602
+ if (fw === "next") for (let i = 1; i < usual; i++) args[i] = args[i] ?? {};
32603
+ }
32604
+ const mwNodes = [...(r.uses ?? []).flatMap((u) => u.args.filter((a) => !(a.type === "Lit"))), ...r.middleware ?? []];
32605
+ if (wrapperName && (MAYBE_GUARD_MIDDLEWARE.test(wrapperName) || !AUTH_MIDDLEWARE.test(wrapperName)) && !/^(async|asyncHandler|catchAsync|wrap|handler|tryCatch|withErrorHandling|errorHandler|withErrors|safe)$/i.test(wrapperName)) {
32606
+ const wv = an.lookup(wrapperName, st, ctx, r.line);
32607
+ if (!wv.fn) st.unresolved.push({ says: `${wrapperName}(\u2026)`, why: `the handler is wrapped in ${wrapperName}, which is not in these files`, file: r.file, line: r.line });
32608
+ } else if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName)) st.identity = { says: `${wrapperName}(\u2026)`, file: r.file, line: r.line };
32609
+ let s = st;
32610
+ for (const mwNode of mwNodes) {
32611
+ const label = mwNode.type === "Id" ? mwNode.name : mwNode.type === "Call" ? mwNode.callee.type === "Id" ? mwNode.callee.name : `${mwNode.callee.object?.name ?? ""}.${mwNode.callee.prop}` : mwNode.type === "Member" ? `${mwNode.object?.name ?? ""}.${mwNode.prop}` : "a middleware";
32612
+ const base2 = label.split(".").pop();
32613
+ if (BENIGN_MIDDLEWARE.test(label) || BENIGN_MIDDLEWARE.test(base2)) continue;
32614
+ const roleish = ROLE_FN.test(base2) || /admin|role|permission|scope/i.test(label);
32615
+ const v = mwNode.type === "Arrow" ? { fn: { node: mwNode, scope: st.scope, file: r.file, name: "a middleware" } } : an.expr(mwNode, s, ctx);
32616
+ if (v.fn && (v.fn.node.params?.length ?? 0) >= 2) {
32617
+ const mctx = { ...ctx, depth: 1 };
32618
+ const ms = cloneState(s);
32619
+ ms.calledNext = false;
32620
+ try {
32621
+ an.callFunction(v.fn, args, ms, mctx, mwNode.line);
32622
+ if (ms.calledNext) {
32623
+ ms.calledNext = false;
32624
+ s = ms;
32625
+ } else s.unresolved.push({ says: `${label}`, why: `the middleware ${label} never visibly calls next()`, file: r.file, line: mwNode.line });
32626
+ } catch (err) {
32627
+ if (err.limit) throw err;
32628
+ s.unresolved.push({ says: `${label}`, why: `Thunder could not follow the middleware ${label}`, file: r.file, line: mwNode.line });
32629
+ }
32630
+ if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
32631
+ if (roleish && !s.role) s.role = { says: label, file: r.file, line: mwNode.line };
32632
+ continue;
32633
+ }
32634
+ if (roleish) {
32635
+ if (!s.role) s.role = { says: label, file: r.file, line: mwNode.line };
32636
+ if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
32637
+ continue;
32638
+ }
32639
+ if (MAYBE_GUARD_MIDDLEWARE.test(label)) {
32640
+ s.unresolved.push({ says: label, why: `the route runs ${label} first, which may check access, and it is not in these files`, file: r.file, line: mwNode.line });
32641
+ continue;
32642
+ }
32643
+ if (AUTH_MIDDLEWARE.test(label)) {
32644
+ if (!s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
32645
+ continue;
32646
+ }
32647
+ s.unresolved.push({ says: label, why: `the route runs ${label} first, and Thunder cannot see what it checks`, file: r.file, line: mwNode.line });
32648
+ }
32649
+ ctx.returnsSend = fw === "fastify" || fw === "hono" && false;
32650
+ const hctx = { ...ctx, depth: 0, returnsSend: ctx.returnsSend };
32651
+ const frame = { returns: [] };
32652
+ const hs = cloneState(s);
32653
+ hs.scope = new Scope(handlerFn.scope);
32654
+ hs.frame = frame;
32655
+ (node.params ?? []).forEach((p, i) => an.bindPattern(p, args[i] ?? {}, hs.scope, hs, hctx, true));
32656
+ if (node.body?.type === "Block") an.block(node.body.body, hs, hctx);
32657
+ else if (node.body) {
32658
+ const v = an.expr(node.body, hs, hctx);
32659
+ if (hctx.returnsSend) an.sink("response", v, hs, hctx, node.line, "gives it back as the response");
32660
+ }
32661
+ return { route, notes };
32662
+ }
32663
+ function judgePath(sink, rec) {
32664
+ const st = sink.state;
32665
+ const steps = [];
32666
+ const at2 = (x) => ({ file: x.file ?? sink.file, line: x.line ?? null });
32667
+ if (rec.keyed) steps.push({ kind: "input", says: `takes ${rec.keyed.says.replace(/^.* = /, "")} from the request`, ...at2(rec.keyed) });
32668
+ steps.push(st.identity ? { kind: "identity", says: `knows the caller from ${st.identity.says}`, ...at2(st.identity) } : { kind: "identity", says: "no sign-in seen on this path", file: sink.file, line: null });
32669
+ steps.push({ kind: rec.kind === "change" ? "change" : "lookup", says: `${rec.kind === "change" ? "changes" : "reads"} ${rec.model ?? "a record"} with ${rec.op}${rec.keyed ? ` where ${rec.keyed.says}` : ""}${rec.scoped ? ` and ${rec.scoped.says}` : ""}`, file: rec.file, line: rec.line });
32670
+ const respond = { kind: sink.kind === "change" ? "change" : "response", says: sink.says, file: sink.file, line: sink.line };
32671
+ const result = (verdict, why, guard) => {
32672
+ if (guard) steps.push({ kind: "guard", says: guard.says, file: guard.file ?? rec.file, line: guard.line ?? rec.line });
32673
+ if (sink.kind !== "change") steps.push(respond);
32674
+ return { verdict, why, steps, record: rec.model ?? null, lines: [...new Set(steps.map((x) => x.line).filter(Boolean))].sort((x, y) => x - y) };
32675
+ };
32676
+ if (!rec.keyed && rec.byIdentity) return result("guarded", `the record is chosen by the caller (${rec.byIdentity.says}), not by the request`);
32677
+ if (rec.scoped) return result("guarded", `the lookup is limited to the caller: ${rec.scoped.says}`, { says: `limits it to the caller: ${rec.scoped.says}`, file: rec.file, line: rec.line });
32678
+ const g = st.guards.get(rec.id) ?? (rec.keyed?.value ? st.guards.get(`key:${rec.keyed.value}`) : null);
32679
+ if (g) return result("guarded", `${g.says} before ${sink.kind === "change" ? "changing it" : "answering"}`, g);
32680
+ if (!rec.keyed && !rec.unknownWhere) return null;
32681
+ if (rec.clientScoped) return result("cannot tell", `it uses a database client made for the caller (${rec.clientScoped.says}); Thunder cannot see whether it filters by tenant`);
32682
+ if (rec.unknownWhere) return result("cannot tell", rec.unknownWhere);
32683
+ if (st.unresolved.length) {
32684
+ const u = st.unresolved[0];
32685
+ return result("cannot tell", `${u.why} (${u.file}, line ${u.line})${st.unresolved.length > 1 ? `, and ${st.unresolved.length - 1} more` : ""}`);
32686
+ }
32687
+ if (st.role) return result("cannot tell", `only callers who pass ${st.role.says} reach it; whether they may see every tenant's records is a rule Thunder cannot check`);
32688
+ return result("unguarded", `no step between the request and the ${sink.kind === "change" ? "change" : "response"} limits ${rec.model ?? "the record"} to the caller`);
32689
+ }
32690
+ function judgeUnknown(sink, u) {
32691
+ const st = sink.state;
32692
+ const steps = [
32693
+ { kind: "stopped", says: `${u.says} could not be followed: ${u.why}`, file: u.file, line: u.line },
32694
+ { kind: "response", says: sink.says, file: sink.file, line: sink.line }
32695
+ ];
32696
+ if (st.identity) steps.unshift({ kind: "identity", says: `knows the caller from ${st.identity.says}`, file: st.identity.file, line: st.identity.line });
32697
+ return { verdict: "cannot tell", why: `it answers with what ${u.says} gives back, and ${u.why}`, steps, record: null, lines: [u.line, sink.line] };
32698
+ }
32699
+ var RANK = { unguarded: 3, "cannot tell": 2, guarded: 1 };
32700
+ function accessFlow(files, { maxRoutes = 2e3 } = {}) {
32701
+ const project = new Project(files);
32702
+ const routes = findRoutes(project).slice(0, maxRoutes);
32703
+ const out = [];
32704
+ for (const r of routes) {
32705
+ const an = new Analyzer(project);
32706
+ let res;
32707
+ try {
32708
+ res = analyzeRoute(an, project, r);
32709
+ } catch (err) {
32710
+ if (!err.limit) throw err;
32711
+ out.push({ method: r.method, path: r.path, framework: r.framework, file: r.file, line: r.line, verdict: "cannot tell", why: `Thunder stopped: the route is larger than it follows (${MAX_WORK} steps)`, identity: null, paths: [] });
32712
+ continue;
32713
+ }
32714
+ if (res.stopped) {
32715
+ out.push({ method: r.method, path: r.path, framework: r.framework, file: r.file, line: r.line, verdict: null, why: res.why, identity: null, paths: [] });
32716
+ continue;
32717
+ }
32718
+ const paths = [];
32719
+ const seen = /* @__PURE__ */ new Set();
32720
+ for (const sink of res.route.sinks) {
32721
+ for (const rec of sink.val.recs ?? []) {
32722
+ if (rec.kind === "create") continue;
32723
+ const key = `${rec.id}@${sink.line}`;
32724
+ if (seen.has(key)) continue;
32725
+ seen.add(key);
32726
+ const p = judgePath(sink, rec);
32727
+ if (p) paths.push(p);
32728
+ }
32729
+ if (!(sink.val.recs ?? []).some((rc) => rc.keyed || rc.unknownWhere)) {
32730
+ for (const u of sink.val.unknown ?? []) {
32731
+ const key = `${u.file}:${u.line}@${sink.line}`;
32732
+ if (seen.has(key)) continue;
32733
+ seen.add(key);
32734
+ paths.push(judgeUnknown(sink, u));
32735
+ }
32736
+ }
32737
+ }
32738
+ paths.sort((a, b) => RANK[b.verdict] - RANK[a.verdict]);
32739
+ const worst = paths[0]?.verdict ?? null;
32740
+ const identity = res.route.sinks.map((x) => x.state.identity).find(Boolean) ?? null;
32741
+ out.push({
32742
+ method: r.method,
32743
+ path: r.path,
32744
+ framework: r.framework,
32745
+ file: r.file,
32746
+ line: r.line,
32747
+ verdict: worst,
32748
+ why: worst ? paths[0].why : "it reads or changes no stored record chosen by the request",
32749
+ identity: identity ? { says: identity.says, file: identity.file, line: identity.line } : null,
32750
+ paths
32751
+ });
32752
+ }
32753
+ const count = (v) => out.filter((x) => x.verdict === v).length;
32754
+ return {
32755
+ schema: ACCESS_SCHEMA,
32756
+ routes: out,
32757
+ summary: { routes: out.length, guarded: count("guarded"), unguarded: count("unguarded"), cannotTell: count("cannot tell"), noLookup: count(null) },
32758
+ unread: project.failures
32759
+ };
32760
+ }
32761
+ function ownershipWords(route) {
32762
+ if (!route || !route.verdict) return null;
32763
+ if (route.verdict === "guarded") {
32764
+ const g = route.paths.flatMap((p) => p.steps).find((s) => s.kind === "guard");
32765
+ return `Ownership: checked${g?.line ? ` (line ${g.line})` : ""}: ${route.paths[0].why}`;
32766
+ }
32767
+ if (route.verdict === "unguarded") return `No ownership check on this path (lines ${route.paths[0].lines.join(", ")}): ${route.paths[0].why}`;
32768
+ return `Ownership: Thunder cannot tell: ${route.paths[0].why}`;
32769
+ }
32770
+
29789
32771
  // src/model.mjs
29790
32772
  var MODEL_SCHEMA = "thunder-model-v1";
29791
32773
  var THING_LANGUAGES = ["python", "typescript", "javascript", "java", "csharp", "kotlin", "php", "go", "rust", "ruby", "sql", "c", "cpp", "swift", "r", "powershell"];
@@ -29804,6 +32786,7 @@ function startValue(expr, params = {}) {
29804
32786
  if (/^(True|true)$/.test(e)) return "yes at first";
29805
32787
  if (/^(False|false)$/.test(e)) return "no at first";
29806
32788
  if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
32789
+ if (/^-?\d+(\.\d+)?(?:[mMfFdDlL]|[uU][lL]?|[lL][uU])$/.test(e)) return `${e.replace(/[a-zA-Z]+$/, "")} at first`;
29807
32790
  if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes2(e)}" at first`;
29808
32791
  const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/) || e.match(/^(?:[A-Z]\w*)?\.([a-z]\w*)$/);
29809
32792
  if (en) return `${words10(en[1])} at first`;
@@ -30347,7 +33330,7 @@ function youGiveOf(item2) {
30347
33330
  }
30348
33331
  return given;
30349
33332
  }
30350
- var dirOf2 = (p) => String(p).includes("/") ? String(p).slice(0, String(p).lastIndexOf("/")) : "";
33333
+ var dirOf3 = (p) => String(p).includes("/") ? String(p).slice(0, String(p).lastIndexOf("/")) : "";
30351
33334
  function resolveAcrossFiles(pending, things, links, linkKeys) {
30352
33335
  const add2 = (p, to) => {
30353
33336
  const key = `${p.from}>${to}>${p.l.kind}>${p.l.line}`;
@@ -30357,13 +33340,13 @@ function resolveAcrossFiles(pending, things, links, linkKeys) {
30357
33340
  }
30358
33341
  };
30359
33342
  const resources = things.filter((t) => t.kind === "resource" && t.address);
30360
- const byDirAddr = new Map(resources.map((t) => [`${dirOf2(t.file)}|${t.address}`, t.id]));
33343
+ const byDirAddr = new Map(resources.map((t) => [`${dirOf3(t.file)}|${t.address}`, t.id]));
30361
33344
  const byAddr = /* @__PURE__ */ new Map();
30362
33345
  for (const t of resources) byAddr.set(t.address, [...byAddr.get(t.address) ?? [], t]);
30363
33346
  const oneDir = (hits, dir) => {
30364
- const here = hits.filter((t) => dirOf2(t.file) === dir);
33347
+ const here = hits.filter((t) => dirOf3(t.file) === dir);
30365
33348
  if (here.length) return here;
30366
- return new Set(hits.map((t) => dirOf2(t.file))).size === 1 ? hits : [];
33349
+ return new Set(hits.map((t) => dirOf3(t.file))).size === 1 ? hits : [];
30367
33350
  };
30368
33351
  for (const p of pending) {
30369
33352
  const to = p.l.to;
@@ -30511,14 +33494,14 @@ function thunderModel(files, { name = "app" } = {}) {
30511
33494
  if (from && to && !linkKeys.has(key)) {
30512
33495
  linkKeys.add(key);
30513
33496
  links.push({ from, to, kind: l.kind, file: l.file, line: l.line });
30514
- } else if (from && !to && (language === "terraform" || language === "kubernetes" || language === "docker-compose")) pending.push({ dir: dirOf2(f.path), from, l, language });
33497
+ } else if (from && !to && (language === "terraform" || language === "kubernetes" || language === "docker-compose")) pending.push({ dir: dirOf3(f.path), from, l, language });
30515
33498
  }
30516
33499
  }
30517
33500
  }
30518
33501
  if (pending.length) resolveAcrossFiles(pending, things, links, linkKeys);
30519
33502
  const dockerImages = things.filter((t) => t.resourceType === "docker-image");
30520
33503
  for (const t of things) for (const im of t.images ?? []) {
30521
- const hits = dockerImages.filter((d) => dirOf2(d.address.slice("image:".length)).split("/").pop() === im.name);
33504
+ const hits = dockerImages.filter((d) => dirOf3(d.address.slice("image:".length)).split("/").pop() === im.name);
30522
33505
  const key = hits.length === 1 && `${t.id}>${hits[0].id}>uses>${im.line}`;
30523
33506
  if (key && !linkKeys.has(key)) {
30524
33507
  linkKeys.add(key);
@@ -30585,6 +33568,20 @@ function thunderModel(files, { name = "app" } = {}) {
30585
33568
  } catch (e) {
30586
33569
  unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` });
30587
33570
  }
33571
+ const routeMembers = members.filter((m) => m.route && /^(typescript|javascript)$/i.test(m.language ?? ""));
33572
+ if (routeMembers.length) {
33573
+ try {
33574
+ const access = accessFlow(files.filter((f) => /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(f.path)));
33575
+ for (const r of access.routes) {
33576
+ if (!r.verdict) continue;
33577
+ const m = routeMembers.find((x) => x.file === r.file && x.route === `${r.method} ${r.path}`) ?? routeMembers.find((x) => x.file === r.file && Math.abs((x.lines?.[0] ?? 0) - r.line) <= 2);
33578
+ if (m) m.ownership = { verdict: r.verdict, says: ownershipWords(r), why: r.why, paths: r.paths };
33579
+ }
33580
+ model.access = { schema: access.schema, summary: access.summary };
33581
+ } catch (e) {
33582
+ unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Ownership on routes could not be checked: ${e.message}` });
33583
+ }
33584
+ }
30588
33585
  return model;
30589
33586
  }
30590
33587
  function flowLines(flow, depth = 1, note = null, full = false) {
@@ -30659,6 +33656,7 @@ function modelText(model, id, { note = null, full = false } = {}) {
30659
33656
  const lines = [`${m.label}${owner && m.kind !== "setup" ? ` (${owner.label})` : ""}${m.kind === "rule" ? ": a rule" : ""}`];
30660
33657
  if (m.when) lines.push(` ${m.when}`);
30661
33658
  else if (m.route) lines.push(` When someone calls ${m.route}`);
33659
+ if (m.ownership) lines.push(` ${m.ownership.says}`);
30662
33660
  if (m.doc) lines.push(` Author's note: ${m.doc}`);
30663
33661
  if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(", ")}`);
30664
33662
  if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
@@ -30671,7 +33669,7 @@ function modelText(model, id, { note = null, full = false } = {}) {
30671
33669
  var SAME_SCHEMA = "thunder-same-v1";
30672
33670
  var MAX_CASES = 4096;
30673
33671
  var nameKey = (name) => String(name).replace(/[_\s-]/g, "").toLowerCase();
30674
- var norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
33672
+ var norm2 = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
30675
33673
  var stemKey = (path) => nameKey(String(path).replace(/\.[^./]+$/, "").replace(/\\/g, "/"));
30676
33674
  function compact(it, key, file, language) {
30677
33675
  const base2 = { key, file, language, name: it.name, kind: it.kind, line: it.line, route: it.route, element: visualFor(it).element };
@@ -30768,7 +33766,7 @@ function stepSignature(code3) {
30768
33766
  return toks.filter((x) => !SYNTAX.has(x)).map((x) => OPS4[x] ?? (/^["'`]/.test(x) ? `"${x.slice(1, -1)}"` : /^[A-Za-z_$]/.test(x) ? x.replace(/[_$]/g, "").toLowerCase() : x)).join(" ");
30769
33767
  }
30770
33768
  var flatSteps = (steps, depth = 0) => (steps || []).flatMap((s) => [
30771
- { sig: `${depth}:${s.restates ? "code" : s.kind}:${s.restates || s.kind === "other" ? "" : norm(s.says)}`, code: stepSignature(s.code), raw: String(s.code ?? ""), text: s.restates || s.kind === "other" ? `\`${s.code ?? s.says}\`` : s.says },
33769
+ { sig: `${depth}:${s.restates ? "code" : s.kind}:${s.restates || s.kind === "other" ? "" : norm2(s.says)}`, code: stepSignature(s.code), raw: String(s.code ?? ""), text: s.restates || s.kind === "other" ? `\`${s.code ?? s.says}\`` : s.says },
30772
33770
  ...flatSteps(s.children, depth + 1)
30773
33771
  ]);
30774
33772
  function compareItems(o, n) {
@@ -33090,7 +36088,7 @@ function nearName(word, options) {
33090
36088
  const sorted = (w) => [...w].sort().join("");
33091
36089
  return closest(word, options) ?? options.find((o) => o.length === word.length && sorted(o) === sorted(word)) ?? null;
33092
36090
  }
33093
- var Scope = class {
36091
+ var Scope2 = class {
33094
36092
  constructor(parent, kind) {
33095
36093
  this.parent = parent;
33096
36094
  this.kind = kind;
@@ -33110,7 +36108,7 @@ var Checker = class {
33110
36108
  constructor(program) {
33111
36109
  this.p = program;
33112
36110
  this.d = [];
33113
- this.global = new Scope(null, "global");
36111
+ this.global = new Scope2(null, "global");
33114
36112
  this.records = /* @__PURE__ */ new Map();
33115
36113
  this.funcs = /* @__PURE__ */ new Map();
33116
36114
  this.rules = [];
@@ -33172,7 +36170,7 @@ var Checker = class {
33172
36170
  for (const s of top) if (s.k === "test") {
33173
36171
  s.py = `test_${pyName(s.title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim() || "unnamed")}`.replace(/_+$/, "");
33174
36172
  this.uniqueTestName(s);
33175
- const sc = new Scope(this.global, "test");
36173
+ const sc = new Scope2(this.global, "test");
33176
36174
  this.block(s.body, sc, { inTest: true });
33177
36175
  this.info.tests.push(s);
33178
36176
  }
@@ -33181,7 +36179,7 @@ var Checker = class {
33181
36179
  const first = this.info.screens[0];
33182
36180
  const needs = first ? first.params.filter((p) => !p.dflt) : [];
33183
36181
  if (needs.length) this.err("TC214", first.line, `"${first.text}" is the first screen, where the app starts, so nothing gives it ${needs.map((p) => p.text).join(", ")}.`, `Put the screen the app starts on first, or give ${needs.length === 1 ? "the input" : "each input"} a value for when it isn't given: Receive ${needs[0].text} (\u2026 if not given).`);
33184
- const main = new Scope(this.global, "main");
36182
+ const main = new Scope2(this.global, "main");
33185
36183
  this.mainScope = main;
33186
36184
  const mainBody = top.filter((s) => !["record", "func", "use", "keep", "never", "test", "screen"].includes(s.k));
33187
36185
  this.block(mainBody, main, {});
@@ -33264,7 +36262,7 @@ var Checker = class {
33264
36262
  this.err("TC201", rule.line, `"${rule.text}" watches "${subject}", but nothing in this program is called that.`);
33265
36263
  return;
33266
36264
  }
33267
- const sc = new Scope(this.global, "rule");
36265
+ const sc = new Scope2(this.global, "rule");
33268
36266
  const fieldType = fieldOf[0]?.fieldMap.get(subject).type ?? UNKNOWN;
33269
36267
  sc.vars.set(subject, { kind: "subject", py: "value", type: fieldType });
33270
36268
  this.ex(rule.cond, sc, {});
@@ -33291,7 +36289,7 @@ var Checker = class {
33291
36289
  return this.rules.filter((r) => r.watchesVar && r.subject === key);
33292
36290
  }
33293
36291
  checkFunc(f) {
33294
- const sc = new Scope(this.global, "func");
36292
+ const sc = new Scope2(this.global, "func");
33295
36293
  sc.func = f;
33296
36294
  f.gives = [];
33297
36295
  let sawDefault = false;
@@ -33367,7 +36365,7 @@ var Checker = class {
33367
36365
  return;
33368
36366
  case "each": {
33369
36367
  const it = this.ex(s.iter, sc);
33370
- const inner = new Scope(sc, "loop");
36368
+ const inner = new Scope2(sc, "loop");
33371
36369
  const [a, b] = s.vars;
33372
36370
  let ta = UNKNOWN, tb = UNKNOWN;
33373
36371
  if (it.k === "list") {
@@ -33395,7 +36393,7 @@ var Checker = class {
33395
36393
  const t = this.ex(e, sc);
33396
36394
  if (known(t) && t.k !== "whole") this.err("TC305", line, `"For each \u2026 from \u2026 to" counts in whole numbers, but this is ${typeWords4(t)}.`);
33397
36395
  }
33398
- const inner = new Scope(sc, "loop");
36396
+ const inner = new Scope2(sc, "loop");
33399
36397
  s.v.py = this.localPy(s.v.name, sc);
33400
36398
  inner.vars.set(s.v.name, { kind: "var", py: s.v.py, type: T("whole"), line });
33401
36399
  this.block(s.body, inner, ctx);
@@ -33459,7 +36457,7 @@ var Checker = class {
33459
36457
  return;
33460
36458
  case "tryFail": {
33461
36459
  this.stmt(s.stmt, sc, ctx);
33462
- const inner = new Scope(sc, "handler");
36460
+ const inner = new Scope2(sc, "handler");
33463
36461
  s.errPy = this.localPy("error", sc);
33464
36462
  inner.vars.set("error", { kind: "var", py: s.errPy, type: T("text"), line });
33465
36463
  this.block(s.handler, inner, ctx);
@@ -33496,7 +36494,7 @@ var Checker = class {
33496
36494
  return target;
33497
36495
  }
33498
36496
  checkScreen(s) {
33499
- const sc = new Scope(this.global, "screen");
36497
+ const sc = new Scope2(this.global, "screen");
33500
36498
  sc.screen = s;
33501
36499
  for (const p of s.params) {
33502
36500
  if (p.dflt) this.ex(p.dflt, this.global, {});
@@ -33542,7 +36540,7 @@ var Checker = class {
33542
36540
  case "list": {
33543
36541
  const it = this.ex(el.iter, sc);
33544
36542
  if (known(it) && it.k !== "list" && it.k !== "optional") this.err("TC305", line, `"Show a list" goes through a list, but this is ${typeWords4(it)}.`);
33545
- const inner = new Scope(sc, "loop");
36543
+ const inner = new Scope2(sc, "loop");
33546
36544
  el.v.py = pyName(el.v.name);
33547
36545
  inner.vars.set(el.v.name, { kind: "item", py: el.v.py, type: it.k === "list" ? it.of ?? UNKNOWN : UNKNOWN, line });
33548
36546
  this.elements(el.body, inner, screen);
@@ -33576,7 +36574,7 @@ var Checker = class {
33576
36574
  if (el.off) this.cond(el.off, sc);
33577
36575
  if (el.opens) this.screenRef(el.opens, line);
33578
36576
  if (el.press) {
33579
- const ps = new Scope(sc, "press");
36577
+ const ps = new Scope2(sc, "press");
33580
36578
  this.block(el.press.body, ps, { inPress: true });
33581
36579
  el.press.locals = [...ps.vars.values()].map((v) => v.py);
33582
36580
  }
@@ -36914,12 +39912,12 @@ function replacing(text2, old, nw) {
36914
39912
  const t = textOf3(text2, '"replacing"');
36915
39913
  return t.split(old).join(textOf3(nw, '"replacing \u2026 with"'));
36916
39914
  }
36917
- var PUNCT5 = new Set(Array.from(`.,;:!?"'()[]{}<>\u201C\u201D\u2018\u2019\u2026-`));
39915
+ var PUNCT6 = new Set(Array.from(`.,;:!?"'()[]{}<>\u201C\u201D\u2018\u2019\u2026-`));
36918
39916
  function stripPunct(w) {
36919
39917
  const a = Array.from(w);
36920
39918
  let i = 0, j = a.length;
36921
- while (i < j && PUNCT5.has(a[i])) i++;
36922
- while (j > i && PUNCT5.has(a[j - 1])) j--;
39919
+ while (i < j && PUNCT6.has(a[i])) i++;
39920
+ while (j > i && PUNCT6.has(a[j - 1])) j--;
36923
39921
  return a.slice(i, j).join("");
36924
39922
  }
36925
39923