@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/index.cjs CHANGED
@@ -86,6 +86,7 @@ __export(index_exports, {
86
86
  NODE_STATUSES: () => NODE_STATUSES,
87
87
  NODE_TYPES: () => NODE_TYPES,
88
88
  OUTCOME_SCHEMA: () => OUTCOME_SCHEMA,
89
+ PASSPORT_SCHEMA: () => PASSPORT_SCHEMA,
89
90
  PATCH_SCHEMA: () => PATCH_SCHEMA,
90
91
  PRIVACY_SCHEMA: () => PRIVACY_SCHEMA,
91
92
  PROMOTE_SCHEMA: () => PROMOTE_SCHEMA,
@@ -141,6 +142,7 @@ __export(index_exports, {
141
142
  WRITE_STEPS_LANGUAGES: () => WRITE_STEPS_LANGUAGES,
142
143
  WRITE_STEPS_SCHEMA: () => WRITE_STEPS_SCHEMA,
143
144
  acceptedRisks: () => acceptedRisks,
145
+ accessEvidence: () => accessEvidence,
144
146
  adoptRegion: () => adoptRegion,
145
147
  analyzeDecision: () => analyzeDecision,
146
148
  analyzeDistributed: () => analyzeDistributed,
@@ -152,6 +154,7 @@ __export(index_exports, {
152
154
  approvalFor: () => approvalFor,
153
155
  approvalsFor: () => approvalsFor,
154
156
  approveIntent: () => approveIntent,
157
+ assemblePassport: () => assemblePassport,
155
158
  atlasNode: () => atlasNode,
156
159
  autocorrectSource: () => autocorrectSource,
157
160
  backfillNodeField: () => backfillNodeField,
@@ -168,6 +171,7 @@ __export(index_exports, {
168
171
  buildLifecycle: () => buildLifecycle,
169
172
  buildManifest: () => buildManifest,
170
173
  buildMissionIndex: () => buildMissionIndex,
174
+ buildPassport: () => buildPassport,
171
175
  buildProof: () => buildProof,
172
176
  buildReport: () => buildReport,
173
177
  buildReviewAtlas: () => buildReviewAtlas,
@@ -175,6 +179,8 @@ __export(index_exports, {
175
179
  changedCases: () => changedCases,
176
180
  checkDecisionCases: () => checkDecisionCases,
177
181
  checkDrift: () => checkDrift,
182
+ checkPassport: () => checkPassport,
183
+ checkPassportOnDisk: () => checkPassportOnDisk,
178
184
  classify: () => classify,
179
185
  collectReadableFiles: () => collectReadableFiles,
180
186
  compileExpr: () => compileExpr,
@@ -302,6 +308,8 @@ __export(index_exports, {
302
308
  renderMarkdown: () => renderMarkdown,
303
309
  renderMarker: () => renderMarker,
304
310
  renderMermaid: () => renderMermaid,
311
+ renderPassportMarkdown: () => renderPassportMarkdown,
312
+ renderPassportSummary: () => renderPassportSummary,
305
313
  renderReview: () => renderReview,
306
314
  renderReviewBrief: () => renderReviewBrief,
307
315
  renderReviewComment: () => renderReviewComment,
@@ -2577,7 +2585,7 @@ function notesSummary(ast) {
2577
2585
  byLens
2578
2586
  };
2579
2587
  }
2580
- var COMPILER_VERSION = "1.3.0";
2588
+ var COMPILER_VERSION = "1.4.0";
2581
2589
  var PROOF_SCHEMA_VERSION = "0.1.0";
2582
2590
  var SOURCE_PRODUCT = "skillstech-compiler";
2583
2591
  function buildContractGraph(ast, generatedAt) {
@@ -4631,28 +4639,28 @@ function checkDrift(intentText, codeSource, { language = "typescript" } = {}) {
4631
4639
  return verdict(findings2);
4632
4640
  }
4633
4641
  const li = lift.lifted;
4634
- const norm5 = (s) => slug(s);
4635
- const codeGuar = new Set(li.guarantees.map((g) => norm5(g.statement)));
4636
- const codeNever = new Set(li.neverRules.map((n) => norm5(n.statement)));
4637
- const codeInputs = new Set(li.inputs.map((i) => norm5(i.name)));
4638
- const intentGuar = new Set(ast.guarantees.map((g) => norm5(g.statement)));
4642
+ const norm6 = (s) => slug(s);
4643
+ const codeGuar = new Set(li.guarantees.map((g) => norm6(g.statement)));
4644
+ const codeNever = new Set(li.neverRules.map((n) => norm6(n.statement)));
4645
+ const codeInputs = new Set(li.inputs.map((i) => norm6(i.name)));
4646
+ const intentGuar = new Set(ast.guarantees.map((g) => norm6(g.statement)));
4639
4647
  for (const g of ast.guarantees) {
4640
- if (!codeGuar.has(norm5(g.statement))) {
4648
+ if (!codeGuar.has(norm6(g.statement))) {
4641
4649
  add("warning", "INTENT_DRIFT_GUARANTEE_UNSUPPORTED", `Guarantee "${g.statement}" has no matching evidence in the code (test removed or renamed?).`);
4642
4650
  }
4643
4651
  }
4644
4652
  for (const n of ast.neverRules) {
4645
- if (!codeNever.has(norm5(n.statement))) {
4653
+ if (!codeNever.has(norm6(n.statement))) {
4646
4654
  add("warning", "INTENT_DRIFT_NEVER_RULE_UNSUPPORTED", `Never rule "${n.statement}" has no matching error or guard in the code.`);
4647
4655
  }
4648
4656
  }
4649
4657
  for (const f of ast.inputs) {
4650
- if (!codeInputs.has(norm5(f.name))) {
4658
+ if (!codeInputs.has(norm6(f.name))) {
4651
4659
  add("warning", "INTENT_DRIFT_INPUT_REMOVED", `Input "${f.name}" is declared in the intent but not found in the code signature.`);
4652
4660
  }
4653
4661
  }
4654
4662
  for (const g of li.guarantees) {
4655
- if (!intentGuar.has(norm5(g.statement))) {
4663
+ if (!intentGuar.has(norm6(g.statement))) {
4656
4664
  add("info", "INTENT_DRIFT_NEW_BEHAVIOR", `The code has behavior "${g.statement}" that the approved intent does not declare.`);
4657
4665
  }
4658
4666
  }
@@ -8831,16 +8839,16 @@ function buildPython(ast) {
8831
8839
  "# business logic marked TODO is yours, bound by the guarantees and never-rules below.",
8832
8840
  ""
8833
8841
  ];
8834
- const hasData = (ast.inputs || []).length || (ast.outputs || []).length;
8842
+ const hasData2 = (ast.inputs || []).length || (ast.outputs || []).length;
8835
8843
  const cls = (name, fields) => fields.length ? ["@dataclass", `class ${name}:`, ...fields.map((f) => ` ${f.name}: ${pyType(f.type, domain)}`), ""] : [];
8836
8844
  const body2 = [];
8837
8845
  if ((ast.inputs || []).length) body2.push(...cls(`${subject}Input`, ast.inputs));
8838
8846
  if ((ast.outputs || []).length) body2.push(...cls(`${subject}Output`, ast.outputs));
8839
8847
  const usesMoney = domain.has("Money") || plans.some((p) => Object.keys(p.money).length);
8840
8848
  domain.delete("Money");
8841
- if (hasData) L.push("from __future__ import annotations", "from dataclasses import dataclass");
8849
+ if (hasData2) L.push("from __future__ import annotations", "from dataclasses import dataclass");
8842
8850
  if (usesMoney) L.push("from decimal import Decimal");
8843
- if (hasData || usesMoney) L.push("");
8851
+ if (hasData2 || usesMoney) L.push("");
8844
8852
  if (diagnostics.length) {
8845
8853
  L.push(
8846
8854
  "# IL-GEN-001: Thunder could not translate some rule conditions. Those rules raise instead of guessing.",
@@ -9594,10 +9602,21 @@ var CATALOG = [
9594
9602
  } },
9595
9603
  { 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(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9596
9604
  { 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(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9597
- { 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(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9605
+ { 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(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9598
9606
  { 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(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9599
9607
  { re: /^http\s*\.\s*(Get|Post|Head)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9600
9608
  { re: /^reqwest\s*::\s*get\s*\(/, say: (m, c) => ({ says: `Sends a GET request to ${URL_WORDS(splitTop(inside(c, c.indexOf("(")) ?? "")[0])}`, does: "ask" }) },
9609
+ // ── A new random ID: crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), uuidv4(), UUID.randomUUID() ──
9610
+ { 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 }) },
9611
+ // ── .NET: a shared lookup table that makes an entry only once (ConcurrentDictionary.GetOrAdd) ──
9612
+ // `byKey.GetOrAdd(key, _ => new Lazy<Task<T>>(() => Place(request))).Value`: later calls with the same key get the
9613
+ // entry made the first time. The function that makes it is named when the code names one.
9614
+ { re: /^(?:this\.)?(_?[A-Za-z]\w*)\s*\.\s*GetOrAdd\s*\(/, say: (m, c) => {
9615
+ const args = splitTop(inside(c, c.indexOf("(", m.index + m[0].length - 1)) ?? "");
9616
+ if (args.length !== 2) return null;
9617
+ 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();
9618
+ return { says: `the entry for ${valueWords(args[0])} in ${words2(m[1])}, made${made ? ` by ${words2(made)}` : ""} if it is missing (a later call with the same ${valueWords(args[0]).replace(/^the [\w ]+'s /, "")} gets that same entry)`, does: "find", value: true };
9619
+ } },
9601
9620
  // ── Prisma ──
9602
9621
  { 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) => {
9603
9622
  const thing = words2(m[1]), args = inside(c, c.indexOf("(", m.index + m[0].length - 1)) ?? "", whose = whereOf(args);
@@ -9689,6 +9708,14 @@ var CATALOG = [
9689
9708
  { 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" }) },
9690
9709
  // ── JSON, files, time ──
9691
9710
  { re: /^JSON\s*\.\s*parse\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[1])} as JSON`, does: "calculate" }) },
9711
+ // An object written right there names its fields: JSON.stringify({ items: cart, coupon }) -> "Turns items (cart) and coupon into JSON text".
9712
+ { re: /^JSON\s*\.\s*stringify\s*\(\s*\{/, say: (m, c) => {
9713
+ const obj = inside(c, c.indexOf("{"));
9714
+ const fields = obj == null ? null : splitTop(obj).filter((x) => x.trim()).map((x) => x.trim().match(/^([A-Za-z_$][\w$]*)(?:\s*:\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?))?$/));
9715
+ if (!fields?.length || fields.some((f) => !f)) return null;
9716
+ const said = fields.map((f) => f[2] && f[2] !== f[1] ? `${words2(f[1])} (${valueWords(f[2])})` : words2(f[1]));
9717
+ return { says: `Turns ${said.length === 1 ? said[0] : `${said.slice(0, -1).join(", ")} and ${said.at(-1)}`} into JSON text`, does: "calculate" };
9718
+ } },
9692
9719
  { re: /^JSON\s*\.\s*stringify\s*\(\s*([^,]+)/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON text`, does: "calculate" }) },
9693
9720
  { re: /^json\s*\.\s*(loads|load)\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[2])} as JSON`, does: "calculate" }) },
9694
9721
  { re: /^json\s*\.\s*(dumps|dump)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Turns ${valueWords(m[2])} into JSON text`, does: "calculate" }) },
@@ -13588,7 +13615,8 @@ function accountsFor(code3, said, tree = null) {
13588
13615
  const bare2 = stripQuoted(String(said).replace(/`[^`]*`/g, "Q"));
13589
13616
  if (/&&|\|\||[!=]==?|<=|>=|\s[<>]\s|^\s*[<>]|\bis is\b/.test(bare2)) return false;
13590
13617
  const c = tree && tree.kind !== "code" ? exprCounts(tree) : codeCounts(code3), w = wordCounts(said);
13591
- return c.neg === w.neg && c.logic === w.logic && w.compare >= c.compare;
13618
+ const named2 = (String(code3).match(/\bIsNullOr(?:Empty|WhiteSpace)\s*\(/g) || []).length;
13619
+ return c.neg === w.neg && c.logic + named2 === w.logic && w.compare >= c.compare;
13592
13620
  }
13593
13621
  var asCodeWords = (code3, n = 120) => {
13594
13622
  const t = String(code3).replace(/\s+/g, " ").trim();
@@ -13870,9 +13898,9 @@ function sayCodeConditionInner(cond) {
13870
13898
  return `${possessiveWords(ty[2])} is ${ty[1] ? "not " : ""}${kinds.length > 1 ? `one of ${kinds.join(", ")}` : aWord(kinds[0])}`;
13871
13899
  }
13872
13900
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
13873
- const plural6 = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
13901
+ const plural6 = (w, call3) => !call3 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
13874
13902
  if (prop && plural6(words3(prop[3]), !!prop[4])) return `${words3(prop[2])} ${prop[1] ? "has no" : "has"} ${words3(prop[3])}`;
13875
- const yesNo = (w, call2) => /^(is|has|can|should|was) /.test(w) || !call2 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
13903
+ const yesNo = (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));
13876
13904
  if (prop && yesNo(words3(prop[3]), !!prop[4])) {
13877
13905
  const neg = !!prop[1];
13878
13906
  const w = words3(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
@@ -13883,19 +13911,22 @@ function sayCodeConditionInner(cond) {
13883
13911
  if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words3(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words3(pred[3]).replace(/^(not|no|non) /, "$1-")}`;
13884
13912
  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)}`);
13885
13913
  c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
13886
- let call;
13887
- if (call = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) {
13888
- const neg = !!call[1] !== (call[2] === "isset");
13889
- const what = possessiveWords(call[3]);
13890
- if (call[2] === "is_null") return `${what} is ${call[1] ? "not " : ""}null`;
13891
- return call[2] === "isset" ? `${what} is ${call[1] ? "not " : ""}set` : `${what} is ${neg ? "not " : ""}empty`;
13892
- }
13893
- if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
13894
- return `${possessiveWords(call[3])} is ${call[1] ? "not " : ""}${words3(call[2])}`;
13895
- }
13896
- if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
13897
- const w = words3(call[2]);
13898
- if (!call[1]) return w;
13914
+ let call2;
13915
+ if (call2 = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) {
13916
+ const neg = !!call2[1] !== (call2[2] === "isset");
13917
+ const what = possessiveWords(call2[3]);
13918
+ if (call2[2] === "is_null") return `${what} is ${call2[1] ? "not " : ""}null`;
13919
+ return call2[2] === "isset" ? `${what} is ${call2[1] ? "not " : ""}set` : `${what} is ${neg ? "not " : ""}empty`;
13920
+ }
13921
+ if (call2 = c.match(/^(!|not\s+)?[Ss]tring\.IsNullOr(Empty|WhiteSpace)\(\s*([\w$.]+)\s*\)$/)) {
13922
+ return `${possessiveWords(call2[3])} is ${call2[1] ? "not " : ""}${call2[2] === "Empty" ? "empty" : "blank"}${call2[1] ? " and is set" : " or missing"}`;
13923
+ }
13924
+ if ((call2 = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call2[2])) {
13925
+ return `${possessiveWords(call2[3])} is ${call2[1] ? "not " : ""}${words3(call2[2])}`;
13926
+ }
13927
+ if (call2 = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
13928
+ const w = words3(call2[2]);
13929
+ if (!call2[1]) return w;
13899
13930
  return w.replace(/^(is|was|are|should|has|can|does) /, (m0, v) => ({ has: "does not have ", can: "cannot ", does: "does not " })[v] ?? `${v} not `);
13900
13931
  }
13901
13932
  const bare2 = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
@@ -14596,8 +14627,8 @@ function payloadWords(arg) {
14596
14627
  if (/^(["'`])(?:\\.|(?!\1)[^\\])*\1$/.test(a) && !/^`[^`]*\$\{/.test(a)) return a.length < 50 ? `"${a.replace(/^["'`]|["'`]$/g, "")}"` : "a message";
14597
14628
  if (/^["'`]/.test(a) || /["'`]\s*\+|\+\s*["'`]/.test(a)) return "text built from its parts";
14598
14629
  if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(a)) return possessiveWords(a);
14599
- const call = a.match(/^(?:await\s+)?([\w.]+)\s*\(/);
14600
- if (call) return `what ${words3(call[1].split(".").pop())} gives back`;
14630
+ const call2 = a.match(/^(?:await\s+)?([\w.]+)\s*\(/);
14631
+ if (call2) return `what ${words3(call2[1].split(".").pop())} gives back`;
14601
14632
  return "a value";
14602
14633
  }
14603
14634
  function callArgs(text2) {
@@ -15019,6 +15050,7 @@ function statementExpr(raw) {
15019
15050
  return parseStatement(text2, readingLanguage());
15020
15051
  }
15021
15052
  var codeExpr = (text2) => ({ kind: "code", text: String(text2 ?? "").replace(/\s+/g, " ").trim() });
15053
+ var callWithObject = (first) => /[(,]\s*\{\s*$/.test(first) && !/=>\s*\{\s*$/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ""));
15022
15054
  function classifyWords(raw, { inner = 0 } = {}) {
15023
15055
  const text2 = String(raw).trim();
15024
15056
  let first = text2.split("\n")[0].trim();
@@ -15037,8 +15069,9 @@ function classifyWords(raw, { inner = 0 } = {}) {
15037
15069
  const rest2 = c2 > 0 ? text2.slice(c2 + 1).trim() : "";
15038
15070
  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();
15039
15071
  }
15072
+ if (LANG === "csharp") first = first.replace(/^return\s+(?:Task|ValueTask)\.FromResult\((.*)\)\s*;?$/, "return $1;");
15040
15073
  if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text2.split("\n")[1] || "")) first = `return (${text2.split("\n")[1].trim()}`;
15041
- 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))) {
15074
+ 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))) {
15042
15075
  const lines = text2.split("\n");
15043
15076
  const joined = lines.map((l) => l.trim()).join(" ");
15044
15077
  if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || "")) first = joined;
@@ -16871,11 +16904,11 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
16871
16904
  return { type: "block", kind: m[1], head: (m[2] ?? "").trim(), kids: body2, line };
16872
16905
  };
16873
16906
  const nodes2 = parseNodes(null, false);
16874
- const join4 = (list3) => {
16907
+ const join6 = (list3) => {
16875
16908
  const out = [];
16876
16909
  for (const n of list3) {
16877
16910
  if (n.type === "el") {
16878
- n.kids = join4(n.kids);
16911
+ n.kids = join6(n.kids);
16879
16912
  out.push(n);
16880
16913
  continue;
16881
16914
  }
@@ -16883,7 +16916,7 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
16883
16916
  out.push(n);
16884
16917
  continue;
16885
16918
  }
16886
- n.kids = join4(n.kids);
16919
+ n.kids = join6(n.kids);
16887
16920
  const prev = out[out.length - 1];
16888
16921
  if (n.kind === "else" && prev?.type === "cond") {
16889
16922
  let tail = prev;
@@ -16909,7 +16942,7 @@ function parseTemplate(html, fileSrc = null, offset = 0) {
16909
16942
  }
16910
16943
  return out;
16911
16944
  };
16912
- return join4(nodes2);
16945
+ return join6(nodes2);
16913
16946
  }
16914
16947
  var CONTAINERS = /* @__PURE__ */ new Set(["div", "span", "section", "main", "article", "aside", "Fragment", "React.Fragment", "ng-container", "ng-template", "template", "body", "html"]);
16915
16948
  var INLINE = /* @__PURE__ */ new Set(["strong", "em", "b", "i", "small", "code", "mark", "u", "sup", "sub", "abbr", "time"]);
@@ -18101,6 +18134,13 @@ function newThing(v, says) {
18101
18134
  if (!m) return false;
18102
18135
  let c = coreOf(v);
18103
18136
  if (c?.kind === "unary" && c.op === "&") c = coreOf(c.value);
18137
+ if (m[1] === "random ID") {
18138
+ let x = c;
18139
+ if (x?.kind === "call" && x.callee?.kind === "member" && /^(?:ToString|toString)$/.test(x.callee.property)) x = x.callee.object;
18140
+ if (x?.kind === "member" && x.property === "hex") x = x.object;
18141
+ const name = x?.kind === "call" ? x.callee?.kind === "member" ? x.callee.property : x.callee?.name : null;
18142
+ return /^(?:randomUUID|uuid4|NewGuid|uuidv4|v4|new_v4)$/.test(name ?? "") && !x.args?.length;
18143
+ }
18104
18144
  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;
18105
18145
  return !!type && sameWords(String(type).replace(/<.*$/, "").split(/::|\./).pop(), m[1]);
18106
18146
  }
@@ -18166,9 +18206,9 @@ var SAID_AS = {
18166
18206
  none: / set | nothing | none | missing /
18167
18207
  };
18168
18208
  function namesKept(tree, said) {
18169
- const norm5 = (t) => t.replace(/ have /g, " has ").replace(/ are /g, " is ").replace(/ does /g, " ");
18209
+ const norm6 = (t) => t.replace(/ have /g, " has ").replace(/ are /g, " is ").replace(/ does /g, " ");
18170
18210
  const base2 = ` ${splitWords(claimText(said)).join(" ")} ${splitWords(said).join(" ")} `;
18171
- const sw = norm5(`${base2} ${base2.replace(/ (?:not|no|does not|doesn t) /g, " ")} `);
18211
+ const sw = norm6(`${base2} ${base2.replace(/ (?:not|no|does not|doesn t) /g, " ")} `);
18172
18212
  const has2 = (x) => {
18173
18213
  const w = splitWords(x).join(" ");
18174
18214
  if (!w || /^(?:self|this|it|super)$/.test(w) || sw.includes(` ${w} `) || sw.includes(` ${w.replace(/s$/, "")} `) || sw.includes(` ${w}s `)) return true;
@@ -18227,6 +18267,7 @@ function namesKept(tree, said) {
18227
18267
  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));
18228
18268
  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);
18229
18269
  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);
18270
+ if (name && /^IsNullOr(?:Empty|WhiteSpace)$/.test(name) && c?.kind === "member" && /^[Ss]tring$/.test(c.object?.name ?? "") && setWords2) return ok(n.args);
18230
18271
  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);
18231
18272
  return (name == null || has2(name)) && (c?.kind !== "member" || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? "")) && ok(n.args);
18232
18273
  }
@@ -18256,7 +18297,7 @@ function namesKept(tree, said) {
18256
18297
  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)$/;
18257
18298
  var coreOf = (e) => {
18258
18299
  let c = e;
18259
- while (c && (c.kind === "unary" && (c.op === "await" || c.op === "?" || c.op === "!!") || c.kind === "cast" && c.form === "nonnull")) c = c.value;
18300
+ 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;
18260
18301
  return c;
18261
18302
  };
18262
18303
  function chainCallees(e) {
@@ -18542,6 +18583,7 @@ function conditionCore(test, says, code3, lang) {
18542
18583
  if (tn !== wn) return M("L378");
18543
18584
  let logic = 0;
18544
18585
  for (const n of nodesOf2(test)) if (n.kind === "logic") logic += n.operands.length - 1;
18586
+ else if (n.kind === "call" && /^IsNullOr(?:Empty|WhiteSpace)$/.test(n.callee?.property ?? "")) logic++;
18545
18587
  const wl = (said.match(/\band\b|\bor\b/g) || []).length;
18546
18588
  if (logic !== wl) return M("L381");
18547
18589
  if (!orderingKept(test, says)) return M("L382");
@@ -29506,7 +29548,7 @@ function sayValue2(toks, plain = false) {
29506
29548
  }
29507
29549
  if (first.length === 1 && (first[0].t === "var" || first[0].t === "type")) {
29508
29550
  const members = [];
29509
- let k = 1, call = null;
29551
+ let k = 1, call2 = null;
29510
29552
  let index = null;
29511
29553
  while (k < g.length) {
29512
29554
  if (g[k][0].text === "[" && g[k].length > 2) {
@@ -29521,7 +29563,7 @@ function sayValue2(toks, plain = false) {
29521
29563
  const m = g[k + 1]?.[0];
29522
29564
  if (!m || m.t !== "word") break;
29523
29565
  if (g[k + 2]?.[0].text === "(") {
29524
- call = m.text;
29566
+ call2 = m.text;
29525
29567
  k += 3;
29526
29568
  break;
29527
29569
  }
@@ -29534,7 +29576,7 @@ function sayValue2(toks, plain = false) {
29534
29576
  k += 2;
29535
29577
  }
29536
29578
  const owner = first[0].t === "var" ? varWords2(first[0].name) : `the ${first[0].name.split(".").pop()}`;
29537
- if (index != null && (k !== g.length || call)) return null;
29579
+ if (index != null && (k !== g.length || call2)) return null;
29538
29580
  if (index != null) {
29539
29581
  const of3 = chainWords(owner, members);
29540
29582
  if (index.key != null) return possessive(of3, index.key);
@@ -29544,11 +29586,11 @@ function sayValue2(toks, plain = false) {
29544
29586
  if (of3 === "the inputs" && index.n < 10) return `the ${ORD[index.n]} input`;
29545
29587
  return `the item at index ${index.n} of ${of3}`;
29546
29588
  }
29547
- if (k === g.length && first[0].t === "type" && !call && members.length) return `the ${words9(members[members.length - 1])} (${first[0].name.split(".").pop()})`;
29548
- if (k === g.length && first[0].t === "var" && !call) return chainWords(varWords2(first[0].name), members);
29549
- if (k === g.length && call) {
29550
- if (/^new$/i.test(call) && first[0].t === "type") return `a new ${first[0].name.replace(/\[.*$/, "").split(".").pop()}`;
29551
- return `the result of ${words9(call)}${first[0].t === "var" ? ` on ${chainWords(varWords2(first[0].name), members)}` : ""}`;
29589
+ if (k === g.length && first[0].t === "type" && !call2 && members.length) return `the ${words9(members[members.length - 1])} (${first[0].name.split(".").pop()})`;
29590
+ if (k === g.length && first[0].t === "var" && !call2) return chainWords(varWords2(first[0].name), members);
29591
+ if (k === g.length && call2) {
29592
+ if (/^new$/i.test(call2) && first[0].t === "type") return `a new ${first[0].name.replace(/\[.*$/, "").split(".").pop()}`;
29593
+ return `the result of ${words9(call2)}${first[0].t === "var" ? ` on ${chainWords(varWords2(first[0].name), members)}` : ""}`;
29552
29594
  }
29553
29595
  }
29554
29596
  const AR = { "+": "plus", "-": "minus", "*": "times", "/": "divided by", "%": "remainder after dividing by" };
@@ -29643,11 +29685,11 @@ function condWords3(toks, neg) {
29643
29685
  }
29644
29686
  return parts;
29645
29687
  };
29646
- for (const [names, join4, flip] of [[["or", "xor"], " or ", " and "], [["and"], " and ", " or "]]) {
29688
+ for (const [names, join6, flip] of [[["or", "xor"], " or ", " and "], [["and"], " and ", " or "]]) {
29647
29689
  const parts = split(names);
29648
29690
  if (parts.length > 1) {
29649
29691
  const said = parts.map((p) => condWords3(p.flat(), neg));
29650
- return said.some((x) => !x) ? null : said.join(neg ? flip : join4);
29692
+ return said.some((x) => !x) ? null : said.join(neg ? flip : join6);
29651
29693
  }
29652
29694
  }
29653
29695
  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(), !neg);
@@ -30844,7 +30886,7 @@ function powershellReading(src, file = "") {
30844
30886
  }
30845
30887
  function psThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
30846
30888
  const { things } = powershellReading(src, file);
30847
- const norm5 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
30889
+ const norm6 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
30848
30890
  const kind = (t) => {
30849
30891
  const x = String(t ?? "").toLowerCase();
30850
30892
  if (!x) return null;
@@ -30860,7 +30902,7 @@ function psThings(src, file, { words: w, kindWords: kindWords3, startValue: star
30860
30902
  lines: t.lines,
30861
30903
  ...t.doc ? { doc: t.doc } : {},
30862
30904
  choices: t.choices,
30863
- 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(norm5(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm5(k.start)), line: k.line }))
30905
+ 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(norm6(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm6(k.start)), line: k.line }))
30864
30906
  }));
30865
30907
  }
30866
30908
 
@@ -31204,8 +31246,8 @@ function sayValue3(list3) {
31204
31246
  const owner = sayValue3(g.slice(0, -1).flat());
31205
31247
  if (owner) return `an item of ${owner}`;
31206
31248
  }
31207
- const call = callOf(v);
31208
- if (call) return callNoun(call) ?? (callVerb(call) ? `the result of ${gerund(callVerb(call))}` : `the result of ${rWords(call.name)}`);
31249
+ const call2 = callOf(v);
31250
+ if (call2) return callNoun(call2) ?? (callVerb(call2) ? `the result of ${gerund(callVerb(call2))}` : `the result of ${rWords(call2.name)}`);
31209
31251
  if (g.length === 1 && isOp(g[0][0], "(")) return sayValue3(g[0].slice(1, -1));
31210
31252
  if (isId(v[0], "function") || isOp(v[0], "\\")) return "a small function";
31211
31253
  return null;
@@ -31490,7 +31532,7 @@ function condWords4(list3, neg, preCall = null) {
31490
31532
  const v = at02(list3);
31491
31533
  if (!v.length && !preCall) return null;
31492
31534
  const g = groups2(v);
31493
- for (const [ops, join4, flip] of [[["||", "|"], " or ", " and "], [["&&", "&"], " and ", " or "]]) {
31535
+ for (const [ops, join6, flip] of [[["||", "|"], " or ", " and "], [["&&", "&"], " and ", " or "]]) {
31494
31536
  const parts = [[]];
31495
31537
  for (const x of g) {
31496
31538
  if (x.length === 1 && x[0].t === "op" && ops.includes(x[0].text)) parts.push([]);
@@ -31499,7 +31541,7 @@ function condWords4(list3, neg, preCall = null) {
31499
31541
  if (parts.length > 1) {
31500
31542
  if (neg) return null;
31501
31543
  const said = parts.map((p) => condWords4(p, neg));
31502
- return said.some((s) => !s || /^not: /.test(s)) ? null : said.join(join4);
31544
+ return said.some((s) => !s || /^not: /.test(s)) ? null : said.join(join6);
31503
31545
  }
31504
31546
  }
31505
31547
  if (!preCall && isOp(g[0]?.[0], "!")) return condWords4(v.slice(1), !neg);
@@ -31515,11 +31557,11 @@ function condWords4(list3, neg, preCall = null) {
31515
31557
  }
31516
31558
  }
31517
31559
  }
31518
- const call = preCall ?? callOf(v);
31519
- if (call) {
31520
- const a0 = call.args[0] ? sayValue3(call.args[0].toks) : null;
31560
+ const call2 = preCall ?? callOf(v);
31561
+ if (call2) {
31562
+ const a0 = call2.args[0] ? sayValue3(call2.args[0].toks) : null;
31521
31563
  const yes = (p, n) => neg ? n : p;
31522
- switch (call.bare) {
31564
+ switch (call2.bare) {
31523
31565
  // NULL, not "empty": an empty text "" is a different thing in R.
31524
31566
  case "is.null":
31525
31567
  case "is_null":
@@ -31533,7 +31575,7 @@ function condWords4(list3, neg, preCall = null) {
31533
31575
  case "dir.exists":
31534
31576
  return `the folder ${a0} ${yes("exists", "does not exist")}`;
31535
31577
  case "exists": {
31536
- const where = call.args.find((x) => x.name === "envir" || x.name === "where") ?? call.args.filter((x) => !x.name)[1];
31578
+ const where = call2.args.find((x) => x.name === "envir" || x.name === "where") ?? call2.args.filter((x) => !x.name)[1];
31537
31579
  return `${a0} ${yes("exists", "does not exist")}${where ? ` in ${sayValue3(where.toks) ?? "an environment"}` : ""}`;
31538
31580
  }
31539
31581
  case "length":
@@ -31541,7 +31583,7 @@ function condWords4(list3, neg, preCall = null) {
31541
31583
  case "NROW":
31542
31584
  case "ncol":
31543
31585
  case "nchar":
31544
- return `${callNoun(call)} is ${yes("not 0", "0")}`;
31586
+ return `${callNoun(call2)} is ${yes("not 0", "0")}`;
31545
31587
  case "nzchar":
31546
31588
  return `${a0} is ${yes("not empty", "empty")}`;
31547
31589
  case "isTRUE":
@@ -31550,20 +31592,20 @@ function condWords4(list3, neg, preCall = null) {
31550
31592
  return `${a0} is ${yes("no", "not no")}`;
31551
31593
  case "inherits":
31552
31594
  case "is":
31553
- return `${a0} is ${yes("", "not ")}a ${call.args[1] ? at02(call.args[1].toks)[0]?.value ?? sayValue3(call.args[1].toks) : "kind"}`;
31595
+ return `${a0} is ${yes("", "not ")}a ${call2.args[1] ? at02(call2.args[1].toks)[0]?.value ?? sayValue3(call2.args[1].toks) : "kind"}`;
31554
31596
  case "identical":
31555
- return `${a0} is ${yes("", "not ")}${call.args[1] ? sayValue3(call.args[1].toks) : "?"}`;
31597
+ return `${a0} is ${yes("", "not ")}${call2.args[1] ? sayValue3(call2.args[1].toks) : "?"}`;
31556
31598
  case "interactive":
31557
31599
  return `it is ${yes("", "not ")}running with a person at the keyboard`;
31558
31600
  case "requireNamespace":
31559
- return `the ${at02(call.args[0]?.toks ?? [])[0]?.value ?? "needed"} package is ${yes("installed", "not installed")}`;
31601
+ return `the ${at02(call2.args[0]?.toks ?? [])[0]?.value ?? "needed"} package is ${yes("installed", "not installed")}`;
31560
31602
  case "any":
31561
- return `${yes("any", "none")} of ${a0 ?? "them"}${call.args[0] ? "" : ""} ${neg ? "holds" : "holds"}`.replace(/ +/g, " ");
31603
+ return `${yes("any", "none")} of ${a0 ?? "them"}${call2.args[0] ? "" : ""} ${neg ? "holds" : "holds"}`.replace(/ +/g, " ");
31562
31604
  case "all":
31563
31605
  return `${yes("all", "not all")} of ${a0 ?? "them"} hold`;
31564
31606
  default:
31565
- if (KIND_IS[call.bare] && call.args.length === 1) return `${a0} is ${yes("", "not ")}${KIND_IS[call.bare]}`;
31566
- 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(", ")})` : ""}`;
31607
+ if (KIND_IS[call2.bare] && call2.args.length === 1) return `${a0} is ${yes("", "not ")}${KIND_IS[call2.bare]}`;
31608
+ 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(", ")})` : ""}`;
31567
31609
  }
31568
31610
  }
31569
31611
  const val = sayValue3(v);
@@ -31656,13 +31698,13 @@ var fixedOf2 = (list3) => {
31656
31698
  if (v.length === 1 && v[0].t === "num" && /^\d+(\.\d+)?L?$/.test(v[0].text)) return v[0].text.replace(/L$/, "");
31657
31699
  if (v.length === 2 && isOp(v[0], "-") && v[1].t === "num") return `-${v[1].text.replace(/L$/, "")}`;
31658
31700
  if (v.length === 1 && v[0].t === "id" && /^(TRUE|FALSE)$/.test(v[0].text)) return v[0].text.toLowerCase();
31659
- const call = callOf(v);
31660
- if (call && (call.bare === "return" || call.bare === "invisible") && call.args.length === 1) return fixedOf2(call.args[0].toks);
31701
+ const call2 = callOf(v);
31702
+ if (call2 && (call2.bare === "return" || call2.bare === "invisible") && call2.args.length === 1) return fixedOf2(call2.args[0].toks);
31661
31703
  return null;
31662
31704
  };
31663
31705
  var colsOf = (args) => list2(args.map((a) => a.name ? rWords(a.name) : sayValue3(a.toks) ?? "\u2026").slice(0, 6));
31664
- function verbStep(call) {
31665
- const { bare: bare2, args } = call;
31706
+ function verbStep(call2) {
31707
+ const { bare: bare2, args } = call2;
31666
31708
  const plain = args.filter((a) => !a.name);
31667
31709
  switch (bare2) {
31668
31710
  case "filter":
@@ -31745,9 +31787,9 @@ function verbStep(call) {
31745
31787
  case "data.frame":
31746
31788
  return { kind: "set", says: "Turns it into a table" };
31747
31789
  default: {
31748
- const verb = callVerb({ ...call, args: [{ name: null, toks: [] }, ...args] });
31790
+ const verb = callVerb({ ...call2, args: [{ name: null, toks: [] }, ...args] });
31749
31791
  if (verb) return { kind: "call", says: verb.replace(/ \?/g, "") };
31750
- const noun = callNoun(call);
31792
+ const noun = callNoun(call2);
31751
31793
  if (noun) return { kind: "set", says: `Works out ${noun}` };
31752
31794
  return { kind: "call", says: `Calls ${rWords(bare2)}`, callee: bare2 };
31753
31795
  }
@@ -31841,17 +31883,17 @@ function makeReader2(src) {
31841
31883
  }
31842
31884
  function returnStep(list3, s, e) {
31843
31885
  const v = at02(list3);
31844
- const call = callOf(v);
31845
- if (call && (call.bare === "return" || call.bare === "invisible") && call.args.length <= 1) {
31846
- if (!call.args.length || !at02(call.args[0].toks).length) return { kind: "return", says: "Stops here", ...base2(s, e) };
31847
- return returnStep(call.args[0].toks, s, e);
31886
+ const call2 = callOf(v);
31887
+ if (call2 && (call2.bare === "return" || call2.bare === "invisible") && call2.args.length <= 1) {
31888
+ if (!call2.args.length || !at02(call2.args[0].toks).length) return { kind: "return", says: "Stops here", ...base2(s, e) };
31889
+ return returnStep(call2.args[0].toks, s, e);
31848
31890
  }
31849
31891
  const pipe = pipeline(v);
31850
31892
  if (pipe) return null;
31851
31893
  const said = sayValue3(v);
31852
31894
  if (said) return { kind: "return", says: `Returns ${said}`, ...base2(s, e) };
31853
- if (call) {
31854
- const verb = callVerb(call);
31895
+ if (call2) {
31896
+ const verb = callVerb(call2);
31855
31897
  if (verb) return { kind: "return", says: `Returns the result of ${gerund(verb)}`, ...base2(s, e) };
31856
31898
  }
31857
31899
  return { kind: "return", says: "Returns a computed value", restates: true, ...base2(s, e) };
@@ -31946,11 +31988,11 @@ function makeReader2(src) {
31946
31988
  const inAt = inner.findIndex((x2) => isId(x2, "in"));
31947
31989
  const x = inner[0]?.text ?? "item";
31948
31990
  const over = inner.slice(inAt + 1);
31949
- const call = callOf(over);
31991
+ const call2 = callOf(over);
31950
31992
  const og = groups2(over);
31951
31993
  let says;
31952
- if (call?.bare === "seq_along") says = `For each position ${rWords(x)} in ${sayValue3(call.args[0]?.toks ?? []) ?? "the list"}`;
31953
- else if (call?.bare === "seq_len") says = `Counts ${rWords(x)} from 1 to ${sayValue3(call.args[0]?.toks ?? []) ?? "n"}`;
31994
+ if (call2?.bare === "seq_along") says = `For each position ${rWords(x)} in ${sayValue3(call2.args[0]?.toks ?? []) ?? "the list"}`;
31995
+ else if (call2?.bare === "seq_len") says = `Counts ${rWords(x)} from 1 to ${sayValue3(call2.args[0]?.toks ?? []) ?? "n"}`;
31954
31996
  else if (og.length === 3 && isOp(og[1][0], ":")) says = `Counts ${rWords(x)} from ${sayValue3(og[0]) ?? "?"} to ${sayValue3(og[2]) ?? "?"}`;
31955
31997
  else says = `For each ${rWords(x)} in ${sayValue3(over) ?? "the list"}`;
31956
31998
  const kids2 = stepsOfBody(open.match + 1, e, { ...ctx, last: false });
@@ -32009,14 +32051,14 @@ function makeReader2(src) {
32009
32051
  return ctx.fn ? [{ kind: "set", says: `Defines a helper, ${rWords(lv[0].text)}`, ...base2(s, e, head(s, e)) }] : [];
32010
32052
  }
32011
32053
  const rv = at02(rhs);
32012
- const call = callOf(rv);
32013
- if (call && /^(R6Class|setRefClass|setClass)$/.test(call.bare)) {
32014
- defineThing(lv[0]?.text ?? "", call, s, e);
32054
+ const call2 = callOf(rv);
32055
+ if (call2 && /^(R6Class|setRefClass|setClass)$/.test(call2.bare)) {
32056
+ defineThing(lv[0]?.text ?? "", call2, s, e);
32015
32057
  return [];
32016
32058
  }
32017
- if (call && call.bare === "tryCatch") return [tryStep(call, s, e, ctx, target)];
32018
- if (call && /^(lapply|sapply|vapply|map|map_chr|map_dbl|map_int|map_lgl|map_dfr|purrr::map|Map|mapply)$/.test(call.bare)) {
32019
- const l = loopOfApply(call, s, e, ctx);
32059
+ if (call2 && call2.bare === "tryCatch") return [tryStep(call2, s, e, ctx, target)];
32060
+ if (call2 && /^(lapply|sapply|vapply|map|map_chr|map_dbl|map_int|map_lgl|map_dfr|purrr::map|Map|mapply)$/.test(call2.bare)) {
32061
+ const l = loopOfApply(call2, s, e, ctx);
32020
32062
  if (l) return [{ ...l, says: `${l.says}, keeping the answers as ${target}` }];
32021
32063
  }
32022
32064
  if (isId(rv[0], "if")) {
@@ -32030,17 +32072,17 @@ function makeReader2(src) {
32030
32072
  if (pipe) return [{ kind: "set", says: `Works out ${target}, step by step`, ...base2(s, e, head(s, e)), children: pipelineSteps(pipe, s, e) }];
32031
32073
  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) }];
32032
32074
  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) }];
32033
- if (call) {
32034
- if (call.bare === "switch") {
32035
- const st = switchStep(call, s, e, { ...ctx, last: true });
32075
+ if (call2) {
32076
+ if (call2.bare === "switch") {
32077
+ const st = switchStep(call2, s, e, { ...ctx, last: true });
32036
32078
  giveValue2(st, target);
32037
32079
  return [st];
32038
32080
  }
32039
- const verb = callVerb(call);
32040
- if (verb) return [{ kind: "call", says: `${verb}, keeping it as ${target}`, callee: call.bare, ...base2(s, e) }];
32041
- const noun = callNoun(call);
32081
+ const verb = callVerb(call2);
32082
+ if (verb) return [{ kind: "call", says: `${verb}, keeping it as ${target}`, callee: call2.bare, ...base2(s, e) }];
32083
+ const noun = callNoun(call2);
32042
32084
  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) }];
32043
- return [{ kind: "set", says: `Works out ${target} from ${rWords(call.bare)}`, callee: call.bare, ...base2(s, e) }];
32085
+ return [{ kind: "set", says: `Works out ${target} from ${rWords(call2.bare)}`, callee: call2.bare, ...base2(s, e) }];
32044
32086
  }
32045
32087
  const val = sayValue3(rv);
32046
32088
  return [{ kind: "set", says: val ? `Sets ${target} to ${val}` : `Works out ${target}`, ...val ? {} : { restates: true }, ...base2(s, e) }];
@@ -32059,8 +32101,8 @@ function makeReader2(src) {
32059
32101
  };
32060
32102
  fix([step]);
32061
32103
  }
32062
- function loopOfApply(call, s, e, ctx) {
32063
- const [xs, f] = call.args.filter((a) => !a.name || a.name === "X" || a.name === "FUN" || a.name === ".x" || a.name === ".f");
32104
+ function loopOfApply(call2, s, e, ctx) {
32105
+ const [xs, f] = call2.args.filter((a) => !a.name || a.name === "X" || a.name === "FUN" || a.name === ".x" || a.name === ".f");
32064
32106
  if (!xs || !f) return null;
32065
32107
  const fv = fnValue(f.toks);
32066
32108
  const what = sayValue3(xs.toks) ?? "the list";
@@ -32071,15 +32113,15 @@ function makeReader2(src) {
32071
32113
  const kids2 = stepsOfBody(fv.from, fv.to, { ...ctx, last: true, fn: true });
32072
32114
  return { kind: "loop", says: `For each ${rWords(fv.params[0]?.name ?? "item")} in ${what}`, ...base2(s, e, head(s, e)), ...kids2.length ? { children: kids2 } : {} };
32073
32115
  }
32074
- function tryStep(call, s, e, ctx, target = null) {
32116
+ function tryStep(call2, s, e, ctx, target = null) {
32075
32117
  const step = { kind: "try", says: `Tries these steps and handles any error${target ? ` (the answer becomes ${target})` : ""}`, ...base2(s, e, head(s, e)) };
32076
- const expr = call.args.find((a) => !a.name || a.name === "expr");
32118
+ const expr = call2.args.find((a) => !a.name || a.name === "expr");
32077
32119
  if (expr && at02(expr.toks).length) {
32078
32120
  const r = range(at02(expr.toks));
32079
32121
  const kids2 = stepsOfBody(r[0], r[1], { ...ctx, last: !!target || ctx.last });
32080
32122
  if (kids2.length) step.children = kids2;
32081
32123
  }
32082
- for (const a of call.args.filter((x) => x.name && x.name !== "expr")) {
32124
+ for (const a of call2.args.filter((x) => x.name && x.name !== "expr")) {
32083
32125
  const fv = fnValue(a.toks);
32084
32126
  const r = at02(a.toks).length ? range(at02(a.toks)) : null;
32085
32127
  if (a.name === "finally") {
@@ -32094,8 +32136,8 @@ function makeReader2(src) {
32094
32136
  }
32095
32137
  return step;
32096
32138
  }
32097
- function switchStep(call, s, e, ctx) {
32098
- const [subject, ...rest2] = call.args;
32139
+ function switchStep(call2, s, e, ctx) {
32140
+ const [subject, ...rest2] = call2.args;
32099
32141
  const arms = [];
32100
32142
  let pending = [];
32101
32143
  for (const a of rest2) {
@@ -32119,9 +32161,9 @@ function makeReader2(src) {
32119
32161
  if (ctx.last) steps.push({ kind: "return", says: "Returns the result", ...base2(s, e) });
32120
32162
  return steps;
32121
32163
  }
32122
- const call = callOf(v);
32123
- if (call) {
32124
- const { bare: bare2, args } = call;
32164
+ const call2 = callOf(v);
32165
+ if (call2) {
32166
+ const { bare: bare2, args } = call2;
32125
32167
  const a0 = args[0] ? sayValue3(args[0].toks) : null;
32126
32168
  if (bare2 === "stop_input_type") {
32127
32169
  const what = at02(args[1]?.toks ?? [])[0];
@@ -32150,7 +32192,7 @@ function makeReader2(src) {
32150
32192
  return [{ kind: "check", says: `Checks that ${c.every(Boolean) ? c.join(" and ") : "its conditions hold"} (stops with an error if not)`, ...base2(s, e) }];
32151
32193
  }
32152
32194
  if (/^(library|require|requireNamespace|suppressPackageStartupMessages|suppressMessages)$/.test(bare2)) {
32153
- const inner = bare2.startsWith("suppress") ? callOf(at02(args[0]?.toks ?? [])) : call;
32195
+ const inner = bare2.startsWith("suppress") ? callOf(at02(args[0]?.toks ?? [])) : call2;
32154
32196
  if (inner && /^(library|require)$/.test(inner.bare)) {
32155
32197
  const p = at02(inner.args[0]?.toks ?? [])[0];
32156
32198
  return [{ kind: "set", says: `Loads the ${p?.value ?? p?.text ?? "?"} package`, ...base2(s, e) }];
@@ -32158,7 +32200,7 @@ function makeReader2(src) {
32158
32200
  if (!inner) return [{ kind: "call", says: "Runs it quietly", ...base2(s, e) }];
32159
32201
  }
32160
32202
  if (bare2 === "source") return [{ kind: "call", says: `Runs the R file ${a0 ?? "?"}`, ...base2(s, e) }];
32161
- if (bare2 === "tryCatch" || bare2 === "withCallingHandlers") return [tryStep(call, s, e, ctx)];
32203
+ if (bare2 === "tryCatch" || bare2 === "withCallingHandlers") return [tryStep(call2, s, e, ctx)];
32162
32204
  if (bare2 === "try") {
32163
32205
  const r = args[0] && at02(args[0].toks).length ? range(at02(args[0].toks)) : null;
32164
32206
  const kids2 = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
@@ -32169,9 +32211,9 @@ function makeReader2(src) {
32169
32211
  const kids2 = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
32170
32212
  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 } : {} }];
32171
32213
  }
32172
- if (bare2 === "switch") return [switchStep(call, s, e, ctx)];
32214
+ if (bare2 === "switch") return [switchStep(call2, s, e, ctx)];
32173
32215
  if (/^(lapply|sapply|vapply|map|walk|map_chr|map_dbl|map_int|map_lgl|map_dfr|Map|mapply|purrr::walk)$/.test(bare2)) {
32174
- const l = loopOfApply(call, s, e, ctx);
32216
+ const l = loopOfApply(call2, s, e, ctx);
32175
32217
  if (l) return [l];
32176
32218
  }
32177
32219
  if (bare2 === "test_that") {
@@ -32197,7 +32239,7 @@ function makeReader2(src) {
32197
32239
  const r = returnStep(v, s, e);
32198
32240
  if (r && !r.restates) return [r];
32199
32241
  }
32200
- const verb = callVerb(call);
32242
+ const verb = callVerb(call2);
32201
32243
  if (verb) return [{ kind: "call", says: verb, callee: bare2, ...base2(s, e) }];
32202
32244
  if (ctx.last) {
32203
32245
  const r = returnStep(v, s, e);
@@ -32212,9 +32254,9 @@ function makeReader2(src) {
32212
32254
  const val = sayValue3(v);
32213
32255
  return [val ? { kind: "call", says: `Works out ${val}`, ...base2(s, e) } : { kind: "other", says: code3(s, e), ...base2(s, e) }];
32214
32256
  }
32215
- function defineThing(name, call, s, e) {
32257
+ function defineThing(name, call2, s, e) {
32216
32258
  const lines = [lineAt4(toks[s].at), lineAt4(toks[e - 1].end - 1)];
32217
- const className = at02(call.args[0]?.toks ?? [])[0]?.value ?? at02(call.args.find((a) => a.name === "Classname")?.toks ?? [])[0]?.value ?? name;
32259
+ const className = at02(call2.args[0]?.toks ?? [])[0]?.value ?? at02(call2.args.find((a) => a.name === "Classname")?.toks ?? [])[0]?.value ?? name;
32218
32260
  const { doc } = docAbove5(s);
32219
32261
  const thing = { kind: "record", name: className || name, lines, ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
32220
32262
  const listArgs = (a) => {
@@ -32260,18 +32302,18 @@ function makeReader2(src) {
32260
32302
  }
32261
32303
  }
32262
32304
  };
32263
- if (call.bare === "R6Class") {
32305
+ if (call2.bare === "R6Class") {
32264
32306
  for (const part of ["public", "private", "active"]) {
32265
- const args = listArgs(call.args.find((a) => a.name === part));
32307
+ const args = listArgs(call2.args.find((a) => a.name === part));
32266
32308
  knowsFrom(args, false);
32267
32309
  methodsFrom(args);
32268
32310
  }
32269
- } else if (call.bare === "setRefClass") {
32270
- knowsFrom(listArgs(call.args.find((a) => a.name === "fields")), true);
32271
- methodsFrom(listArgs(call.args.find((a) => a.name === "methods")));
32311
+ } else if (call2.bare === "setRefClass") {
32312
+ knowsFrom(listArgs(call2.args.find((a) => a.name === "fields")), true);
32313
+ methodsFrom(listArgs(call2.args.find((a) => a.name === "methods")));
32272
32314
  } else {
32273
- knowsFrom(listArgs(call.args.find((a) => a.name === "representation" || a.name === "slots") ?? call.args.find((a, k) => k === 1 && !a.name)), true);
32274
- for (const p of listArgs(call.args.find((a) => a.name === "prototype")) || []) {
32315
+ knowsFrom(listArgs(call2.args.find((a) => a.name === "representation" || a.name === "slots") ?? call2.args.find((a, k) => k === 1 && !a.name)), true);
32316
+ for (const p of listArgs(call2.args.find((a) => a.name === "prototype")) || []) {
32275
32317
  const k = thing.knows.find((q2) => q2.name === p.name);
32276
32318
  if (k) k.start = at02(p.toks).map((x) => x.text).join("");
32277
32319
  }
@@ -32354,12 +32396,12 @@ function decisionOf2(r, fv) {
32354
32396
  }
32355
32397
  if (!isLast) return null;
32356
32398
  const v = at02(toks.slice(s, e));
32357
- const call = callOf(v);
32358
- if (call?.bare === "switch") {
32359
- const subj = condJs2(call.args[0]?.toks ?? []);
32399
+ const call2 = callOf(v);
32400
+ if (call2?.bare === "switch") {
32401
+ const subj = condJs2(call2.args[0]?.toks ?? []);
32360
32402
  if (!subj || /\s/.test(subj)) return null;
32361
32403
  let pending = [];
32362
- for (const a of call.args.slice(1)) {
32404
+ for (const a of call2.args.slice(1)) {
32363
32405
  const vt = at02(a.toks);
32364
32406
  if (a.name && !vt.length) {
32365
32407
  pending.push(a.name);
@@ -32391,10 +32433,10 @@ function rReading(src, file = "") {
32391
32433
  for (const [s, e] of splitStatements2(r.toks, 0, r.toks.length)) {
32392
32434
  const v = at02(r.toks.slice(s, e));
32393
32435
  const steps = r.statement(s, e, {});
32394
- const call = callOf(v);
32436
+ const call2 = callOf(v);
32395
32437
  const assign = groups2(v).findIndex((x) => x.length === 1 && x[0].t === "op" && /^(<-|=|<<-)$/.test(x[0].text));
32396
32438
  const rhs = assign > 0 ? callOf(groups2(v).slice(assign + 1).flat()) : null;
32397
- const isDef = call && DEFINITION.test(call.bare) || rhs && DEFINITION.test(rhs.bare) || !steps.length;
32439
+ const isDef = call2 && DEFINITION.test(call2.bare) || rhs && DEFINITION.test(rhs.bare) || !steps.length;
32398
32440
  if (!isDef) real = true;
32399
32441
  topSteps.push(...steps);
32400
32442
  }
@@ -32421,7 +32463,7 @@ function rReading(src, file = "") {
32421
32463
  return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
32422
32464
  }
32423
32465
  function rThings(src, file, { words: w, kindWords: kindWords3, startValue: startValue2 }) {
32424
- const norm5 = (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"');
32466
+ const norm6 = (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"');
32425
32467
  return rReading(src, file).things.map((t) => ({
32426
32468
  kind: t.kind,
32427
32469
  name: t.name,
@@ -32430,7 +32472,7 @@ function rThings(src, file, { words: w, kindWords: kindWords3, startValue: start
32430
32472
  ...t.doc ? { doc: t.doc } : {},
32431
32473
  choices: t.choices,
32432
32474
  memberRanges: t.memberRanges,
32433
- 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(norm5(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm5(k.start)), line: k.line }))
32475
+ 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(norm6(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm6(k.start)), line: k.line }))
32434
32476
  }));
32435
32477
  }
32436
32478
 
@@ -32528,6 +32570,36 @@ function matchClose(src, open) {
32528
32570
  return -1;
32529
32571
  }
32530
32572
  var READING_RUST = false;
32573
+ function textRanges(src) {
32574
+ const flags2 = new Uint8Array(src.length + 1);
32575
+ for (let i = 0; i < src.length; i++) {
32576
+ const c = src[i];
32577
+ if (c === "/" && src[i + 1] === "/") {
32578
+ const e = src.indexOf("\n", i);
32579
+ const end2 = e < 0 ? src.length : e;
32580
+ flags2.fill(1, i, end2);
32581
+ i = end2;
32582
+ continue;
32583
+ }
32584
+ if (c === "/" && src[i + 1] === "*") {
32585
+ const e = src.indexOf("*/", i + 2);
32586
+ const end2 = e < 0 ? src.length : e + 2;
32587
+ flags2.fill(1, i, end2);
32588
+ i = end2 - 1;
32589
+ continue;
32590
+ }
32591
+ if (c === '"' || c === "'") {
32592
+ let end2;
32593
+ if (c === '"' && src[i - 1] === "@" || c === '"' && src[i - 1] === "$" && src[i - 2] === "@") {
32594
+ end2 = i + 1;
32595
+ while (end2 < src.length && !(src[end2] === '"' && src[end2 + 1] !== '"')) end2 += src[end2] === '"' ? 2 : 1;
32596
+ } else end2 = skipString3(src, i);
32597
+ flags2.fill(1, i, Math.min(src.length, end2 + 1));
32598
+ i = end2;
32599
+ }
32600
+ }
32601
+ return flags2;
32602
+ }
32531
32603
  function skipString3(src, i) {
32532
32604
  const q2 = src[i];
32533
32605
  if (q2 === '"' && src[i + 1] === '"' && src[i + 2] === '"') {
@@ -32756,6 +32828,7 @@ function findFunctions(src, language) {
32756
32828
  patterns.javascript = patterns.typescript;
32757
32829
  patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
32758
32830
  const seen = /* @__PURE__ */ new Set();
32831
+ const inText = language === "csharp" || language === "java" ? textRanges(src) : null;
32759
32832
  for (const re of patterns[language] || []) {
32760
32833
  let m;
32761
32834
  re.lastIndex = 0;
@@ -32763,6 +32836,7 @@ function findFunctions(src, language) {
32763
32836
  const name = m[1];
32764
32837
  const open = src.indexOf("(", m.index + m[0].length - 1);
32765
32838
  if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
32839
+ if (inText && (inText[m.index + m[0].lastIndexOf(name, m[0].length - 1)] || language === "csharp" && name === "async")) continue;
32766
32840
  const close = matchClose(src, open);
32767
32841
  if (close < 0) continue;
32768
32842
  const after = src.slice(close + 1, close + 1 + 4e3);
@@ -32817,7 +32891,7 @@ function findFunctions(src, language) {
32817
32891
  fns.push({ name: `${m[1].toUpperCase()} ${m[2]}`, line: lineAt2(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: m[1].toUpperCase(), path: m[2] } });
32818
32892
  }
32819
32893
  }
32820
- 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] : [];
32894
+ 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] : [];
32821
32895
  for (const re of routeRes) {
32822
32896
  let m;
32823
32897
  while (m = re.exec(src)) {
@@ -32828,7 +32902,7 @@ function findFunctions(src, language) {
32828
32902
  const brace = src.indexOf("{", close);
32829
32903
  if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) {
32830
32904
  const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
32831
- if (!(language === "typescript" || language === "javascript") || !arrow || src[close + 1 + arrow[0].length] === "{") continue;
32905
+ if (!(language === "typescript" || language === "javascript" || language === "csharp") || !arrow || src[close + 1 + arrow[0].length] === "{") continue;
32832
32906
  const from = close + 1 + arrow[0].length;
32833
32907
  let depth = 0, end2 = from, q2 = null;
32834
32908
  for (; end2 < src.length; end2++) {
@@ -33584,6 +33658,15 @@ function annotateRoutes(fns, src) {
33584
33658
  for (const fn of fns) {
33585
33659
  if (fn.route) continue;
33586
33660
  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());
33661
+ const std = /^do_(GET|POST|PUT|PATCH|DELETE|HEAD)$/.exec(fn.name ?? "");
33662
+ const stdBody = typeof fn.body === "string" ? fn.body : Array.isArray(fn.pyBody) ? fn.pyBody.map((x) => x.text).join("\n") : null;
33663
+ if (std && stdBody) {
33664
+ const paths = new Set([...stdBody.matchAll(/\bself\.path\s*(?:==|!=)\s*['"](\/[^'"]*)['"]/g)].map((x) => x[1]));
33665
+ if (paths.size === 1) {
33666
+ fn.route = { method: std[1], path: [...paths][0] };
33667
+ continue;
33668
+ }
33669
+ }
33587
33670
  for (const l of above) {
33588
33671
  let m;
33589
33672
  if (m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i)) {
@@ -35933,10 +36016,10 @@ function plainFromReading(item4) {
35933
36016
  };
35934
36017
  for (const r of item4.rules) {
35935
36018
  const when = r.when.trim();
35936
- const join4 = / or /.test(when) ? "any" : "all";
36019
+ const join6 = / or /.test(when) ? "any" : "all";
35937
36020
  if (/ or /.test(when) && / and /.test(when)) return null;
35938
36021
  const conditions = [];
35939
- for (const part of when.split(join4 === "all" ? " and " : " or ")) {
36022
+ for (const part of when.split(join6 === "all" ? " and " : " or ")) {
35940
36023
  const t = part.trim();
35941
36024
  let m;
35942
36025
  const input2 = (id2) => inputs2.find((i) => i.id === id2);
@@ -35960,7 +36043,7 @@ function plainFromReading(item4) {
35960
36043
  } else return null;
35961
36044
  }
35962
36045
  if (!outcome(r.result)) return null;
35963
- model.rules.push({ outcome: r.result, join: join4, conditions });
36046
+ model.rules.push({ outcome: r.result, join: join6, conditions });
35964
36047
  }
35965
36048
  if (!outcome(item4.otherwise.result)) return null;
35966
36049
  model.otherwise = item4.otherwise.result;
@@ -36282,11 +36365,18 @@ function cDocAbove(src, idx) {
36282
36365
  return docAbove4(src, idx);
36283
36366
  }
36284
36367
  function ownLevel(body2) {
36285
- let depth = 0, own = "";
36286
- for (const c of body2) {
36287
- if (c === "{") depth++;
36368
+ let depth = 0, own = "", start = 0;
36369
+ for (let i = 0; i < body2.length; i++) {
36370
+ const c = body2[i];
36371
+ if (c === "{") {
36372
+ if (depth === 0) start = i;
36373
+ depth++;
36374
+ }
36288
36375
  if (depth === 0) own += c;
36289
- if (c === "}") depth--;
36376
+ if (c === "}") {
36377
+ depth--;
36378
+ if (depth === 0 && /(?:=|\bnew\b[\w.<>,[\] ?]*(?:\([^()]*\))?)\s*$/.test(own) && body2.slice(start + 1, i).trim()) own = `${own.replace(/\s+$/, "")} {\u2026}`;
36379
+ }
36290
36380
  }
36291
36381
  return own;
36292
36382
  }
@@ -36311,7 +36401,11 @@ function goDoc(src, at2, name) {
36311
36401
  return t.charAt(0).toUpperCase() + t.slice(1);
36312
36402
  }
36313
36403
  function makeThingReaders({ words: words14, kindWords: kindWords3, startValue: startValue2 }) {
36314
- const know = (name, type, start, params, line = null) => ({ name, label: words14(name.replace(/^[_$]+|_$/g, "")), kind: type ? kindWords3(type) : null, start: start != null && start !== "" ? startValue2(start, params) : null, line });
36404
+ const know = (name, type, start, params, line = null) => {
36405
+ const kind = type ? kindWords3(type) : null;
36406
+ 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;
36407
+ return { name, label: words14(name.replace(/^[_$]+|_$/g, "")), kind, start: said, line };
36408
+ };
36315
36409
  function curlyThings(src, file, language) {
36316
36410
  const lineAt4 = lineFinder5(src);
36317
36411
  const out = [];
@@ -36380,6 +36474,7 @@ function makeThingReaders({ words: words14, kindWords: kindWords3, startValue: s
36380
36474
  thing.knows.push(know(f[2], f[1], f[3], params));
36381
36475
  }
36382
36476
  }
36477
+ thing.knows = thing.knows.filter((k, i, all) => all.findIndex((x) => x.label === k.label) === i);
36383
36478
  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*)?\\{`);
36384
36479
  const ctor = body2.match(ctorRe);
36385
36480
  if (ctor) {
@@ -36745,8 +36840,8 @@ function makeThingReaders({ words: words14, kindWords: kindWords3, startValue: s
36745
36840
  const head = mem.head.replace(/^(?:(?:public|private|protected)\s*:\s*)+/, "").replace(/\[\[[^\]]*\]\]\s*/g, "").trim();
36746
36841
  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;
36747
36842
  const sig = head.replace(/<[^<>]*(?:<[^<>]*>[^<>]*)*>/g, "<>");
36748
- const call = sig.split(/=(?!=)/)[0];
36749
- if (/\(/.test(call) && !/\(\s*\*\s*\w+\s*\)\s*\(/.test(call)) {
36843
+ const call2 = sig.split(/=(?!=)/)[0];
36844
+ if (/\(/.test(call2) && !/\(\s*\*\s*\w+\s*\)\s*\(/.test(call2)) {
36750
36845
  methods = true;
36751
36846
  const ctor = head.match(new RegExp(`^(?:explicit\\s+|constexpr\\s+|inline\\s+)*${name}\\s*\\(([^)]*)\\)\\s*(?:noexcept\\s*)?(?::\\s*([\\s\\S]+))?$`));
36752
36847
  if (ctor) cppCtor(ctor[1], ctor[2], mem.block, params, inits);
@@ -36939,9 +37034,9 @@ function callsIn(expr, out = []) {
36939
37034
  var bind = (files, symbol = null, extra = {}) => ({ files, symbol, ...extra });
36940
37035
  function jsImports(src, file, ctx, out) {
36941
37036
  const clean = stripComments2(src);
36942
- const resolve4 = (spec) => ctx.jsFile(file, spec);
37037
+ const resolve5 = (spec) => ctx.jsFile(file, spec);
36943
37038
  const add = (local, spec, symbol, line) => {
36944
- const r = resolve4(spec);
37039
+ const r = resolve5(spec);
36945
37040
  if (r.file) out.bindings.set(local, bind([r.file], symbol, { line, spec }));
36946
37041
  else out.unresolved.push({ file, line, import: spec, why: r.why });
36947
37042
  };
@@ -37216,9 +37311,9 @@ function segsMatch(a, b) {
37216
37311
  return exact;
37217
37312
  }
37218
37313
  var HTTP_SAYS = /^Sends an? ([A-Z]+) request to /;
37219
- function urlArg(call) {
37220
- const args = call.args || [];
37221
- const path = calleePath(call.callee) || [];
37314
+ function urlArg(call2) {
37315
+ const args = call2.args || [];
37316
+ const path = calleePath(call2.callee) || [];
37222
37317
  const last = path.at(-1) || "";
37223
37318
  if (/^NewRequest(WithContext)?$/.test(last)) return args[last.endsWith("Context") ? 2 : 1];
37224
37319
  if (args[0]?.kind === "object") {
@@ -37229,8 +37324,8 @@ function urlArg(call) {
37229
37324
  return args[0];
37230
37325
  }
37231
37326
  function httpOfCode(calls) {
37232
- for (const call of calls) {
37233
- const path = calleePath(call.callee) || [];
37327
+ for (const call2 of calls) {
37328
+ const path = calleePath(call2.callee) || [];
37234
37329
  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()];
37235
37330
  }
37236
37331
  return null;
@@ -37667,7 +37762,7 @@ function linkSystem(model, files) {
37667
37762
  }
37668
37763
  return typesFor2(file).get(name);
37669
37764
  };
37670
- const resolve4 = (file, path, isNew, member) => {
37765
+ const resolve5 = (file, path, isNew, member) => {
37671
37766
  const lang = langOf.get(file);
37672
37767
  const mod = modules.get(file);
37673
37768
  if (!mod) return { why: null };
@@ -37765,14 +37860,14 @@ function linkSystem(model, files) {
37765
37860
  if (!calls.length) continue;
37766
37861
  const http = HTTP_SAYS.exec(nd.text || "") || (nd.explained === false ? httpOfCode(calls) : null);
37767
37862
  let httpDone = false;
37768
- for (const call of calls) {
37769
- const path = calleePath(call.callee);
37863
+ for (const call2 of calls) {
37864
+ const path = calleePath(call2.callee);
37770
37865
  if (!path) continue;
37771
37866
  stats.calls++;
37772
37867
  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))) {
37773
37868
  httpDone = true;
37774
37869
  const method = http[1];
37775
- const u = urlOf(urlArg(call));
37870
+ const u = urlOf(urlArg(call2));
37776
37871
  const service = u.path ? `${method} ${u.path}` : `${method} request`;
37777
37872
  if (!u.segs) {
37778
37873
  notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: service, why: u.why });
@@ -37790,8 +37885,8 @@ function linkSystem(model, files) {
37790
37885
  }
37791
37886
  const last = path.at(-1);
37792
37887
  const queue = path.length === 2 && /^(add|addBulk)$/.test(last) ? queueNames.get(`${m.file}|${path[0]}`) : null;
37793
- if (queue || EVENT_PUBLISH.test(last) && call.args?.[0]?.kind === "literal" && call.args[0].type === "text") {
37794
- const name = queue ?? String(call.args[0].value);
37888
+ if (queue || EVENT_PUBLISH.test(last) && call2.args?.[0]?.kind === "literal" && call2.args[0].type === "text") {
37889
+ const name = queue ?? String(call2.args[0].value);
37795
37890
  if (GENERIC_EVENTS.has(name)) continue;
37796
37891
  const ls = (listeners.get(name) || []).filter((x) => x.member.id !== m.id);
37797
37892
  for (const x of ls) {
@@ -37801,13 +37896,13 @@ function linkSystem(model, files) {
37801
37896
  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}` });
37802
37897
  if (ls.length) continue;
37803
37898
  }
37804
- let p = path, isNew = !!call.new, task = false;
37899
+ let p = path, isNew = !!call2.new, task = false;
37805
37900
  if (p.length >= 2 && /^(delay|apply_async|send|enqueue|perform_async|perform_later)$/.test(last) && langOf.get(m.file) !== "go") {
37806
37901
  p = p.slice(0, -1);
37807
37902
  task = /^(delay|apply_async|perform_async|perform_later)$/.test(last);
37808
37903
  }
37809
- argc = (call.args || []).length;
37810
- const r = resolve4(m.file, p, isNew, m);
37904
+ argc = (call2.args || []).length;
37905
+ const r = resolve5(m.file, p, isNew, m);
37811
37906
  if (r.member && r.member.id !== m.id) {
37812
37907
  const cross = r.member.file !== m.file;
37813
37908
  link({ from: m.id, to: r.member.id, kind: task ? "sends-to" : "uses", node: nd.id, file: r.member.file, line: nd.line ?? null, ...cross ? { crossFile: true } : {}, ...task ? { task: r.member.name } : {} });
@@ -37873,20 +37968,20 @@ function serviceFacts(model, files) {
37873
37968
  if (!nd.expr) continue;
37874
37969
  const http = HTTP_SAYS.exec(nd.text || "");
37875
37970
  let httpDone = false;
37876
- for (const call of callsIn(nd.expr)) {
37877
- const path = calleePath(call.callee);
37971
+ for (const call2 of callsIn(nd.expr)) {
37972
+ const path = calleePath(call2.callee);
37878
37973
  if (!path) continue;
37879
37974
  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))) {
37880
37975
  httpDone = true;
37881
- const t = requestTarget(urlArg(call));
37976
+ const t = requestTarget(urlArg(call2));
37882
37977
  if (t) requests.push({ method: http[1], path: t.path, segs: t.segs, base: t.base, ...at2(m, nd.line) });
37883
- else unknown.push({ ...at2(m, nd.line), call: `${http[1]} request`, why: urlOf(urlArg(call)).why ?? "the path is worked out when it runs" });
37978
+ else unknown.push({ ...at2(m, nd.line), call: `${http[1]} request`, why: urlOf(urlArg(call2)).why ?? "the path is worked out when it runs" });
37884
37979
  continue;
37885
37980
  }
37886
37981
  const last = path.at(-1);
37887
37982
  const queue = path.length === 2 && /^(add|addBulk)$/.test(last) ? queueNames.get(`${m.file}|${path[0]}`) : null;
37888
- if (queue || EVENT_PUBLISH.test(last) && call.args?.[0]?.kind === "literal" && call.args[0].type === "text") {
37889
- const name = queue ?? String(call.args[0].value);
37983
+ if (queue || EVENT_PUBLISH.test(last) && call2.args?.[0]?.kind === "literal" && call2.args[0].type === "text") {
37984
+ const name = queue ?? String(call2.args[0].value);
37890
37985
  if (name.trim() && !GENERIC_EVENTS.has(name)) publishes.push({ event: name, how: queue ? "queue" : last, ...at2(m, nd.line) });
37891
37986
  }
37892
37987
  }
@@ -37915,6 +38010,2901 @@ function callsSummary(model) {
37915
38010
  return [...pairs2.values()].sort((x, y) => y.calls + y.sends - (x.calls + x.sends) || x.from.localeCompare(y.from) || x.to.localeCompare(y.to));
37916
38011
  }
37917
38012
 
38013
+ // src/flow/ts-parse.mjs
38014
+ var ParseError2 = class extends Error {
38015
+ constructor(message2, line) {
38016
+ super(message2);
38017
+ this.line = line;
38018
+ }
38019
+ };
38020
+ var PUNCT5 = [
38021
+ ">>>=",
38022
+ "...",
38023
+ "===",
38024
+ "!==",
38025
+ "**=",
38026
+ "<<=",
38027
+ ">>=",
38028
+ ">>>",
38029
+ "&&=",
38030
+ "||=",
38031
+ "??=",
38032
+ "=>",
38033
+ "==",
38034
+ "!=",
38035
+ "<=",
38036
+ ">=",
38037
+ "&&",
38038
+ "||",
38039
+ "??",
38040
+ "?.",
38041
+ "++",
38042
+ "--",
38043
+ "+=",
38044
+ "-=",
38045
+ "*=",
38046
+ "/=",
38047
+ "%=",
38048
+ "&=",
38049
+ "|=",
38050
+ "^=",
38051
+ "**",
38052
+ "<<",
38053
+ ">>",
38054
+ "{",
38055
+ "}",
38056
+ "(",
38057
+ ")",
38058
+ "[",
38059
+ "]",
38060
+ ";",
38061
+ ",",
38062
+ "<",
38063
+ ">",
38064
+ "+",
38065
+ "-",
38066
+ "*",
38067
+ "/",
38068
+ "%",
38069
+ "&",
38070
+ "|",
38071
+ "^",
38072
+ "!",
38073
+ "~",
38074
+ "?",
38075
+ ":",
38076
+ "=",
38077
+ ".",
38078
+ "@",
38079
+ "#"
38080
+ ];
38081
+ var KEYWORDS_BEFORE_REGEX = /* @__PURE__ */ new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
38082
+ function tokenize5(src) {
38083
+ const out = [];
38084
+ let i = 0, line = 1, nl = false;
38085
+ const n = src.length;
38086
+ const prevAllowsRegex = () => {
38087
+ const p = out[out.length - 1];
38088
+ if (!p) return true;
38089
+ if (p.t === "num" || p.t === "str" || p.t === "tpl" || p.t === "re") return false;
38090
+ if (p.t === "id") return KEYWORDS_BEFORE_REGEX.has(p.v);
38091
+ return !(p.v === ")" || p.v === "]" || p.v === "}");
38092
+ };
38093
+ const push = (t, v, extra) => {
38094
+ out.push({ t, v, line, nl, ...extra });
38095
+ nl = false;
38096
+ };
38097
+ while (i < n) {
38098
+ const c = src[i];
38099
+ if (c === "\n") {
38100
+ line++;
38101
+ nl = true;
38102
+ i++;
38103
+ continue;
38104
+ }
38105
+ if (c === " " || c === " " || c === "\r" || c === "\f" || c === "\v" || c === "\uFEFF" || c === "\xA0") {
38106
+ i++;
38107
+ continue;
38108
+ }
38109
+ if (c === "/" && src[i + 1] === "/") {
38110
+ while (i < n && src[i] !== "\n") i++;
38111
+ continue;
38112
+ }
38113
+ if (c === "/" && src[i + 1] === "*") {
38114
+ const end2 = src.indexOf("*/", i + 2);
38115
+ const stop = end2 < 0 ? n : end2 + 2;
38116
+ for (let k = i; k < stop; k++) if (src[k] === "\n") {
38117
+ line++;
38118
+ nl = true;
38119
+ }
38120
+ i = stop;
38121
+ continue;
38122
+ }
38123
+ if (/[A-Za-z_$À-￿]/.test(c)) {
38124
+ let j = i + 1;
38125
+ while (j < n && /[\w$À-￿]/.test(src[j])) j++;
38126
+ push("id", src.slice(i, j));
38127
+ i = j;
38128
+ continue;
38129
+ }
38130
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(src[i + 1] ?? "")) {
38131
+ let j = i + 1;
38132
+ while (j < n && /[\w.]/.test(src[j])) {
38133
+ if ((src[j] === "e" || src[j] === "E") && (src[j + 1] === "-" || src[j + 1] === "+")) j++;
38134
+ j++;
38135
+ }
38136
+ push("num", src.slice(i, j));
38137
+ i = j;
38138
+ continue;
38139
+ }
38140
+ if (c === '"' || c === "'") {
38141
+ let j = i + 1, v = "";
38142
+ while (j < n && src[j] !== c) {
38143
+ if (src[j] === "\\") {
38144
+ v += src[j + 1] ?? "";
38145
+ j += 2;
38146
+ continue;
38147
+ }
38148
+ if (src[j] === "\n") break;
38149
+ v += src[j++];
38150
+ }
38151
+ push("str", v);
38152
+ i = j + 1;
38153
+ continue;
38154
+ }
38155
+ if (c === "`") {
38156
+ const startLine = line;
38157
+ const parts = [];
38158
+ let j = i + 1, text2 = "";
38159
+ while (j < n && src[j] !== "`") {
38160
+ if (src[j] === "\\") {
38161
+ text2 += src[j + 1] ?? "";
38162
+ j += 2;
38163
+ continue;
38164
+ }
38165
+ if (src[j] === "$" && src[j + 1] === "{") {
38166
+ let depth = 1, k = j + 2;
38167
+ while (k < n && depth) {
38168
+ const ch = src[k];
38169
+ if (ch === "{") depth++;
38170
+ else if (ch === "}") depth--;
38171
+ else if (ch === '"' || ch === "'" || ch === "`") {
38172
+ const q2 = ch;
38173
+ k++;
38174
+ while (k < n && src[k] !== q2) {
38175
+ if (src[k] === "\\") k++;
38176
+ k++;
38177
+ }
38178
+ } else if (ch === "\n") line++;
38179
+ if (depth) k++;
38180
+ }
38181
+ parts.push({ text: text2 });
38182
+ parts.push({ expr: src.slice(j + 2, k), line });
38183
+ text2 = "";
38184
+ j = k + 1;
38185
+ continue;
38186
+ }
38187
+ if (src[j] === "\n") line++;
38188
+ text2 += src[j++];
38189
+ }
38190
+ parts.push({ text: text2 });
38191
+ out.push({ t: "tpl", v: parts, line: startLine, nl });
38192
+ nl = false;
38193
+ i = j + 1;
38194
+ continue;
38195
+ }
38196
+ if (c === "/" && prevAllowsRegex()) {
38197
+ let j = i + 1, inClass = false;
38198
+ while (j < n && src[j] !== "\n") {
38199
+ if (src[j] === "\\") {
38200
+ j += 2;
38201
+ continue;
38202
+ }
38203
+ if (src[j] === "[") inClass = true;
38204
+ else if (src[j] === "]") inClass = false;
38205
+ else if (src[j] === "/" && !inClass) break;
38206
+ j++;
38207
+ }
38208
+ j++;
38209
+ while (j < n && /[a-z]/i.test(src[j])) j++;
38210
+ push("re", src.slice(i, j));
38211
+ i = j;
38212
+ continue;
38213
+ }
38214
+ const p = PUNCT5.find((x) => src.startsWith(x, i));
38215
+ if (!p) throw new ParseError2(`an unexpected character "${c}"`, line);
38216
+ push("p", p);
38217
+ i += p.length;
38218
+ }
38219
+ out.push({ t: "eof", v: "", line, nl: true });
38220
+ return out;
38221
+ }
38222
+ function parse3(src) {
38223
+ const toks = tokenize5(src);
38224
+ let pos = 0;
38225
+ const peek = (k = 0) => toks[Math.min(pos + k, toks.length - 1)];
38226
+ const at2 = (v, k = 0) => {
38227
+ const t = peek(k);
38228
+ return (t.t === "p" || t.t === "id") && t.v === v;
38229
+ };
38230
+ const next = () => {
38231
+ 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);
38232
+ return toks[pos++];
38233
+ };
38234
+ const fail3 = (what) => {
38235
+ throw new ParseError2(`${what} (found "${typeof peek().v === "string" ? peek().v : "a template"}")`, peek().line);
38236
+ };
38237
+ const eat = (v) => {
38238
+ if (!at2(v)) fail3(`expected "${v}"`);
38239
+ return next();
38240
+ };
38241
+ const opt2 = (v) => at2(v) ? next() : null;
38242
+ const semi = () => {
38243
+ if (opt2(";")) return;
38244
+ if (at2("}") || peek().t === "eof" || peek().nl) return;
38245
+ fail3("expected the end of a statement");
38246
+ };
38247
+ const skipBalanced2 = () => {
38248
+ const open = next().v;
38249
+ const close = { "(": ")", "[": "]", "{": "}", "<": ">" }[open];
38250
+ let depth = 1;
38251
+ while (depth && peek().t !== "eof") {
38252
+ const t = next();
38253
+ if (t.t !== "p") continue;
38254
+ if (t.v === open) depth++;
38255
+ else if (t.v === close) depth--;
38256
+ else if (open === "<" && t.v === ">>") depth -= 2;
38257
+ else if (open === "<" && t.v === ">>>") depth -= 3;
38258
+ else if (open === "<" && t.v === "=>") {
38259
+ }
38260
+ }
38261
+ };
38262
+ const skipType = (stops = [",", ")", "=", ";", "{", "}", "]", "=>"]) => {
38263
+ let guard = 0;
38264
+ const stopSet = new Set(stops);
38265
+ for (; ; ) {
38266
+ if (++guard > 1e4) fail3("a type Thunder cannot follow");
38267
+ const t = peek();
38268
+ if (t.t === "eof") return;
38269
+ if (t.t === "p" && (t.v === "(" || t.v === "[" || t.v === "{" || t.v === "<")) {
38270
+ if (t.v === "{" && stopSet.has("{") && guard > 1) return;
38271
+ skipBalanced2();
38272
+ if (at2("=>") && t.v === "(" && !stopSet.has("=>")) {
38273
+ next();
38274
+ continue;
38275
+ }
38276
+ continue;
38277
+ }
38278
+ if (t.t === "p" && (t.v === "|" || t.v === "&" || t.v === "." || t.v === "?" || t.v === ":" && !stopSet.has(":"))) {
38279
+ if (t.v === "?" && stopSet.has("?")) return;
38280
+ next();
38281
+ continue;
38282
+ }
38283
+ if (t.t === "p" && t.v === "=>") {
38284
+ if (stopSet.has("=>")) return;
38285
+ next();
38286
+ continue;
38287
+ }
38288
+ if (t.t === "id" || t.t === "str" || t.t === "num" || t.t === "tpl") {
38289
+ if (t.t === "id" && guard > 1 && t.nl && !["extends", "keyof", "typeof", "infer", "is", "readonly", "unique"].includes(t.v)) {
38290
+ const prev = toks[pos - 1];
38291
+ if (!(prev.t === "p" && (prev.v === "|" || prev.v === "&" || prev.v === ":" || prev.v === "." || prev.v === "=>" || prev.v === "?"))) return;
38292
+ }
38293
+ next();
38294
+ continue;
38295
+ }
38296
+ if (t.t === "p" && t.v === "-" && peek(1).t === "num") {
38297
+ next();
38298
+ next();
38299
+ continue;
38300
+ }
38301
+ if (stopSet.has(t.v)) return;
38302
+ return;
38303
+ }
38304
+ };
38305
+ const program = () => {
38306
+ const body2 = [];
38307
+ while (peek().t !== "eof") {
38308
+ const s = statement2();
38309
+ if (s) body2.push(s);
38310
+ }
38311
+ return { type: "Program", body: body2 };
38312
+ };
38313
+ const block = () => {
38314
+ const line = eat("{").line;
38315
+ const body2 = [];
38316
+ while (!at2("}")) {
38317
+ if (peek().t === "eof") fail3('expected "}"');
38318
+ const s = statement2();
38319
+ if (s) body2.push(s);
38320
+ }
38321
+ next();
38322
+ return { type: "Block", body: body2, line };
38323
+ };
38324
+ 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";
38325
+ const skipTypeDecl = () => {
38326
+ const line = peek().line;
38327
+ if (at2("abstract")) {
38328
+ next();
38329
+ return classDecl();
38330
+ }
38331
+ if (at2("declare")) {
38332
+ next();
38333
+ }
38334
+ if (at2("const")) next();
38335
+ if (at2("enum")) {
38336
+ next();
38337
+ next();
38338
+ skipBalanced2();
38339
+ return { type: "Empty", line };
38340
+ }
38341
+ if (at2("interface")) {
38342
+ next();
38343
+ next();
38344
+ if (at2("<")) skipBalanced2();
38345
+ while (!at2("{")) next();
38346
+ skipBalanced2();
38347
+ return { type: "Empty", line };
38348
+ }
38349
+ if (at2("namespace") || at2("module")) {
38350
+ next();
38351
+ next();
38352
+ skipBalanced2();
38353
+ return { type: "Empty", line };
38354
+ }
38355
+ if (at2("type")) {
38356
+ next();
38357
+ next();
38358
+ if (at2("<")) skipBalanced2();
38359
+ eat("=");
38360
+ skipType([";"]);
38361
+ semi();
38362
+ return { type: "Empty", line };
38363
+ }
38364
+ while (!at2(";") && !peek().nl && peek().t !== "eof") {
38365
+ if (at2("{") || at2("(")) skipBalanced2();
38366
+ else next();
38367
+ }
38368
+ opt2(";");
38369
+ return { type: "Empty", line };
38370
+ };
38371
+ const decorators = () => {
38372
+ while (at2("@")) {
38373
+ next();
38374
+ next();
38375
+ while (at2(".")) {
38376
+ next();
38377
+ next();
38378
+ }
38379
+ if (at2("(")) skipBalanced2();
38380
+ }
38381
+ };
38382
+ const statement2 = () => {
38383
+ const t = peek();
38384
+ const line = t.line;
38385
+ decorators();
38386
+ if (at2(";")) {
38387
+ next();
38388
+ return null;
38389
+ }
38390
+ if (at2("{")) return block();
38391
+ if (isTypeDecl()) return skipTypeDecl();
38392
+ if (at2("import") && !at2("(", 1) && !at2(".", 1)) return importDecl();
38393
+ if (at2("export")) return exportDecl();
38394
+ if (at2("const") || at2("let") || at2("var") || at2("using") && peek(1).t === "id" && !peek(1).nl) {
38395
+ const d = varDecl();
38396
+ semi();
38397
+ return d;
38398
+ }
38399
+ if (at2("function") || at2("async") && at2("function", 1) && !peek(1).nl) return functionDecl();
38400
+ if (at2("class")) return classDecl();
38401
+ if (at2("return")) {
38402
+ next();
38403
+ const arg = at2(";") || at2("}") || peek().nl || peek().t === "eof" ? null : expression();
38404
+ semi();
38405
+ return { type: "Return", arg, line };
38406
+ }
38407
+ if (at2("throw")) {
38408
+ next();
38409
+ const arg = expression();
38410
+ semi();
38411
+ return { type: "Throw", arg, line };
38412
+ }
38413
+ if (at2("if")) {
38414
+ next();
38415
+ eat("(");
38416
+ const test = expression();
38417
+ eat(")");
38418
+ const cons = statement2();
38419
+ const alt = opt2("else") ? statement2() : null;
38420
+ return { type: "If", test, cons, alt, line };
38421
+ }
38422
+ if (at2("try")) {
38423
+ next();
38424
+ const body2 = block();
38425
+ let param = null, handler = null, finalizer = null;
38426
+ if (opt2("catch")) {
38427
+ if (opt2("(")) {
38428
+ param = pattern2();
38429
+ if (opt2(":")) skipType([")"]);
38430
+ eat(")");
38431
+ }
38432
+ handler = block();
38433
+ }
38434
+ if (opt2("finally")) finalizer = block();
38435
+ return { type: "Try", body: body2, param, handler, finalizer, line };
38436
+ }
38437
+ if (at2("for")) {
38438
+ next();
38439
+ opt2("await");
38440
+ eat("(");
38441
+ let init = null, iter = null, kind = "for";
38442
+ if (at2("const") || at2("let") || at2("var")) {
38443
+ const k = next().v;
38444
+ const id2 = pattern2();
38445
+ if (opt2(":")) skipType([";", "=", "of", "in"]);
38446
+ if (at2("of") || at2("in")) {
38447
+ kind = next().v;
38448
+ iter = expression();
38449
+ init = { type: "Var", kind: k, decls: [{ id: id2, init: null, line }], line };
38450
+ } else {
38451
+ const decls = [{ id: id2, init: opt2("=") ? assign() : null, line }];
38452
+ while (opt2(",")) {
38453
+ const id22 = pattern2();
38454
+ decls.push({ id: id22, init: opt2("=") ? assign() : null, line });
38455
+ }
38456
+ init = { type: "Var", kind: k, decls, line };
38457
+ }
38458
+ } else if (!at2(";")) {
38459
+ const e = expression(true);
38460
+ if (at2("of") || at2("in")) {
38461
+ kind = next().v;
38462
+ iter = expression();
38463
+ init = { type: "Expr", expr: e, line };
38464
+ } else init = { type: "Expr", expr: e, line };
38465
+ }
38466
+ let test = null, update = null;
38467
+ if (kind === "for") {
38468
+ eat(";");
38469
+ if (!at2(";")) test = expression();
38470
+ eat(";");
38471
+ if (!at2(")")) update = expression();
38472
+ }
38473
+ eat(")");
38474
+ const body2 = statement2();
38475
+ return { type: "Loop", kind, init, iter, test, update, body: body2, line };
38476
+ }
38477
+ if (at2("while")) {
38478
+ next();
38479
+ eat("(");
38480
+ const test = expression();
38481
+ eat(")");
38482
+ const body2 = statement2();
38483
+ return { type: "Loop", kind: "while", test, body: body2, line };
38484
+ }
38485
+ if (at2("do")) {
38486
+ next();
38487
+ const body2 = statement2();
38488
+ eat("while");
38489
+ eat("(");
38490
+ const test = expression();
38491
+ eat(")");
38492
+ opt2(";");
38493
+ return { type: "Loop", kind: "do", test, body: body2, line };
38494
+ }
38495
+ if (at2("switch")) {
38496
+ next();
38497
+ eat("(");
38498
+ const disc = expression();
38499
+ eat(")");
38500
+ eat("{");
38501
+ const cases = [];
38502
+ while (!at2("}")) {
38503
+ let test = null;
38504
+ if (opt2("default")) eat(":");
38505
+ else {
38506
+ eat("case");
38507
+ test = expression();
38508
+ eat(":");
38509
+ }
38510
+ const body2 = [];
38511
+ while (!at2("case") && !at2("default") && !at2("}")) {
38512
+ const s = statement2();
38513
+ if (s) body2.push(s);
38514
+ }
38515
+ cases.push({ test, body: body2 });
38516
+ }
38517
+ next();
38518
+ return { type: "Switch", disc, cases, line };
38519
+ }
38520
+ if (at2("break") || at2("continue")) {
38521
+ next();
38522
+ if (peek().t === "id" && !peek().nl) next();
38523
+ semi();
38524
+ return { type: "Jump", line };
38525
+ }
38526
+ if (t.t === "id" && at2(":", 1) && !["default", "case"].includes(t.v)) {
38527
+ next();
38528
+ next();
38529
+ return statement2();
38530
+ }
38531
+ const expr = expression();
38532
+ semi();
38533
+ return { type: "Expr", expr, line };
38534
+ };
38535
+ const importDecl = () => {
38536
+ const line = next().line;
38537
+ if (at2("type") && !at2(",", 1) && !at2("from", 1)) next();
38538
+ const names = [];
38539
+ if (peek().t === "str") {
38540
+ next();
38541
+ semi();
38542
+ return { type: "Import", from: null, names, line };
38543
+ }
38544
+ if (peek().t === "id" && !at2("{") && !at2("*")) {
38545
+ names.push({ imported: "default", local: next().v });
38546
+ opt2(",");
38547
+ }
38548
+ if (opt2("*")) {
38549
+ eat("as");
38550
+ names.push({ imported: "*", local: next().v });
38551
+ }
38552
+ if (opt2("{")) {
38553
+ while (!at2("}")) {
38554
+ if (at2("type") && peek(1).t === "id" && !at2(",", 1) && !at2("}", 1) && !at2("as", 1)) next();
38555
+ const imported = next().v;
38556
+ const local = opt2("as") ? next().v : imported;
38557
+ names.push({ imported, local });
38558
+ if (!opt2(",")) break;
38559
+ }
38560
+ eat("}");
38561
+ }
38562
+ eat("from");
38563
+ const from = next().v;
38564
+ if (at2("assert") || at2("with")) {
38565
+ next();
38566
+ skipBalanced2();
38567
+ }
38568
+ semi();
38569
+ return { type: "Import", from, names, line };
38570
+ };
38571
+ const exportDecl = () => {
38572
+ const line = next().line;
38573
+ if (at2("type") && (at2("{", 1) || at2("*", 1))) next();
38574
+ if (opt2("default")) {
38575
+ if (at2("function") || at2("async") && at2("function", 1)) {
38576
+ const f = functionDecl(true);
38577
+ return { type: "Export", decl: f, isDefault: true, line };
38578
+ }
38579
+ if (at2("class")) {
38580
+ const c = classDecl(true);
38581
+ return { type: "Export", decl: c, isDefault: true, line };
38582
+ }
38583
+ const expr = assign();
38584
+ semi();
38585
+ return { type: "Export", expr, isDefault: true, line };
38586
+ }
38587
+ if (at2("{") || at2("*")) {
38588
+ const names = [];
38589
+ if (opt2("*")) {
38590
+ if (opt2("as")) names.push({ local: "*", exported: next().v });
38591
+ } else {
38592
+ next();
38593
+ while (!at2("}")) {
38594
+ if (at2("type") && peek(1).t === "id" && !at2(",", 1) && !at2("}", 1)) next();
38595
+ const local = next().v;
38596
+ const exported = opt2("as") ? next().v : local;
38597
+ names.push({ local, exported });
38598
+ if (!opt2(",")) break;
38599
+ }
38600
+ eat("}");
38601
+ }
38602
+ const from = opt2("from") ? next().v : null;
38603
+ semi();
38604
+ return { type: "Export", names, from, line };
38605
+ }
38606
+ if (at2("=")) {
38607
+ next();
38608
+ assign();
38609
+ semi();
38610
+ return { type: "Empty", line };
38611
+ }
38612
+ const decl2 = statement2();
38613
+ return { type: "Export", decl: decl2, line };
38614
+ };
38615
+ const varDecl = () => {
38616
+ const line = peek().line;
38617
+ const kind = next().v;
38618
+ const decls = [];
38619
+ do {
38620
+ const dline = peek().line;
38621
+ const id2 = pattern2();
38622
+ if (opt2("!")) {
38623
+ }
38624
+ if (opt2(":")) skipType([",", "=", ";", "}"]);
38625
+ const init = opt2("=") ? assign() : null;
38626
+ decls.push({ id: id2, init, line: dline });
38627
+ } while (opt2(","));
38628
+ return { type: "Var", kind, decls, line };
38629
+ };
38630
+ const pattern2 = () => {
38631
+ const line = peek().line;
38632
+ if (at2("{")) {
38633
+ next();
38634
+ const props = [];
38635
+ while (!at2("}")) {
38636
+ if (opt2("...")) {
38637
+ props.push({ rest: pattern2() });
38638
+ opt2(",");
38639
+ continue;
38640
+ }
38641
+ let key;
38642
+ if (at2("[")) {
38643
+ next();
38644
+ key = { computed: expression() };
38645
+ eat("]");
38646
+ } else key = next().v;
38647
+ let value;
38648
+ if (opt2(":")) value = pattern2();
38649
+ else value = { type: "Id", name: typeof key === "string" ? key : "?", line };
38650
+ if (opt2("=")) value = { type: "Default", target: value, value: assign(), line };
38651
+ props.push({ key, value });
38652
+ if (!opt2(",")) break;
38653
+ }
38654
+ eat("}");
38655
+ return { type: "ObjPat", props, line };
38656
+ }
38657
+ if (at2("[")) {
38658
+ next();
38659
+ const elems = [];
38660
+ while (!at2("]")) {
38661
+ if (at2(",")) {
38662
+ next();
38663
+ elems.push(null);
38664
+ continue;
38665
+ }
38666
+ if (opt2("...")) {
38667
+ elems.push({ type: "Rest", arg: pattern2(), line });
38668
+ opt2(",");
38669
+ continue;
38670
+ }
38671
+ let p = pattern2();
38672
+ if (opt2("=")) p = { type: "Default", target: p, value: assign(), line };
38673
+ elems.push(p);
38674
+ if (!opt2(",")) break;
38675
+ }
38676
+ eat("]");
38677
+ return { type: "ArrPat", elems, line };
38678
+ }
38679
+ const t = next();
38680
+ if (t.t !== "id") {
38681
+ pos--;
38682
+ fail3("expected a name");
38683
+ }
38684
+ return { type: "Id", name: t.v, line: t.line };
38685
+ };
38686
+ const params = () => {
38687
+ eat("(");
38688
+ const ps = [];
38689
+ while (!at2(")")) {
38690
+ decorators();
38691
+ while (["public", "private", "protected", "readonly", "override"].includes(peek().v) && peek(1).t === "id") next();
38692
+ if (opt2("...")) {
38693
+ const p2 = pattern2();
38694
+ if (opt2("?")) {
38695
+ }
38696
+ if (opt2(":")) skipType([",", ")", "="]);
38697
+ ps.push({ type: "Rest", arg: p2 });
38698
+ opt2(",");
38699
+ continue;
38700
+ }
38701
+ let p = pattern2();
38702
+ opt2("?");
38703
+ if (opt2(":")) skipType([",", ")", "="]);
38704
+ if (opt2("=")) p = { type: "Default", target: p, value: assign(), line: p.line };
38705
+ ps.push(p);
38706
+ if (!opt2(",")) break;
38707
+ }
38708
+ eat(")");
38709
+ return ps;
38710
+ };
38711
+ const functionBody = () => at2("{") ? block() : null;
38712
+ const functionDecl = (allowAnonymous = false) => {
38713
+ const line = peek().line;
38714
+ const isAsync = !!opt2("async");
38715
+ eat("function");
38716
+ opt2("*");
38717
+ let name = null;
38718
+ if (peek().t === "id" && !at2("(")) name = next().v;
38719
+ else if (!allowAnonymous) fail3("expected a function name");
38720
+ if (at2("<")) skipBalanced2();
38721
+ const ps = params();
38722
+ if (opt2(":")) skipType(["{", ";"]);
38723
+ const body2 = functionBody();
38724
+ if (!body2) {
38725
+ opt2(";");
38726
+ return { type: "Empty", line };
38727
+ }
38728
+ return { type: "Function", name, params: ps, body: body2, isAsync, line };
38729
+ };
38730
+ const classDecl = (allowAnonymous = false) => {
38731
+ const line = eat("class").line;
38732
+ let name = null;
38733
+ if (peek().t === "id" && !at2("extends") && !at2("implements") && !at2("{")) name = next().v;
38734
+ else if (!allowAnonymous) {
38735
+ }
38736
+ if (at2("<")) skipBalanced2();
38737
+ let superClass = null;
38738
+ if (opt2("extends")) {
38739
+ superClass = postfix(primary());
38740
+ if (at2("<")) skipBalanced2();
38741
+ }
38742
+ if (opt2("implements")) {
38743
+ while (!at2("{")) next();
38744
+ }
38745
+ eat("{");
38746
+ const members = [];
38747
+ while (!at2("}")) {
38748
+ if (opt2(";")) continue;
38749
+ decorators();
38750
+ let isStatic = false;
38751
+ const mline = peek().line;
38752
+ while (["public", "private", "protected", "readonly", "static", "abstract", "override", "declare", "accessor"].includes(peek().v) && !at2("(", 1) && !at2("=", 1) && !at2(":", 1) && !at2(";", 1) && !at2("?", 1)) {
38753
+ if (next().v === "static") isStatic = true;
38754
+ }
38755
+ if (at2("static") && at2("{", 1)) {
38756
+ next();
38757
+ block();
38758
+ continue;
38759
+ }
38760
+ const isAsync = at2("async") && !at2("(", 1) && !peek(1).nl ? !!next() : false;
38761
+ opt2("*");
38762
+ let kind = "method";
38763
+ if ((at2("get") || at2("set")) && !at2("(", 1) && !at2("=", 1) && !at2(":", 1)) {
38764
+ kind = next().v;
38765
+ }
38766
+ let key;
38767
+ if (at2("[")) {
38768
+ next();
38769
+ expression();
38770
+ eat("]");
38771
+ key = "[computed]";
38772
+ } else if (at2("#")) {
38773
+ next();
38774
+ key = "#" + next().v;
38775
+ } else key = next().v;
38776
+ opt2("?");
38777
+ opt2("!");
38778
+ if (at2("(") || at2("<")) {
38779
+ if (at2("<")) skipBalanced2();
38780
+ const ps = params();
38781
+ if (opt2(":")) skipType(["{", ";"]);
38782
+ const body2 = functionBody();
38783
+ if (!body2) {
38784
+ opt2(";");
38785
+ continue;
38786
+ }
38787
+ members.push({ kind, key, isStatic, fn: { type: "Arrow", params: ps, body: body2, isAsync, line: mline, isMethod: true, name: key }, line: mline });
38788
+ } else {
38789
+ if (opt2(":")) skipType(["=", ";", "}"]);
38790
+ const value = opt2("=") ? assign() : null;
38791
+ semi();
38792
+ members.push({ kind: "field", key, isStatic, value, line: mline });
38793
+ }
38794
+ }
38795
+ eat("}");
38796
+ return { type: "Class", name, superClass, members, line };
38797
+ };
38798
+ const expression = (noIn = false) => {
38799
+ const line = peek().line;
38800
+ const first = assign(noIn);
38801
+ if (!at2(",")) return first;
38802
+ const list3 = [first];
38803
+ while (opt2(",")) list3.push(assign(noIn));
38804
+ return { type: "Seq", list: list3, line };
38805
+ };
38806
+ const isArrowAhead = () => {
38807
+ let k = pos;
38808
+ if (toks[k].v === "async" && toks[k].t === "id") k++;
38809
+ if (toks[k].t === "p" && toks[k].v === "<") {
38810
+ let d = 0;
38811
+ for (; k < toks.length; k++) {
38812
+ if (toks[k].v === "<") d++;
38813
+ else if (toks[k].v === ">") {
38814
+ d--;
38815
+ if (!d) {
38816
+ k++;
38817
+ break;
38818
+ }
38819
+ } else if (toks[k].t === "eof") return false;
38820
+ }
38821
+ }
38822
+ if (toks[k].t === "id" && toks[k + 1]?.v === "=>") return true;
38823
+ if (!(toks[k].t === "p" && toks[k].v === "(")) return false;
38824
+ let depth = 0;
38825
+ for (; k < toks.length; k++) {
38826
+ const t = toks[k];
38827
+ if (t.t !== "p") continue;
38828
+ if (t.v === "(" || t.v === "[" || t.v === "{") depth++;
38829
+ else if (t.v === ")" || t.v === "]" || t.v === "}") {
38830
+ depth--;
38831
+ if (!depth) break;
38832
+ }
38833
+ if (t.t === "eof") return false;
38834
+ }
38835
+ const after = toks[k + 1];
38836
+ if (!after) return false;
38837
+ if (after.t === "p" && after.v === "=>") return true;
38838
+ if (after.t === "p" && after.v === ":") {
38839
+ let d = 0;
38840
+ for (let j = k + 2; j < toks.length && j < k + 200; j++) {
38841
+ const t = toks[j];
38842
+ if (t.t === "p" && (t.v === "(" || t.v === "[" || t.v === "{" || t.v === "<")) d++;
38843
+ else if (t.t === "p" && (t.v === ")" || t.v === "]" || t.v === "}" || t.v === ">")) {
38844
+ d--;
38845
+ if (d < 0) return false;
38846
+ } else if (t.t === "p" && t.v === "=>" && d === 0) return true;
38847
+ else if (t.t === "p" && (t.v === ";" || t.v === "," || t.v === "=") && d === 0) return false;
38848
+ else if (t.t === "eof") return false;
38849
+ }
38850
+ }
38851
+ return false;
38852
+ };
38853
+ const arrow = () => {
38854
+ const line = peek().line;
38855
+ const isAsync = at2("async") && !at2("=>", 1) ? !!next() : false;
38856
+ if (at2("<")) skipBalanced2();
38857
+ let ps;
38858
+ if (peek().t === "id" && at2("=>", 1)) ps = [{ type: "Id", name: next().v, line }];
38859
+ else {
38860
+ ps = params();
38861
+ if (opt2(":")) skipType(["=>"]);
38862
+ }
38863
+ eat("=>");
38864
+ const body2 = at2("{") ? block() : assign();
38865
+ return { type: "Arrow", params: ps, body: body2, isAsync, line };
38866
+ };
38867
+ const ASSIGN_OPS2 = /* @__PURE__ */ new Set(["=", "+=", "-=", "*=", "/=", "%=", "**=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "&&=", "||=", "??="]);
38868
+ const assign = (noIn = false) => {
38869
+ if ((at2("(") || at2("<") || peek().t === "id" && at2("=>", 1) || at2("async") && (at2("(", 1) || peek(1).t === "id" || at2("<", 1))) && isArrowAhead()) return arrow();
38870
+ if (at2("yield")) {
38871
+ const line2 = next().line;
38872
+ opt2("*");
38873
+ const arg = at2(")") || at2("]") || at2("}") || at2(",") || at2(";") || peek().nl ? null : assign(noIn);
38874
+ return { type: "Await", arg, line: line2 };
38875
+ }
38876
+ const line = peek().line;
38877
+ const left = conditional(noIn);
38878
+ if (peek().t === "p" && ASSIGN_OPS2.has(peek().v)) {
38879
+ const op = next().v;
38880
+ const right = assign(noIn);
38881
+ return { type: "Assign", op, left, right, line };
38882
+ }
38883
+ return left;
38884
+ };
38885
+ const conditional = (noIn) => {
38886
+ const line = peek().line;
38887
+ const test = binary(0, noIn);
38888
+ if (!at2("?")) return test;
38889
+ next();
38890
+ const cons = assign();
38891
+ eat(":");
38892
+ const alt = assign(noIn);
38893
+ return { type: "Cond", test, cons, alt, line };
38894
+ };
38895
+ const PREC2 = {
38896
+ "??": 1,
38897
+ "||": 2,
38898
+ "&&": 3,
38899
+ "|": 4,
38900
+ "^": 5,
38901
+ "&": 6,
38902
+ "==": 7,
38903
+ "!=": 7,
38904
+ "===": 7,
38905
+ "!==": 7,
38906
+ "<": 8,
38907
+ ">": 8,
38908
+ "<=": 8,
38909
+ ">=": 8,
38910
+ instanceof: 8,
38911
+ in: 8,
38912
+ "<<": 9,
38913
+ ">>": 9,
38914
+ ">>>": 9,
38915
+ "+": 10,
38916
+ "-": 10,
38917
+ "*": 11,
38918
+ "/": 11,
38919
+ "%": 11,
38920
+ "**": 12
38921
+ };
38922
+ const binary = (minPrec, noIn) => {
38923
+ let left = unary();
38924
+ for (; ; ) {
38925
+ const t = peek();
38926
+ if (t.t === "id" && (t.v === "as" || t.v === "satisfies") && !t.nl) {
38927
+ next();
38928
+ if (at2("const")) next();
38929
+ else skipType([",", ")", "]", ";", "}", "=", "?", ":", "&&", "||", "??", "=>"]);
38930
+ continue;
38931
+ }
38932
+ const op = t.t === "p" || t.t === "id" && (t.v === "instanceof" || t.v === "in" && !noIn) ? t.v : null;
38933
+ const prec = op != null ? PREC2[op] : void 0;
38934
+ if (prec === void 0 || prec < minPrec) return left;
38935
+ next();
38936
+ const right = binary(op === "**" ? prec : prec + 1, noIn);
38937
+ left = { type: op === "&&" || op === "||" || op === "??" ? "Logic" : "Bin", op, left, right, line: t.line };
38938
+ }
38939
+ };
38940
+ const unary = () => {
38941
+ const t = peek();
38942
+ if (t.t === "p" && ["!", "-", "+", "~"].includes(t.v)) {
38943
+ next();
38944
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
38945
+ }
38946
+ if (t.t === "p" && (t.v === "++" || t.v === "--")) {
38947
+ next();
38948
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
38949
+ }
38950
+ if (t.t === "id" && (t.v === "typeof" || t.v === "void" || t.v === "delete")) {
38951
+ next();
38952
+ return { type: "Unary", op: t.v, arg: unary(), line: t.line };
38953
+ }
38954
+ if (t.t === "id" && t.v === "await" && !(at2("(", 1) && false)) {
38955
+ const n2 = peek(1);
38956
+ if (!(n2.t === "p" && [")", "]", "}", ",", ";", "=", "."].includes(n2.v))) {
38957
+ next();
38958
+ return { type: "Await", arg: unary(), line: t.line };
38959
+ }
38960
+ }
38961
+ if (t.t === "p" && t.v === "<" && !isArrowAhead()) {
38962
+ skipBalanced2();
38963
+ return unary();
38964
+ }
38965
+ return postfix(primary());
38966
+ };
38967
+ const args = () => {
38968
+ eat("(");
38969
+ const list3 = [];
38970
+ while (!at2(")")) {
38971
+ if (opt2("...")) list3.push({ type: "Spread", arg: assign(), line: peek().line });
38972
+ else list3.push(assign());
38973
+ if (!opt2(",")) break;
38974
+ }
38975
+ eat(")");
38976
+ return list3;
38977
+ };
38978
+ const genericCallAhead = () => {
38979
+ if (!at2("<")) return false;
38980
+ let d = 0, k = pos;
38981
+ for (; k < toks.length && k < pos + 80; k++) {
38982
+ const t = toks[k];
38983
+ if (t.t === "p" && t.v === "<") d++;
38984
+ else if (t.t === "p" && t.v === ">") {
38985
+ d--;
38986
+ if (!d) break;
38987
+ } else if (t.t === "p" && t.v === ">>") {
38988
+ d -= 2;
38989
+ if (d <= 0) break;
38990
+ } else if (t.t === "p" && ![",", ".", "|", "&", "[", "]", "{", "}", ":", "?", "(", ")", "=>", ";"].includes(t.v)) return false;
38991
+ else if (t.t === "eof") return false;
38992
+ }
38993
+ return toks[k + 1]?.t === "p" && (toks[k + 1].v === "(" || toks[k + 1].v === "`");
38994
+ };
38995
+ const postfix = (expr) => {
38996
+ for (; ; ) {
38997
+ const t = peek();
38998
+ if (t.t === "p" && t.v === ".") {
38999
+ next();
39000
+ const name = at2("#") ? (next(), "#" + next().v) : next().v;
39001
+ expr = { type: "Member", object: expr, prop: name, line: t.line };
39002
+ continue;
39003
+ }
39004
+ if (t.t === "p" && t.v === "?.") {
39005
+ next();
39006
+ if (at2("(")) {
39007
+ expr = { type: "Call", callee: expr, args: args(), optional: true, line: t.line };
39008
+ continue;
39009
+ }
39010
+ if (at2("[")) {
39011
+ next();
39012
+ const p = expression();
39013
+ eat("]");
39014
+ expr = { type: "Member", object: expr, computed: p, prop: p.type === "Lit" ? String(p.value) : null, optional: true, line: t.line };
39015
+ continue;
39016
+ }
39017
+ expr = { type: "Member", object: expr, prop: next().v, optional: true, line: t.line };
39018
+ continue;
39019
+ }
39020
+ if (t.t === "p" && t.v === "[" && !t.nl) {
39021
+ next();
39022
+ const p = expression();
39023
+ eat("]");
39024
+ expr = { type: "Member", object: expr, computed: p, prop: p.type === "Lit" ? String(p.value) : null, line: t.line };
39025
+ continue;
39026
+ }
39027
+ if (t.t === "p" && t.v === "(") {
39028
+ if (t.nl && false) break;
39029
+ expr = { type: "Call", callee: expr, args: args(), line: t.line };
39030
+ continue;
39031
+ }
39032
+ if (t.t === "p" && t.v === "<" && genericCallAhead()) {
39033
+ skipBalanced2();
39034
+ continue;
39035
+ }
39036
+ if (t.t === "tpl") {
39037
+ next();
39038
+ expr = { type: "Tagged", tag: expr, tpl: tplNode(t), line: t.line };
39039
+ continue;
39040
+ }
39041
+ if (t.t === "p" && t.v === "!" && !t.nl && !at2("=", 1) && !at2("==", 1)) {
39042
+ next();
39043
+ continue;
39044
+ }
39045
+ if (t.t === "p" && (t.v === "++" || t.v === "--") && !t.nl) {
39046
+ next();
39047
+ expr = { type: "Unary", op: t.v, arg: expr, line: t.line };
39048
+ continue;
39049
+ }
39050
+ return expr;
39051
+ }
39052
+ };
39053
+ const tplNode = (t) => {
39054
+ const parts = t.v.map((p) => {
39055
+ if (p.expr == null) return { text: p.text };
39056
+ let e;
39057
+ try {
39058
+ e = parseExpressionAt(p.expr, p.line);
39059
+ } catch {
39060
+ e = { type: "Unknown", line: p.line };
39061
+ }
39062
+ return { expr: e };
39063
+ });
39064
+ return { type: "Tpl", parts, line: t.line };
39065
+ };
39066
+ const objectLiteral = () => {
39067
+ const line = eat("{").line;
39068
+ const props = [];
39069
+ while (!at2("}")) {
39070
+ const pline = peek().line;
39071
+ if (opt2("...")) {
39072
+ props.push({ spread: assign(), line: pline });
39073
+ if (!opt2(",")) break;
39074
+ continue;
39075
+ }
39076
+ let isAsync = false, kind = "init";
39077
+ if (at2("async") && !at2(",", 1) && !at2(":", 1) && !at2("(", 1) && !at2("}", 1)) {
39078
+ next();
39079
+ isAsync = true;
39080
+ }
39081
+ opt2("*");
39082
+ if ((at2("get") || at2("set")) && !at2(",", 1) && !at2(":", 1) && !at2("(", 1) && !at2("}", 1)) kind = next().v;
39083
+ let key, computed = null;
39084
+ if (at2("[")) {
39085
+ next();
39086
+ computed = assign();
39087
+ eat("]");
39088
+ key = computed.type === "Lit" ? String(computed.value) : null;
39089
+ } else {
39090
+ const kt = next();
39091
+ key = kt.t === "num" ? kt.v : kt.v;
39092
+ }
39093
+ if (at2("(") || at2("<")) {
39094
+ if (at2("<")) skipBalanced2();
39095
+ const ps = params();
39096
+ if (opt2(":")) skipType(["{"]);
39097
+ const body2 = block();
39098
+ props.push({ key, value: { type: "Arrow", params: ps, body: body2, isAsync, line: pline, isMethod: true, name: key }, method: true, kind, line: pline });
39099
+ } else if (opt2(":")) props.push({ key, computed, value: assign(), line: pline });
39100
+ else if (at2("=")) {
39101
+ next();
39102
+ props.push({ key, value: { type: "Id", name: key, line: pline }, shorthand: true, line: pline, dflt: assign() });
39103
+ } else props.push({ key, value: { type: "Id", name: key, line: pline }, shorthand: true, line: pline });
39104
+ if (!opt2(",")) break;
39105
+ }
39106
+ eat("}");
39107
+ return { type: "Obj", props, line };
39108
+ };
39109
+ const primary = () => {
39110
+ const t = peek();
39111
+ const line = t.line;
39112
+ if (t.t === "num") {
39113
+ next();
39114
+ return { type: "Lit", value: Number(t.v.replace(/_/g, "")), raw: t.v, line };
39115
+ }
39116
+ if (t.t === "str") {
39117
+ next();
39118
+ return { type: "Lit", value: t.v, line };
39119
+ }
39120
+ if (t.t === "tpl") {
39121
+ next();
39122
+ return tplNode(t);
39123
+ }
39124
+ if (t.t === "re") {
39125
+ next();
39126
+ return { type: "Lit", value: t.v, regex: true, line };
39127
+ }
39128
+ if (t.t === "p") {
39129
+ if (t.v === "(") {
39130
+ next();
39131
+ const e = expression();
39132
+ eat(")");
39133
+ return { ...e, paren: true };
39134
+ }
39135
+ if (t.v === "[") {
39136
+ next();
39137
+ const elems = [];
39138
+ while (!at2("]")) {
39139
+ if (at2(",")) {
39140
+ next();
39141
+ elems.push(null);
39142
+ continue;
39143
+ }
39144
+ if (opt2("...")) elems.push({ type: "Spread", arg: assign(), line });
39145
+ else elems.push(assign());
39146
+ if (!opt2(",")) break;
39147
+ }
39148
+ eat("]");
39149
+ return { type: "Arr", elems, line };
39150
+ }
39151
+ if (t.v === "{") return objectLiteral();
39152
+ if (t.v === "#") {
39153
+ next();
39154
+ next();
39155
+ return { type: "Id", name: "#private", line };
39156
+ }
39157
+ if (t.v === "@") {
39158
+ decorators();
39159
+ return primary();
39160
+ }
39161
+ fail3("an expression Thunder cannot read");
39162
+ }
39163
+ if (t.t === "id") {
39164
+ if (t.v === "function" || t.v === "async" && at2("function", 1)) {
39165
+ const f = functionDecl(true);
39166
+ return { type: "Arrow", params: f.params, body: f.body, isAsync: f.isAsync, line, name: f.name };
39167
+ }
39168
+ if (t.v === "class") {
39169
+ const c = classDecl(true);
39170
+ return { ...c, type: "ClassExpr" };
39171
+ }
39172
+ if (t.v === "new") {
39173
+ next();
39174
+ if (at2(".")) {
39175
+ next();
39176
+ next();
39177
+ return { type: "Id", name: "new.target", line };
39178
+ }
39179
+ let callee2 = primary();
39180
+ while (at2(".") || at2("[")) {
39181
+ if (opt2(".")) callee2 = { type: "Member", object: callee2, prop: next().v, line };
39182
+ else {
39183
+ next();
39184
+ const p = expression();
39185
+ eat("]");
39186
+ callee2 = { type: "Member", object: callee2, computed: p, line };
39187
+ }
39188
+ }
39189
+ if (at2("<") && genericCallAhead()) skipBalanced2();
39190
+ const a = at2("(") ? args() : [];
39191
+ return { type: "New", callee: callee2, args: a, line };
39192
+ }
39193
+ if (t.v === "this") {
39194
+ next();
39195
+ return { type: "This", line };
39196
+ }
39197
+ if (t.v === "super") {
39198
+ next();
39199
+ return { type: "Id", name: "super", line };
39200
+ }
39201
+ if (t.v === "true" || t.v === "false") {
39202
+ next();
39203
+ return { type: "Lit", value: t.v === "true", line };
39204
+ }
39205
+ if (t.v === "null") {
39206
+ next();
39207
+ return { type: "Lit", value: null, line };
39208
+ }
39209
+ if (t.v === "undefined") {
39210
+ next();
39211
+ return { type: "Lit", value: void 0, line };
39212
+ }
39213
+ if (t.v === "import" && at2("(", 1)) {
39214
+ next();
39215
+ const a = args();
39216
+ return { type: "Call", callee: { type: "Id", name: "import", line }, args: a, line };
39217
+ }
39218
+ if (t.v === "import" && at2(".", 1)) {
39219
+ next();
39220
+ next();
39221
+ next();
39222
+ return { type: "Id", name: "import.meta", line };
39223
+ }
39224
+ next();
39225
+ return { type: "Id", name: t.v, line };
39226
+ }
39227
+ fail3("an expression Thunder cannot read");
39228
+ };
39229
+ return { program, expressionOnly: () => {
39230
+ const e = expression();
39231
+ return e;
39232
+ } };
39233
+ }
39234
+ function parseExpressionAt(src, line) {
39235
+ const p = parse3(src);
39236
+ const e = p.expressionOnly();
39237
+ const shift = (n) => {
39238
+ if (!n || typeof n !== "object") return;
39239
+ if (typeof n.line === "number") n.line += line - 1;
39240
+ for (const v of Object.values(n)) {
39241
+ if (Array.isArray(v)) v.forEach(shift);
39242
+ else if (v && typeof v === "object") shift(v);
39243
+ }
39244
+ };
39245
+ shift(e);
39246
+ return e;
39247
+ }
39248
+ function parseProgram(src) {
39249
+ return parse3(src).program();
39250
+ }
39251
+
39252
+ // src/flow/access.mjs
39253
+ var ACCESS_SCHEMA = "thunder-access-v1";
39254
+ var CODE_FILE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i;
39255
+ var METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "del", "all", "options", "head"]);
39256
+ 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;
39257
+ 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)?$/;
39258
+ var IDENTITY_FN_EXACT = /* @__PURE__ */ new Set(["auth", "getAuth", "currentUser", "getServerSession", "getSession", "getUser", "requireUser", "requireSession", "verifyToken", "verifySession", "validateRequest", "getKindeServerSession", "useSession"]);
39259
+ var AUTH_MIDDLEWARE = /auth|authenticate|authenticated|requireUser|requireLogin|loggedIn|isLoggedIn|signedIn|protect|ensureUser|verifyToken|verifyJwt|jwt|passport|session|clerk|bearer/i;
39260
+ var ROLE_FN = /^(require|assert|ensure|check|is|has)(Admin|SuperAdmin|Staff|Role|Roles|Permission|Permissions|Scope|Scopes)$/;
39261
+ var GUARDISH = /assert|ensure|check|verify|authori[sz]e|^can[A-Z]|^can$|guard|permit|allow|policy|access|own|belongs|scope|forbid/i;
39262
+ 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;
39263
+ var MAYBE_GUARD_MIDDLEWARE = /authori[sz]|permi|polic|access|owner|ownership|guard|can[A-Z]|tenant|scope/i;
39264
+ var CLONE = "structuredClone";
39265
+ var BUF = "Buffer";
39266
+ var PASS_THROUGH = /* @__PURE__ */ new Set(["String", "Number", "Boolean", "BigInt", "parseInt", "parseFloat", "decodeURIComponent", "encodeURIComponent", "Array", "Object", CLONE]);
39267
+ 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"]);
39268
+ var PRISMA_READ = /* @__PURE__ */ new Set(["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "count", "aggregate", "groupBy"]);
39269
+ var PRISMA_WRITE = /* @__PURE__ */ new Set(["update", "updateMany", "delete", "deleteMany", "upsert"]);
39270
+ var PRISMA_ALL = /* @__PURE__ */ new Set([...PRISMA_READ, ...PRISMA_WRITE, "create", "createMany"]);
39271
+ 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"]]);
39272
+ var DB_NAMES = /^(prisma|db|database|tx|trx|knex|pool|pg|sql|conn|connection|orm|drizzle|client|dbClient|prismaClient)$/;
39273
+ var DB_FACTORIES = /^(PrismaClient|drizzle|knex|Knex|Pool|Client|postgres|createPool|createConnection|createClient|neon|Kysely)$/;
39274
+ var NEXT_EXITS = /* @__PURE__ */ new Set(["notFound", "redirect", "permanentRedirect", "forbidden", "unauthorized"]);
39275
+ var MAX_DEPTH = 5;
39276
+ var LOOKUP_NAME = /^(get|find|load|fetch|read|query|select|lookup|retrieve|search|list|show)([A-Z_]|$)|By[A-Z]|ById$|OrFail$|OrThrow$/;
39277
+ var LOOKUP_OWNER = /repo|repository|store|service|dao|model|db|database|client|api|prisma|orm|collection|table|manager|provider/i;
39278
+ 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$)/;
39279
+ var MAX_WORK = 4e4;
39280
+ var DATA = ["input", "ident", "recs", "unknown", "recFields"];
39281
+ var uniq = (a, b) => {
39282
+ if (!a?.length) return b;
39283
+ if (!b?.length) return a;
39284
+ const out = [...a];
39285
+ for (const x of b) if (!out.includes(x)) out.push(x);
39286
+ return out;
39287
+ };
39288
+ function join2(a, b) {
39289
+ if (!a) return b ?? {};
39290
+ if (!b) return a;
39291
+ const out = { ...a };
39292
+ for (const k of DATA) {
39293
+ const u = uniq(a[k], b[k]);
39294
+ if (u?.length) out[k] = u;
39295
+ }
39296
+ for (const [k, v] of Object.entries(b)) {
39297
+ if (DATA.includes(k)) continue;
39298
+ if (k === "obj" && a.obj) {
39299
+ const m = new Map(a.obj);
39300
+ for (const [pk, pv] of b.obj) m.set(pk, join2(m.get(pk), pv));
39301
+ out.obj = m;
39302
+ continue;
39303
+ }
39304
+ if (k === "lit") {
39305
+ if (a.lit !== b.lit) delete out.lit;
39306
+ continue;
39307
+ }
39308
+ if (out[k] === void 0) out[k] = v;
39309
+ }
39310
+ if ("lit" in a && !("lit" in b)) delete out.lit;
39311
+ return out;
39312
+ }
39313
+ var joinAll = (vals) => vals.reduce((acc, v) => join2(acc, v), null) ?? {};
39314
+ var dataOf = (v) => {
39315
+ const out = {};
39316
+ for (const k of DATA) if (v?.[k]?.length) out[k] = v[k];
39317
+ return out;
39318
+ };
39319
+ var hasData = (v) => DATA.some((k) => v?.[k]?.length);
39320
+ var Scope = class {
39321
+ constructor(parent = null, vars = /* @__PURE__ */ new Map()) {
39322
+ this.parent = parent;
39323
+ this.vars = vars;
39324
+ }
39325
+ find(name) {
39326
+ for (let s = this; s; s = s.parent) if (s.vars.has(name)) return s;
39327
+ return null;
39328
+ }
39329
+ get(name) {
39330
+ const s = this.find(name);
39331
+ return s ? s.vars.get(name) : void 0;
39332
+ }
39333
+ set(name, v) {
39334
+ const s = this.find(name) ?? this;
39335
+ s.vars.set(name, v);
39336
+ }
39337
+ declare(name, v) {
39338
+ this.vars.set(name, v);
39339
+ }
39340
+ };
39341
+ function cloneScope(s, memo = /* @__PURE__ */ new Map()) {
39342
+ if (!s || s.module) return s;
39343
+ if (memo.has(s)) return memo.get(s);
39344
+ const c = new Scope(cloneScope(s.parent, memo), new Map(s.vars));
39345
+ memo.set(s, c);
39346
+ return c;
39347
+ }
39348
+ function mergeScope(a, b) {
39349
+ for (let x = a, y = b; x && y && !x.module; x = x.parent, y = y.parent) {
39350
+ for (const [k, v] of y.vars) x.vars.set(k, join2(x.vars.get(k), v));
39351
+ }
39352
+ return a;
39353
+ }
39354
+ function newState(scope, frame) {
39355
+ return { scope, frame, guards: /* @__PURE__ */ new Map(), role: null, identity: null, unresolved: [], exited: null, calledNext: false, req: /* @__PURE__ */ new Map() };
39356
+ }
39357
+ function cloneState(s) {
39358
+ return { ...s, scope: cloneScope(s.scope), guards: new Map(s.guards), unresolved: [...s.unresolved], req: new Map(s.req) };
39359
+ }
39360
+ function mergeStates(a, b) {
39361
+ if (a.exited && b.exited) return a;
39362
+ if (a.exited) return b;
39363
+ if (b.exited) return a;
39364
+ const out = { ...a, scope: mergeScope(a.scope, b.scope) };
39365
+ out.guards = new Map([...a.guards].filter(([k]) => b.guards.has(k)));
39366
+ out.role = a.role && b.role ? a.role : null;
39367
+ out.identity = a.identity ?? b.identity;
39368
+ out.unresolved = uniq(a.unresolved, b.unresolved) ?? [];
39369
+ out.calledNext = a.calledNext || b.calledNext;
39370
+ out.req = new Map(a.req);
39371
+ for (const [k, v] of b.req) out.req.set(k, join2(out.req.get(k), v));
39372
+ return out;
39373
+ }
39374
+ var norm3 = (p) => {
39375
+ const parts = [];
39376
+ for (const seg of p.replace(/\\/g, "/").split("/")) {
39377
+ if (seg === "..") parts.pop();
39378
+ else if (seg !== "." && seg !== "") parts.push(seg);
39379
+ }
39380
+ return (p.startsWith("/") ? "/" : "") + parts.join("/");
39381
+ };
39382
+ var dirOf2 = (p) => {
39383
+ const q2 = p.replace(/\\/g, "/");
39384
+ return q2.includes("/") ? q2.replace(/\/[^/]*$/, "") || "/" : ".";
39385
+ };
39386
+ var Project = class {
39387
+ constructor(files) {
39388
+ this.files = /* @__PURE__ */ new Map();
39389
+ this.failures = [];
39390
+ for (const f of files) {
39391
+ if (!CODE_FILE.test(f.path) || /\.d\.[mc]?ts$/.test(f.path)) continue;
39392
+ const path = f.path.replace(/\\/g, "/");
39393
+ try {
39394
+ const ast = parseProgram(f.source);
39395
+ this.files.set(path, { path, ast, source: f.source, scope: null, exports: /* @__PURE__ */ new Map(), imports: /* @__PURE__ */ new Map(), bindings: /* @__PURE__ */ new Map() });
39396
+ } catch (e) {
39397
+ this.failures.push({ file: path, line: e.line ?? null, why: `Thunder could not read this file (${e.message}${e.line ? `, line ${e.line}` : ""})` });
39398
+ }
39399
+ }
39400
+ for (const m of this.files.values()) this.index(m);
39401
+ }
39402
+ index(m) {
39403
+ const scope = new Scope(null);
39404
+ scope.module = m;
39405
+ m.scope = scope;
39406
+ const bind2 = (name, b) => {
39407
+ m.bindings.set(name, b);
39408
+ };
39409
+ const visit = (s, exported, isDefault) => {
39410
+ if (!s) return;
39411
+ if (s.type === "Import") {
39412
+ for (const n of s.names) m.imports.set(n.local, { from: s.from, imported: n.imported });
39413
+ return;
39414
+ }
39415
+ if (s.type === "Export") {
39416
+ if (s.decl) {
39417
+ visit(s.decl, true, s.isDefault);
39418
+ return;
39419
+ }
39420
+ if (s.expr) {
39421
+ bind2("default", { kind: "expr", node: s.expr });
39422
+ m.exports.set("default", "default");
39423
+ return;
39424
+ }
39425
+ for (const n of s.names ?? []) {
39426
+ if (s.from) m.exports.set(n.exported, { reexport: s.from, name: n.local });
39427
+ else m.exports.set(n.exported, n.local);
39428
+ }
39429
+ return;
39430
+ }
39431
+ if (s.type === "Function") {
39432
+ const name = s.name ?? "default";
39433
+ bind2(name, { kind: "fn", node: s });
39434
+ if (exported) m.exports.set(isDefault ? "default" : name, name);
39435
+ return;
39436
+ }
39437
+ if (s.type === "Class") {
39438
+ const name = s.name ?? "default";
39439
+ bind2(name, { kind: "class", node: s });
39440
+ if (exported) m.exports.set(isDefault ? "default" : name, name);
39441
+ return;
39442
+ }
39443
+ if (s.type === "Var") {
39444
+ for (const d of s.decls) {
39445
+ if (d.id.type === "Id") {
39446
+ bind2(d.id.name, { kind: "var", node: d.init, line: d.line });
39447
+ if (exported) m.exports.set(d.id.name, d.id.name);
39448
+ } else for (const name of patternNames(d.id)) {
39449
+ bind2(name, { kind: "destructured", node: d.init, pattern: d.id, name });
39450
+ if (exported) m.exports.set(name, name);
39451
+ }
39452
+ }
39453
+ }
39454
+ };
39455
+ for (const s of m.ast.body) visit(s, false, false);
39456
+ }
39457
+ resolveModule(fromFile, spec) {
39458
+ if (!spec || !(spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("@/") || spec.startsWith("~/"))) return null;
39459
+ let base2;
39460
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
39461
+ const rest2 = spec.slice(2);
39462
+ for (const root of ["src/", "", "app/"]) {
39463
+ const hit = this.resolveModule("/x", `/${root}${rest2}`.replace(/^\//, "./"));
39464
+ if (hit) return hit;
39465
+ }
39466
+ for (const p of this.files.keys()) if (p.endsWith(`/${rest2}.ts`) || p.endsWith(`/${rest2}.tsx`) || p.endsWith(`/${rest2}/index.ts`)) return p;
39467
+ return null;
39468
+ }
39469
+ base2 = norm3(`${dirOf2(fromFile)}/${spec}`);
39470
+ const stem = base2.replace(/\.(js|mjs|cjs|jsx)$/, "");
39471
+ 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`]) {
39472
+ if (this.files.has(cand)) return cand;
39473
+ }
39474
+ return null;
39475
+ }
39476
+ };
39477
+ function patternNames(p) {
39478
+ if (!p) return [];
39479
+ if (p.type === "Id") return [p.name];
39480
+ if (p.type === "Default") return patternNames(p.target);
39481
+ if (p.type === "Rest") return patternNames(p.arg);
39482
+ if (p.type === "ObjPat") return p.props.flatMap((x) => x.rest ? patternNames(x.rest) : patternNames(x.value));
39483
+ if (p.type === "ArrPat") return p.elems.flatMap((x) => patternNames(x));
39484
+ return [];
39485
+ }
39486
+ function guardRec(st, rec2, ev) {
39487
+ if (!st.guards.has(rec2.id)) st.guards.set(rec2.id, ev);
39488
+ if (rec2.keyed?.value && !st.guards.has(`key:${rec2.keyed.value}`)) st.guards.set(`key:${rec2.keyed.value}`, ev);
39489
+ }
39490
+ var Analyzer = class {
39491
+ constructor(project) {
39492
+ this.p = project;
39493
+ this.work = 0;
39494
+ this.recCount = 0;
39495
+ this.moduleCache = /* @__PURE__ */ new Map();
39496
+ }
39497
+ // A module-level name, resolved through imports. Returns a value.
39498
+ moduleValue(file, name, line, seen = /* @__PURE__ */ new Set()) {
39499
+ const key = `${file}::${name}`;
39500
+ if (this.moduleCache.has(key)) return this.moduleCache.get(key);
39501
+ if (seen.has(key)) return {};
39502
+ seen.add(key);
39503
+ const m = this.p.files.get(file);
39504
+ let v;
39505
+ const b = m.bindings.get(name);
39506
+ if (b) v = this.bindingValue(m, name, b, seen);
39507
+ else if (m.imports.has(name)) {
39508
+ const imp = m.imports.get(name);
39509
+ const target = this.p.resolveModule(file, imp.from);
39510
+ if (target) {
39511
+ if (imp.imported === "*") v = { ns: target };
39512
+ else v = this.exportValue(target, imp.imported, seen) ?? { opaque: { why: `${name} is not exported by ${target}`, file, line } };
39513
+ } else {
39514
+ v = { opaque: { why: `${name} comes from ${imp.from}, outside these files`, file, line }, pkg: imp.from, pkgName: imp.imported === "default" ? name : imp.imported };
39515
+ if (/^@prisma\/client$|^drizzle-orm|^knex$|^pg$|^postgres$|^mysql2?|^@neondatabase|^kysely$/.test(imp.from) && DB_NAMES.test(name)) v.isDb = { label: name };
39516
+ }
39517
+ }
39518
+ this.moduleCache.set(key, v);
39519
+ return v;
39520
+ }
39521
+ exportValue(file, name, seen = /* @__PURE__ */ new Set()) {
39522
+ const m = this.p.files.get(file);
39523
+ if (!m) return null;
39524
+ const e = m.exports.get(name);
39525
+ if (e == null) {
39526
+ for (const [, x] of m.exports) if (x?.reexport && x.name === "*") {
39527
+ const t = this.p.resolveModule(file, x.reexport);
39528
+ const v = t && this.exportValue(t, name, seen);
39529
+ if (v) return v;
39530
+ }
39531
+ return null;
39532
+ }
39533
+ if (typeof e === "object" && e.reexport) {
39534
+ const t = this.p.resolveModule(file, e.reexport);
39535
+ return t ? this.exportValue(t, e.name, seen) : { opaque: { why: `${name} comes from ${e.reexport}, outside these files`, file } };
39536
+ }
39537
+ return this.moduleValue(file, e, null, seen);
39538
+ }
39539
+ bindingValue(m, name, b, seen) {
39540
+ if (b.kind === "fn") return { fn: { node: b.node, scope: m.scope, file: m.path, name } };
39541
+ if (b.kind === "class") return { cls: { node: b.node, scope: m.scope, file: m.path, name } };
39542
+ if (b.kind === "expr" || b.kind === "var" || b.kind === "destructured") {
39543
+ if (!b.node) return {};
39544
+ const st = newState(m.scope, { returns: [] });
39545
+ const v = this.expr(b.node, st, { file: m.path, depth: 0, route: null, module: true });
39546
+ if (b.kind === "destructured") {
39547
+ const sc = new Scope(null);
39548
+ this.bindPattern(b.pattern, v, sc, st, { file: m.path });
39549
+ return sc.get(b.name) ?? {};
39550
+ }
39551
+ const init = b.node.type === "Logic" ? b.node.right : b.node.type === "Await" ? b.node.arg : b.node;
39552
+ const initName = init.type === "Call" || init.type === "New" ? init.callee.type === "Id" ? init.callee.name : init.callee.prop : null;
39553
+ if (v.dbFactory || initName && DB_FACTORIES.test(initName)) return { isDb: { label: name } };
39554
+ if (b.kind === "var" && DB_NAMES.test(name) && !v.isDb && !hasData(v) && !v.fn && !v.obj && !v.instance) return { isDb: { label: name } };
39555
+ return v;
39556
+ }
39557
+ return {};
39558
+ }
39559
+ tick(ctx, line) {
39560
+ if (++this.work > MAX_WORK) throw Object.assign(new Error("limit"), { limit: true, file: ctx.file, line });
39561
+ }
39562
+ // ── Statements ──
39563
+ block(stmts, st, ctx) {
39564
+ for (const s of stmts) {
39565
+ if (st.exited) break;
39566
+ this.stmt(s, st, ctx);
39567
+ }
39568
+ }
39569
+ stmt(s, st, ctx) {
39570
+ if (!s) return;
39571
+ this.tick(ctx, s.line);
39572
+ switch (s.type) {
39573
+ case "Block": {
39574
+ st.scope = new Scope(st.scope);
39575
+ this.block(s.body, st, ctx);
39576
+ st.scope = st.scope.parent ?? st.scope;
39577
+ return;
39578
+ }
39579
+ case "Var":
39580
+ for (const d of s.decls) {
39581
+ const v = d.init ? this.expr(d.init, st, ctx) : {};
39582
+ this.bindPattern(d.id, v, st.scope, st, ctx, true);
39583
+ }
39584
+ return;
39585
+ case "Function":
39586
+ st.scope.declare(s.name, { fn: { node: s, scope: st.scope, file: ctx.file, name: s.name } });
39587
+ return;
39588
+ case "Class":
39589
+ st.scope.declare(s.name, { cls: { node: s, scope: st.scope, file: ctx.file, name: s.name } });
39590
+ return;
39591
+ case "Expr": {
39592
+ const v = this.expr(s.expr, st, ctx);
39593
+ if (v.exits) st.exited = "throw";
39594
+ return;
39595
+ }
39596
+ case "Return": {
39597
+ const v = s.arg ? this.expr(s.arg, st, ctx) : {};
39598
+ if (ctx.returnsSend && s.arg && !v.response && !v.isRes) this.sink("response", v, st, ctx, s.line, "gives it back as the response");
39599
+ st.frame.returns.push({ val: v, state: cloneState(st) });
39600
+ st.exited = "return";
39601
+ return;
39602
+ }
39603
+ case "Throw":
39604
+ if (s.arg) this.expr(s.arg, st, ctx);
39605
+ st.exited = "throw";
39606
+ return;
39607
+ case "If":
39608
+ return this.ifStmt(s, st, ctx);
39609
+ case "Try": {
39610
+ const before = cloneState(st);
39611
+ this.stmt(s.body, st, ctx);
39612
+ let after = st;
39613
+ if (s.handler) {
39614
+ const c = cloneState(before);
39615
+ if (s.param) this.bindPattern(s.param, {}, c.scope, c, ctx, true);
39616
+ this.stmt(s.handler, c, ctx);
39617
+ after = mergeStates(st, c);
39618
+ }
39619
+ Object.assign(st, after);
39620
+ if (s.finalizer) {
39621
+ const wasExited = st.exited;
39622
+ st.exited = null;
39623
+ this.stmt(s.finalizer, st, ctx);
39624
+ st.exited = st.exited ?? wasExited;
39625
+ }
39626
+ return;
39627
+ }
39628
+ case "Loop": {
39629
+ if (s.init) this.stmt(s.init, st, ctx);
39630
+ if (s.iter) {
39631
+ const it = this.expr(s.iter, st, ctx);
39632
+ if (s.init?.type === "Var") for (const d of s.init.decls) this.bindPattern(d.id, this.element(it), st.scope, st, ctx, true);
39633
+ }
39634
+ if (s.test) this.expr(s.test, st, ctx);
39635
+ const body2 = cloneState(st);
39636
+ this.stmt(s.body, body2, ctx);
39637
+ if (body2.exited) body2.exited = null;
39638
+ Object.assign(st, mergeStates(st, body2));
39639
+ return;
39640
+ }
39641
+ case "Switch": {
39642
+ this.expr(s.disc, st, ctx);
39643
+ let merged = null;
39644
+ let hasDefault = false;
39645
+ for (const c of s.cases) {
39646
+ if (!c.test) hasDefault = true;
39647
+ else this.expr(c.test, st, ctx);
39648
+ const cs = cloneState(st);
39649
+ this.block(c.body, cs, ctx);
39650
+ if (cs.exited === "return" || cs.exited === "throw") {
39651
+ merged = merged ?? null;
39652
+ if (!merged) merged = cs;
39653
+ else merged = mergeStates(merged, cs);
39654
+ continue;
39655
+ }
39656
+ cs.exited = null;
39657
+ merged = merged ? mergeStates(merged, cs) : cs;
39658
+ }
39659
+ if (!hasDefault) merged = merged ? mergeStates(merged, cloneState(st)) : st;
39660
+ Object.assign(st, merged ?? st);
39661
+ return;
39662
+ }
39663
+ case "Export":
39664
+ if (s.decl) this.stmt(s.decl, st, ctx);
39665
+ return;
39666
+ default:
39667
+ return;
39668
+ }
39669
+ }
39670
+ ifStmt(s, st, ctx) {
39671
+ const facts = this.testFacts(s.test, st, ctx);
39672
+ const cons = cloneState(st);
39673
+ const alt = cloneState(st);
39674
+ this.applyFacts(cons, facts.whenTrue);
39675
+ this.applyFacts(alt, facts.whenFalse);
39676
+ this.stmt(s.cons, cons, ctx);
39677
+ if (s.alt) this.stmt(s.alt, alt, ctx);
39678
+ Object.assign(st, mergeStates(cons, alt));
39679
+ if (cons.exited && alt.exited) st.exited = cons.exited === "return" || alt.exited === "return" ? "return" : "throw";
39680
+ }
39681
+ applyFacts(st, facts) {
39682
+ for (const f of facts) {
39683
+ if (f.kind === "guard") for (const r of f.recs) guardRec(st, r, f.ev);
39684
+ if (f.kind === "role" && !st.role) st.role = f.ev;
39685
+ if (f.kind === "unresolved") st.unresolved = uniq(st.unresolved, [f.ev]);
39686
+ }
39687
+ }
39688
+ /**
39689
+ * What a condition establishes: facts that hold when it is true, and when it is false. A comparison of a record's
39690
+ * owner field with the caller (invoice.tenantId !== user.tenantId) guards the record on the side where they match.
39691
+ */
39692
+ testFacts(t, st, ctx) {
39693
+ const none = { whenTrue: [], whenFalse: [] };
39694
+ if (!t) return none;
39695
+ if (t.paren) return this.testFacts({ ...t, paren: false }, st, ctx);
39696
+ if (t.type === "Unary" && t.op === "!") {
39697
+ const f = this.testFacts(t.arg, st, ctx);
39698
+ const v = this.expr(t.arg, cloneState(st), ctx);
39699
+ return { whenTrue: f.whenFalse, whenFalse: [...f.whenTrue, ...this.foundFacts(v, t.line)] };
39700
+ }
39701
+ if (t.type === "Logic" && t.op === "||") {
39702
+ const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
39703
+ return { whenTrue: [...a.whenTrue.filter((x) => x.kind === "unresolved"), ...b.whenTrue.filter((x) => x.kind === "unresolved")], whenFalse: [...a.whenFalse, ...b.whenFalse] };
39704
+ }
39705
+ if (t.type === "Logic" && t.op === "&&") {
39706
+ const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
39707
+ return { whenTrue: [...a.whenTrue, ...b.whenTrue], whenFalse: [...a.whenFalse.filter((x) => x.kind === "unresolved"), ...b.whenFalse.filter((x) => x.kind === "unresolved")] };
39708
+ }
39709
+ if (t.type === "Bin" && ["===", "==", "!==", "!="].includes(t.op)) {
39710
+ const scratch = cloneState(st);
39711
+ const l = this.expr(t.left, scratch, ctx), r = this.expr(t.right, scratch, ctx);
39712
+ const eq2 = t.op === "===" || t.op === "==";
39713
+ const g = this.ownerComparison(l, r, t.line, ctx) ?? this.ownerComparison(r, l, t.line, ctx);
39714
+ if (g) return eq2 ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] };
39715
+ const role = this.roleComparison(l, r, t.line, ctx) ?? this.roleComparison(r, l, t.line, ctx);
39716
+ if (role) return eq2 ? { whenTrue: [role], whenFalse: [] } : { whenTrue: [], whenFalse: [role] };
39717
+ const isNull = (v) => "lit" in v && (v.lit === null || v.lit === void 0);
39718
+ const recSide = isNull(r) ? l : isNull(l) ? r : null;
39719
+ if (recSide?.recs?.length) {
39720
+ const links = this.foundFacts(recSide, t.line);
39721
+ return eq2 ? { whenTrue: [], whenFalse: links } : { whenTrue: links, whenFalse: [] };
39722
+ }
39723
+ return none;
39724
+ }
39725
+ if (t.type === "Call") {
39726
+ const scratch = cloneState(st);
39727
+ const v = this.expr(t, scratch, ctx);
39728
+ if (v.predicate) return v.predicate;
39729
+ for (const u of scratch.unresolved) if (!st.unresolved.includes(u)) return { whenTrue: [{ kind: "unresolved", ev: u }], whenFalse: [{ kind: "unresolved", ev: u }] };
39730
+ return none;
39731
+ }
39732
+ if (t.type === "Member" || t.type === "Id") {
39733
+ const v = this.expr(t, cloneState(st), ctx);
39734
+ 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: [] };
39735
+ if (v.predicate) return v.predicate;
39736
+ const links = this.foundFacts(v, t.line);
39737
+ if (links.length) return { whenTrue: links, whenFalse: [] };
39738
+ }
39739
+ return none;
39740
+ }
39741
+ /**
39742
+ * When a record turns out to exist: a lookup limited to the caller vouches for the records it was keyed by (links),
39743
+ * and for its own request key (a later update by the same id is then the caller's record too).
39744
+ */
39745
+ foundFacts(v, line) {
39746
+ const out = [];
39747
+ for (const rec2 of v.recs ?? []) {
39748
+ if (!rec2.scoped) continue;
39749
+ const ev = { says: `stops unless ${rec2.model ?? "the record"} is found for the caller (${rec2.scoped.says})`, file: rec2.file, line };
39750
+ if (rec2.links?.length) out.push({ kind: "guard", recs: rec2.links, ev });
39751
+ if (rec2.keyed?.value) out.push({ kind: "guard", recs: [rec2], ev });
39752
+ }
39753
+ return out;
39754
+ }
39755
+ ownerComparison(recSide, idSide, line, ctx) {
39756
+ const fields = (recSide.recFields ?? []).filter((f) => OWNER_FIELD.test(f.field) || f.field === "id" && false);
39757
+ if (!fields.length || !idSide.ident?.length) return null;
39758
+ if (idSide.input?.length) return null;
39759
+ const id2 = idSide.ident[0];
39760
+ return { kind: "guard", recs: fields.map((f) => f.rec), ev: { says: `compares ${fields[0].says} with ${id2.says}`, file: ctx.file, line } };
39761
+ }
39762
+ roleComparison(a, b, line, ctx) {
39763
+ if (!a.ident?.some((e) => /^(role|roles|type|kind|permission|permissions|scope|isAdmin|accessLevel|level)$/i.test(e.field ?? ""))) return null;
39764
+ if (!("lit" in b) || typeof b.lit !== "string" || !/admin|staff|super|owner|support|internal|root/i.test(b.lit)) return null;
39765
+ return { kind: "role", ev: { says: `only when ${a.ident[0].says} is "${b.lit}"`, file: ctx.file, line } };
39766
+ }
39767
+ // ── Patterns ──
39768
+ bindPattern(p, v, scope, st, ctx, declare = false) {
39769
+ if (!p) return;
39770
+ const set = (name, val) => declare ? scope.declare(name, val) : scope.set(name, val);
39771
+ if (p.type === "Id") {
39772
+ set(p.name, v ?? {});
39773
+ return;
39774
+ }
39775
+ if (p.type === "Default") {
39776
+ const d = this.expr(p.value, st, ctx);
39777
+ this.bindPattern(p.target, join2(v, d), scope, st, ctx, declare);
39778
+ return;
39779
+ }
39780
+ if (p.type === "Rest") {
39781
+ this.bindPattern(p.arg, v, scope, st, ctx, declare);
39782
+ return;
39783
+ }
39784
+ if (p.type === "ObjPat") {
39785
+ for (const prop of p.props) {
39786
+ if (prop.rest) {
39787
+ this.bindPattern(prop.rest, v, scope, st, ctx, declare);
39788
+ continue;
39789
+ }
39790
+ const key = typeof prop.key === "string" ? prop.key : null;
39791
+ const mv = key ? this.member(v, key, st, ctx, p.line) : dataOf(v);
39792
+ this.bindPattern(prop.value, mv, scope, st, ctx, declare);
39793
+ }
39794
+ return;
39795
+ }
39796
+ if (p.type === "ArrPat") {
39797
+ p.elems.forEach((e, i) => {
39798
+ if (e) this.bindPattern(e, v?.arr?.[i] ?? this.element(v), scope, st, ctx, declare);
39799
+ });
39800
+ }
39801
+ }
39802
+ element(v) {
39803
+ if (!v) return {};
39804
+ const d = dataOf(v);
39805
+ if (v.arr) return join2(d, joinAll(v.arr));
39806
+ return d;
39807
+ }
39808
+ // ── Expressions ──
39809
+ expr(e, st, ctx) {
39810
+ if (!e) return {};
39811
+ this.tick(ctx, e.line);
39812
+ switch (e.type) {
39813
+ case "Lit":
39814
+ return { lit: e.value };
39815
+ case "Tpl": {
39816
+ const parts = e.parts.map((p) => p.expr ? this.expr(p.expr, st, ctx) : null);
39817
+ return { ...joinAll(parts.filter(Boolean).map(dataOf)), tpl: { parts: e.parts.map((p, i) => p.expr ? { val: parts[i] } : { text: p.text }) } };
39818
+ }
39819
+ case "Id":
39820
+ return this.lookup(e.name, st, ctx, e.line);
39821
+ case "This":
39822
+ return ctx.thisVal ?? {};
39823
+ case "Member": {
39824
+ const o = this.expr(e.object, st, ctx);
39825
+ if (e.computed && e.prop == null) {
39826
+ const k = this.expr(e.computed, st, ctx);
39827
+ if (typeof k.lit === "string" || typeof k.lit === "number") return this.member(o, String(k.lit), st, ctx, e.line);
39828
+ return join2(this.element(o), dataOf(k).input ? {} : {});
39829
+ }
39830
+ return this.member(o, e.prop, st, ctx, e.line);
39831
+ }
39832
+ case "Call":
39833
+ return this.call(e, st, ctx);
39834
+ case "New":
39835
+ return this.newExpr(e, st, ctx);
39836
+ case "Await":
39837
+ return e.arg ? this.expr(e.arg, st, ctx) : {};
39838
+ case "Arrow":
39839
+ return { fn: { node: e, scope: st.scope, file: ctx.file, name: e.name ?? null, thisVal: ctx.thisVal } };
39840
+ case "ClassExpr":
39841
+ return { cls: { node: e, scope: st.scope, file: ctx.file, name: e.name } };
39842
+ case "Obj": {
39843
+ const m = /* @__PURE__ */ new Map();
39844
+ let agg = {};
39845
+ for (const p of e.props) {
39846
+ if (p.spread) {
39847
+ const sv = this.expr(p.spread, st, ctx);
39848
+ if (sv.obj) for (const [k, v2] of sv.obj) m.set(k, v2);
39849
+ else m.set(`...${m.size}`, { ...sv, spreadUnknown: true });
39850
+ agg = join2(agg, dataOf(sv));
39851
+ continue;
39852
+ }
39853
+ if (p.computed && p.key == null) this.expr(p.computed, st, ctx);
39854
+ const v = this.expr(p.value, st, ctx);
39855
+ if (p.key != null) m.set(String(p.key), v);
39856
+ agg = join2(agg, dataOf(v));
39857
+ }
39858
+ return { ...agg, obj: m };
39859
+ }
39860
+ case "Arr": {
39861
+ const arr = e.elems.map((x) => x ? this.expr(x.type === "Spread" ? x.arg : x, st, ctx) : {});
39862
+ return { ...joinAll(arr.map(dataOf)), arr };
39863
+ }
39864
+ case "Spread":
39865
+ return this.expr(e.arg, st, ctx);
39866
+ case "Bin": {
39867
+ const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx);
39868
+ const out = join2(dataOf(l), dataOf(r));
39869
+ if (["===", "==", "!==", "!="].includes(e.op)) {
39870
+ const g = this.ownerComparison(l, r, e.line, ctx) ?? this.ownerComparison(r, l, e.line, ctx);
39871
+ if (g) {
39872
+ const eq2 = e.op === "===" || e.op === "==";
39873
+ return { predicate: eq2 ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] } };
39874
+ }
39875
+ }
39876
+ if (e.op === "+" && (l.tpl || r.tpl || typeof l.lit === "string" || typeof r.lit === "string")) out.concat = [l, r];
39877
+ return out;
39878
+ }
39879
+ case "Logic": {
39880
+ const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx);
39881
+ return join2(l, r);
39882
+ }
39883
+ case "Cond": {
39884
+ this.expr(e.test, st, ctx);
39885
+ return join2(this.expr(e.cons, st, ctx), this.expr(e.alt, st, ctx));
39886
+ }
39887
+ case "Unary": {
39888
+ const v = this.expr(e.arg, st, ctx);
39889
+ return e.op === "!" || e.op === "typeof" || e.op === "delete" || e.op === "void" ? {} : dataOf(v);
39890
+ }
39891
+ case "Assign":
39892
+ return this.assign(e, st, ctx);
39893
+ case "Seq": {
39894
+ let v = {};
39895
+ for (const x of e.list) v = this.expr(x, st, ctx);
39896
+ return v;
39897
+ }
39898
+ case "Tagged":
39899
+ return this.tagged(e, st, ctx);
39900
+ default:
39901
+ return {};
39902
+ }
39903
+ }
39904
+ lookup(name, st, ctx, line) {
39905
+ const v = st.scope.get(name);
39906
+ if (v !== void 0) return v;
39907
+ const m = this.p.files.get(ctx.file);
39908
+ if (m && (m.bindings.has(name) || m.imports.has(name))) return this.moduleValue(ctx.file, name, line);
39909
+ if (DB_NAMES.test(name)) return { isDb: { label: name } };
39910
+ return { global: name };
39911
+ }
39912
+ assign(e, st, ctx) {
39913
+ const v = this.expr(e.right, st, ctx);
39914
+ const val = e.op === "=" ? v : join2(this.expr(e.left, cloneState(st), ctx), v);
39915
+ if (e.left.type === "Id") st.scope.set(e.left.name, val);
39916
+ else if (e.left.type === "Member") {
39917
+ const o = this.expr(e.left.object, st, ctx);
39918
+ if ((o.isReq || o.isRes) && e.left.prop) st.req.set(e.left.prop, val);
39919
+ else if (o.obj && e.left.prop) o.obj.set(e.left.prop, val);
39920
+ else if (e.left.object.type === "Member" && e.left.object.prop === "locals") st.req.set(`locals.${e.left.prop}`, val);
39921
+ } else if (e.left.type === "ObjPat" || e.left.type === "Obj" || e.left.type === "Arr") {
39922
+ }
39923
+ return val;
39924
+ }
39925
+ member(o, prop, st, ctx, line) {
39926
+ if (!o) return {};
39927
+ if (prop == null) return dataOf(o);
39928
+ if (o.isReq) {
39929
+ if (st.req.has(prop)) return st.req.get(prop);
39930
+ 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 };
39931
+ 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);
39932
+ if (prop === "nextUrl") return { nextUrl: true, input: [{ says: `${o.isReq.name}.nextUrl`, file: ctx.file, line }] };
39933
+ if (prop === "json" || prop === "formData" || prop === "text") return { reqBodyFn: o.isReq.name };
39934
+ if (prop === "jwtVerify") return { identityFn: `${o.isReq.name}.jwtVerify()` };
39935
+ if (prop === "locals") return { locals: true, isReq: o.isReq };
39936
+ if (prop === "log" || prop === "server") return {};
39937
+ return {};
39938
+ }
39939
+ if (o.isRes) {
39940
+ if (prop === "locals") return { locals: true, isReq: { name: `${o.isRes.name}` } };
39941
+ return {};
39942
+ }
39943
+ if (o.locals) {
39944
+ if (st.req.has(`locals.${prop}`)) return st.req.get(`locals.${prop}`);
39945
+ if (/user|auth|session|account/i.test(prop)) return this.identity(`res.locals.${prop}`, ctx, line, st);
39946
+ return {};
39947
+ }
39948
+ if (o.nextUrl) {
39949
+ if (prop === "searchParams") return { input: o.input, searchParams: true };
39950
+ return { input: o.input };
39951
+ }
39952
+ if (o.isParams) return { input: [{ says: `params.${prop}`, file: ctx.file, line }] };
39953
+ if (o.ctx) {
39954
+ if (prop === "req") return { honoReq: true };
39955
+ if (prop === "var" || prop === "env") return { honoVar: prop };
39956
+ return { ctxMethod: prop, ctxVal: o };
39957
+ }
39958
+ if (o.honoReq) return { honoReqMethod: prop };
39959
+ if (o.honoVar) {
39960
+ if (o.honoVar === "env" && /DB|DATABASE/.test(prop)) return { isDb: { label: `c.env.${prop}` } };
39961
+ if (/user|auth|session|jwt|payload|account|tenant/i.test(prop)) return this.identity(`c.var.${prop}`, ctx, line, st);
39962
+ return {};
39963
+ }
39964
+ if (o.ns) return this.exportValue(o.ns, prop) ?? {};
39965
+ const out = {};
39966
+ if (o.input?.length) out.input = o.input.map((ev) => ({ ...ev, says: `${ev.says}.${prop}` }));
39967
+ if (o.ident?.length) out.ident = o.ident.map((ev) => ({ ...ev, says: `${ev.says}.${prop}`, field: prop }));
39968
+ if (o.recs?.length) {
39969
+ out.recs = o.recs;
39970
+ out.recFields = o.recs.map((rec2) => ({ rec: rec2, field: prop, says: `${rec2.var ?? rec2.model ?? "the record"}.${prop}` }));
39971
+ }
39972
+ if (o.unknown?.length) out.unknown = o.unknown;
39973
+ if (o.obj?.has(prop)) return join2(o.obj.get(prop), {});
39974
+ if (o.obj && !hasData(out)) {
39975
+ for (const [k, v] of o.obj) if (k.startsWith("...") && v.spreadUnknown) return dataOf(v);
39976
+ }
39977
+ if (o.clientFor) return { ...out, dbMember: { client: { label: o.clientFor.says, scoped: o.clientFor }, prop } };
39978
+ if (o.isDb) {
39979
+ if (prop === "query") return { dbQuery: o.isDb };
39980
+ return { dbMember: { client: o.isDb, prop } };
39981
+ }
39982
+ if (o.dbQuery) return { drizzleRel: { client: o.dbQuery, table: prop } };
39983
+ if (o.dbMember) return { dbModelOp: { client: o.dbMember.client, model: o.dbMember.prop, op: prop } };
39984
+ if (o.drizzleRel) return { drizzleRelOp: { ...o.drizzleRel, op: prop } };
39985
+ if (o.cls && o.static !== false) {
39986
+ const mm = this.classMember(o.cls, prop, true);
39987
+ if (mm) return mm;
39988
+ }
39989
+ if (o.instance) {
39990
+ if (o.instance.fields?.has(prop)) return o.instance.fields.get(prop);
39991
+ const mm = this.classMember(o.instance.cls, prop, false, o);
39992
+ if (mm) return mm;
39993
+ }
39994
+ if (o.opaque) return { opaque: { ...o.opaque, why: o.opaque.why }, opaqueName: `${o.opaqueName ?? o.pkgName ?? "it"}.${prop}`, pkg: o.pkg, ...out };
39995
+ if (o.global) return { global: `${o.global}.${prop}`, ...out };
39996
+ if (o.fn && prop === "call") return o;
39997
+ return out;
39998
+ }
39999
+ classMember(cls, prop, isStatic, inst) {
40000
+ for (const m of cls.node.members) {
40001
+ if (m.key !== prop || !!m.isStatic !== isStatic) continue;
40002
+ if (m.fn) return { fn: { node: m.fn, scope: cls.scope, file: cls.file, name: `${cls.name}.${prop}`, thisVal: inst ?? { cls } } };
40003
+ }
40004
+ return null;
40005
+ }
40006
+ identity(says, ctx, line, st) {
40007
+ const ev = { says, file: ctx.file, line };
40008
+ if (st && !st.identity) st.identity = ev;
40009
+ return { ident: [{ ...ev, src: ev, field: null }] };
40010
+ }
40011
+ newExpr(e, st, ctx) {
40012
+ const c = this.expr(e.callee, st, ctx);
40013
+ const args = e.args.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
40014
+ const name = e.callee.type === "Id" ? e.callee.name : e.callee.prop;
40015
+ if (name && DB_FACTORIES.test(name)) return { dbFactory: true };
40016
+ if (name === "Response" || name === "NextResponse") {
40017
+ this.sink("response", args[0] ?? {}, st, ctx, e.line, `answers with new ${name}(\u2026)`, this.statusOf(args[1]));
40018
+ return { response: true };
40019
+ }
40020
+ if (name === "URL") return joinAll(args.map(dataOf));
40021
+ if (/^(Map|Set|WeakMap|WeakSet|URLSearchParams|Headers|FormData|Array)$/.test(name ?? "")) return { ...joinAll(args.map(dataOf)), collection: true };
40022
+ if (c.cls) {
40023
+ const fields = /* @__PURE__ */ new Map();
40024
+ const inst = { instance: { cls: c.cls, fields } };
40025
+ const ctor = c.cls.node.members.find((m) => m.key === "constructor" && m.fn);
40026
+ if (ctor) {
40027
+ ctor.fn.params.forEach((p, i) => {
40028
+ const id2 = p.type === "Default" ? p.target : p;
40029
+ if (id2.type === "Id") fields.set(id2.name, args[i] ?? {});
40030
+ });
40031
+ try {
40032
+ 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);
40033
+ } catch (err) {
40034
+ if (err.limit) throw err;
40035
+ }
40036
+ }
40037
+ 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 }));
40038
+ for (const [k, v] of fields) if (DB_NAMES.test(k) && !v.isDb && !hasData(v)) fields.set(k, { isDb: { label: `this.${k}` } });
40039
+ return inst;
40040
+ }
40041
+ return joinAll(args.map(dataOf));
40042
+ }
40043
+ statusOf(v) {
40044
+ if (!v?.obj) return null;
40045
+ const s = v.obj.get("status");
40046
+ return typeof s?.lit === "number" ? s.lit : null;
40047
+ }
40048
+ // ── Calls ──
40049
+ call(e, st, ctx) {
40050
+ const callee2 = e.callee;
40051
+ const line = e.line;
40052
+ const argNodes = e.args;
40053
+ const evalArgs = () => argNodes.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
40054
+ if (callee2.type === "Member") {
40055
+ const prop = callee2.prop;
40056
+ const o = this.expr(callee2.object, st, ctx);
40057
+ if (o.isRes) {
40058
+ if (prop === "status" || prop === "code" || prop === "type" || prop === "set" || prop === "header" || prop === "setHeader" || prop === "cookie" || prop === "clearCookie" || prop === "append" || prop === "vary" || prop === "location") {
40059
+ const a = evalArgs();
40060
+ return { isRes: { ...o.isRes, status: prop === "status" || prop === "code" ? typeof a[0]?.lit === "number" ? a[0].lit : o.isRes.status : o.isRes.status } };
40061
+ }
40062
+ if (["json", "send", "end", "jsonp", "render", "sendFile", "write", "redirect", "sendStatus", "download"].includes(prop)) {
40063
+ const a = evalArgs();
40064
+ const status = prop === "sendStatus" ? a[0]?.lit : o.isRes.status;
40065
+ const body2 = prop === "render" ? a[1] ?? {} : prop === "redirect" || prop === "sendStatus" ? {} : a[0] ?? {};
40066
+ this.sink("response", body2, st, ctx, line, `answers with ${o.isRes.name}.${prop}(\u2026)`, status);
40067
+ return { response: true, exits: typeof status === "number" && status >= 400 };
40068
+ }
40069
+ return {};
40070
+ }
40071
+ if (o.ctx) {
40072
+ const a = evalArgs();
40073
+ if (["json", "text", "html", "body", "newResponse"].includes(prop)) {
40074
+ this.sink("response", a[0] ?? {}, st, ctx, line, `answers with c.${prop}(\u2026)`, typeof a[1]?.lit === "number" ? a[1].lit : null);
40075
+ return { response: true };
40076
+ }
40077
+ if (prop === "get") {
40078
+ const k = a[0]?.lit;
40079
+ if (typeof k === "string" && st.req.has(`c:${k}`)) return st.req.get(`c:${k}`);
40080
+ if (typeof k === "string" && /user|auth|session|jwt|payload|account|tenant|claims/i.test(k)) return this.identity(`c.get("${k}")`, ctx, line, st);
40081
+ if (typeof k === "string" && /^db$|database|prisma/i.test(k)) return { isDb: { label: `c.get("${k}")` } };
40082
+ return {};
40083
+ }
40084
+ if (prop === "set") {
40085
+ if (typeof a[0]?.lit === "string") st.req.set(`c:${a[0].lit}`, a[1] ?? {});
40086
+ return {};
40087
+ }
40088
+ if (prop === "notFound") return { response: true, exits: true };
40089
+ return {};
40090
+ }
40091
+ if (o.honoReq) {
40092
+ const a = evalArgs();
40093
+ 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 }] };
40094
+ return {};
40095
+ }
40096
+ if (o.reqBodyFn) {
40097
+ evalArgs();
40098
+ return { input: [{ says: `await ${o.reqBodyFn}.json()`, file: ctx.file, line }] };
40099
+ }
40100
+ if (o.identityFn) {
40101
+ evalArgs();
40102
+ return this.identity(o.identityFn, ctx, line, st);
40103
+ }
40104
+ if (o.searchParams) {
40105
+ const a = evalArgs();
40106
+ return { input: [{ says: `searchParams.${prop}(${typeof a[0]?.lit === "string" ? JSON.stringify(a[0].lit) : ""})`, file: ctx.file, line }] };
40107
+ }
40108
+ if ((o.global === "NextResponse" || o.global === "Response" || o.pkgName === "NextResponse") && prop === "json") {
40109
+ const a = evalArgs();
40110
+ const status = this.statusOf(a[1]);
40111
+ this.sink("response", a[0] ?? {}, st, ctx, line, `answers with ${o.global ?? o.pkgName}.json(\u2026)`, status);
40112
+ return { response: true, exits: typeof status === "number" && status >= 400 };
40113
+ }
40114
+ if ((o.global === "NextResponse" || o.pkgName === "NextResponse") && (prop === "redirect" || prop === "next" || prop === "rewrite")) {
40115
+ evalArgs();
40116
+ return { response: true };
40117
+ }
40118
+ if ((prop === "$transaction" || prop === "transaction") && o.isDb) {
40119
+ const a = evalArgs();
40120
+ if (a[0]?.fn) return this.callFunction(a[0].fn, [{ isDb: { label: "tx" } }], st, ctx, line);
40121
+ return joinAll(a.map(dataOf));
40122
+ }
40123
+ if (prop === "model" && (callee2.object.name === "mongoose" || o.pkg === "mongoose")) {
40124
+ const a = evalArgs();
40125
+ return { mongooseModel: { model: typeof a[0]?.lit === "string" ? a[0].lit : "a model" } };
40126
+ }
40127
+ if (o.isDb && prop === "query") return this.dbMethod({ client: o.isDb, prop }, argNodes, evalArgs, st, ctx, line);
40128
+ const fnVal = this.member(o, prop, st, ctx, line);
40129
+ if (fnVal.dbModelOp) return this.prismaOp(fnVal.dbModelOp, evalArgs(), st, ctx, line);
40130
+ if (fnVal.drizzleRelOp) return this.drizzleRel(fnVal.drizzleRelOp, evalArgs(), st, ctx, line);
40131
+ if (fnVal.dbMember) return this.dbMethod(fnVal.dbMember, argNodes, evalArgs, st, ctx, line);
40132
+ if (o.drizzle) return this.drizzleStep(o.drizzle, prop, evalArgs(), st, ctx, line, argNodes);
40133
+ if (o.knex) return this.knexStep(o.knex, prop, evalArgs(), st, ctx, line);
40134
+ if (o.mongooseModel && MONGOOSE_OPS.has(prop)) return this.mongooseOp(o.mongooseModel, prop, evalArgs(), st, ctx, line);
40135
+ if ((prop === "then" || prop === "catch" || prop === "finally") && argNodes.length) {
40136
+ const a = evalArgs();
40137
+ let out = dataOf(o);
40138
+ if (a[0]?.fn && prop === "then") out = join2(out, this.callFunction(a[0].fn, [dataOf(o)], st, ctx, line));
40139
+ return out;
40140
+ }
40141
+ const full = callee2.object.type === "Id" ? `${callee2.object.name}.${prop}` : null;
40142
+ if (full && PASS_THROUGH_MEMBERS.has(full)) {
40143
+ const a = evalArgs();
40144
+ return { ...joinAll(a.map(dataOf)), ...full === "Promise.all" && a[0]?.arr ? { arr: a[0].arr } : {} };
40145
+ }
40146
+ if (full === "jwt.verify" || full === "jose.jwtVerify") {
40147
+ evalArgs();
40148
+ return this.identity(`${full}()`, ctx, line, st);
40149
+ }
40150
+ if (fnVal.fn) return this.callFunction(fnVal.fn, evalArgs(), st, ctx, line, fnVal.fn.thisVal);
40151
+ if (/^(parse|safeParse|parseAsync|validate|validateSync|cast)$/.test(prop) && argNodes.length) {
40152
+ const a = evalArgs();
40153
+ return joinAll(a.map(dataOf));
40154
+ }
40155
+ if (o.collection) {
40156
+ const a = evalArgs();
40157
+ return join2(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf)));
40158
+ }
40159
+ if (hasData(o) && !o.opaque) {
40160
+ const a = evalArgs();
40161
+ if ((prop === "equals" || prop === "isEqual") && a[0]) {
40162
+ const g = this.ownerComparison(o, a[0], line, ctx) ?? this.ownerComparison(a[0], o, line, ctx);
40163
+ if (g) return { predicate: { whenTrue: [g], whenFalse: [] } };
40164
+ }
40165
+ if (prop === "includes" && a[0]) {
40166
+ const recSide = o.recFields?.length || o.recs?.length ? o : a[0].recFields?.length || a[0].recs?.length ? a[0] : null;
40167
+ const idSide = recSide === o ? a[0] : o;
40168
+ if (recSide && idSide?.ident?.length && !idSide.input?.length) {
40169
+ const recs = [.../* @__PURE__ */ new Set([...(recSide.recFields ?? []).map((f2) => f2.rec), ...recSide.recs ?? []])];
40170
+ 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: [] } };
40171
+ }
40172
+ }
40173
+ if (["some", "find", "every", "findIndex", "findLast"].includes(prop) && a[0]?.fn) {
40174
+ const v = this.callFunction(a[0].fn, [this.element(o)], cloneState(st), ctx, line);
40175
+ if (v.predicate?.whenTrue?.length) return { predicate: { whenTrue: v.predicate.whenTrue, whenFalse: [] } };
40176
+ }
40177
+ 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)) {
40178
+ return { predicate: { whenTrue: [{ kind: "role", ev: { says: `only when ${o.ident[0].says} includes "${a[0].lit}"`, file: ctx.file, line } }], whenFalse: [] } };
40179
+ }
40180
+ return join2(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf)));
40181
+ }
40182
+ 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);
40183
+ }
40184
+ const name = callee2.type === "Id" ? callee2.name : null;
40185
+ const f = this.expr(callee2, st, ctx);
40186
+ if (name && NEXT_EXITS.has(name) && (f.pkg === "next/navigation" || f.global)) {
40187
+ evalArgs();
40188
+ return { exits: true };
40189
+ }
40190
+ if (name === "next") {
40191
+ evalArgs();
40192
+ st.calledNext = true;
40193
+ return {};
40194
+ }
40195
+ if (name === "model" && f.pkg === "mongoose") {
40196
+ const a = evalArgs();
40197
+ return { mongooseModel: { model: typeof a[0]?.lit === "string" ? a[0].lit : "a model" } };
40198
+ }
40199
+ if (f.reqNext) {
40200
+ const a = evalArgs();
40201
+ if (!a.length || a[0].lit === void 0) st.calledNext = true;
40202
+ else return { exits: true };
40203
+ return {};
40204
+ }
40205
+ if (f.knexRoot || f.isDb && argNodes.length === 1 && argNodes[0].type === "Lit" && typeof argNodes[0].value === "string") {
40206
+ const a = evalArgs();
40207
+ return { knex: { client: f.isDb ?? { label: name }, table: a[0]?.lit ?? null, conds: [], line, write: null } };
40208
+ }
40209
+ 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);
40210
+ if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !f.fn) {
40211
+ evalArgs();
40212
+ return this.identity(`${name}()`, ctx, line, st);
40213
+ }
40214
+ if (name && ROLE_FN.test(name) && !f.fn) {
40215
+ const a = evalArgs();
40216
+ 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 };
40217
+ return {};
40218
+ }
40219
+ if (f.fn) {
40220
+ const a = evalArgs();
40221
+ const v = this.callFunction(f.fn, a, st, ctx, line);
40222
+ if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !v.ident?.length) return { ...v, ...this.identity(`${name}()`, ctx, line, st) };
40223
+ return v;
40224
+ }
40225
+ if (f.cls) {
40226
+ evalArgs();
40227
+ return {};
40228
+ }
40229
+ if (name && PASS_THROUGH.has(name)) return joinAll(evalArgs().map(dataOf));
40230
+ if (f.isDb) return this.rawSql(f.isDb, evalArgs(), st, ctx, line);
40231
+ 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);
40232
+ }
40233
+ /**
40234
+ * A call Thunder cannot follow. Its result is a value Thunder cannot see into when it was given request data. If it
40235
+ * also sees the record or the caller (or its name says it checks something), it might be an ownership check, so the
40236
+ * path becomes "cannot tell".
40237
+ */
40238
+ unresolvedCall(name, why, args, st, ctx, line, calleeVal) {
40239
+ const ev = { says: `${name}(\u2026)`, why, file: ctx.file, line };
40240
+ const fnArgs = args.filter((a) => a.fn);
40241
+ for (const a of fnArgs) {
40242
+ try {
40243
+ this.callFunction(a.fn, [], st, ctx, line);
40244
+ } catch (err) {
40245
+ if (err.limit) throw err;
40246
+ }
40247
+ }
40248
+ const data = args.filter((a) => !a.fn);
40249
+ const sawRecord = data.some((a) => a.recs?.length || a.recFields?.length);
40250
+ const sawCaller = data.some((a) => a.ident?.length);
40251
+ const sawInput = data.some((a) => a.input?.length || a.unknown?.length);
40252
+ const baseName = String(name).split(".").pop();
40253
+ if ((sawRecord || sawCaller) && (GUARDISH.test(baseName) || sawRecord && sawCaller)) st.unresolved = uniq(st.unresolved, [{ ...ev, says: `${name}(\u2026) might check who may see it` }]);
40254
+ const out = joinAll(data.map(dataOf));
40255
+ if (sawCaller && !GUARDISH.test(baseName)) out.clientFor = { says: `${name}(\u2026)`, file: ctx.file, line };
40256
+ const parts = String(name).split(".");
40257
+ const ownerName = parts.length > 1 ? parts[parts.length - 2] : "";
40258
+ 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));
40259
+ if ((sawInput || calleeVal?.recs?.length) && dataLike) out.unknown = uniq(out.unknown, [{ ...ev, says: `${name}(\u2026)` }]);
40260
+ if (calleeVal && hasData(calleeVal)) return join2(out, dataOf(calleeVal));
40261
+ return out;
40262
+ }
40263
+ callFunction(fn, args, st, ctx, line, thisVal) {
40264
+ if ((ctx.depth ?? 0) >= MAX_DEPTH) {
40265
+ const ev = { says: `${fn.name ?? "a function"}(\u2026)`, why: `Thunder stops following calls ${MAX_DEPTH} deep`, file: ctx.file, line };
40266
+ if (args.some((a) => a.recs?.length || a.ident?.length)) st.unresolved = uniq(st.unresolved, [ev]);
40267
+ const out = joinAll(args.map(dataOf));
40268
+ if (args.some((a) => a.input?.length)) out.unknown = uniq(out.unknown, [ev]);
40269
+ return out;
40270
+ }
40271
+ const node2 = fn.node;
40272
+ const frame = { returns: [] };
40273
+ const inner = cloneState(st);
40274
+ inner.scope = new Scope(fn.scope);
40275
+ inner.frame = frame;
40276
+ inner.exited = null;
40277
+ const c2 = { ...ctx, file: fn.file, depth: (ctx.depth ?? 0) + 1, thisVal: thisVal ?? fn.thisVal ?? ctx.thisVal, returnsSend: false };
40278
+ (node2.params ?? []).forEach((p, i) => {
40279
+ if (p.type === "Rest") this.bindPattern(p.arg, { arr: args.slice(i), ...joinAll(args.slice(i).map(dataOf)) }, inner.scope, inner, c2, true);
40280
+ else this.bindPattern(p, args[i] ?? {}, inner.scope, inner, c2, true);
40281
+ });
40282
+ if (node2.body?.type === "Block") this.block(node2.body.body, inner, c2);
40283
+ else if (node2.body) {
40284
+ const v2 = this.expr(node2.body, inner, c2);
40285
+ frame.returns.push({ val: v2, state: cloneState(inner) });
40286
+ inner.exited = "return";
40287
+ }
40288
+ const back = [...frame.returns.map((r) => r.state)];
40289
+ if (!inner.exited) back.push(inner);
40290
+ if (!back.length) {
40291
+ st.exited = "throw";
40292
+ return {};
40293
+ }
40294
+ const merged = back.reduce((a, b) => mergeStates(a, { ...b, exited: null }), { ...back[0], exited: null });
40295
+ st.guards = merged.guards;
40296
+ st.role = merged.role;
40297
+ st.identity = st.identity ?? merged.identity;
40298
+ st.unresolved = merged.unresolved;
40299
+ st.calledNext = st.calledNext || merged.calledNext;
40300
+ st.req = merged.req;
40301
+ const vals = frame.returns.map((r) => r.val);
40302
+ const v = joinAll(vals);
40303
+ if (frame.returns.length && node2.body) {
40304
+ const preds = [];
40305
+ for (const r of frame.returns) if (r.pred) preds.push(r.pred);
40306
+ }
40307
+ const pred = this.predicateOf(node2, args, c2, fn);
40308
+ if (pred) v.predicate = pred;
40309
+ return v;
40310
+ }
40311
+ // A function whose returned expression is a comparison: canRead(user, invoice) { return invoice.ownerId === user.id }.
40312
+ predicateOf(node2, args, ctx, fn) {
40313
+ const rets = [];
40314
+ const collect = (s) => {
40315
+ if (!s) return;
40316
+ if (s.type === "Return" && s.arg) rets.push(s.arg);
40317
+ else if (s.type === "Block") s.body.forEach(collect);
40318
+ else if (s.type === "If") {
40319
+ collect(s.cons);
40320
+ collect(s.alt);
40321
+ }
40322
+ };
40323
+ if (node2.body?.type === "Block") node2.body.body.forEach(collect);
40324
+ else if (node2.body) rets.push(node2.body);
40325
+ if (rets.length !== 1) return null;
40326
+ const st = newState(new Scope(fn.scope), { returns: [] });
40327
+ (node2.params ?? []).forEach((p, i) => this.bindPattern(p.type === "Rest" ? p.arg : p, args[i] ?? {}, st.scope, st, ctx, true));
40328
+ const f = this.testFacts(rets[0], st, ctx);
40329
+ return f.whenTrue.length || f.whenFalse.length ? f : null;
40330
+ }
40331
+ // ── Databases ──
40332
+ newRec(props) {
40333
+ this.recCount++;
40334
+ return { id: `r${this.recCount}`, ...props };
40335
+ }
40336
+ /** A where condition as conjuncts: { conj: [{ col, val }], or: [[…], …], nested: [...], unknown: why }. */
40337
+ whereFromObject(v) {
40338
+ const w = { conj: [], or: [], unknown: null };
40339
+ if (!v) return w;
40340
+ if (!v.obj) {
40341
+ if (hasData(v)) w.unknown = "the where condition is a value Thunder cannot see into";
40342
+ return w;
40343
+ }
40344
+ for (const [k, val] of v.obj) {
40345
+ if (k.startsWith("...")) {
40346
+ if (hasData(val) || val.opaque) w.unknown = "the where condition spreads a value Thunder cannot see into";
40347
+ continue;
40348
+ }
40349
+ if (k === "AND") {
40350
+ for (const x of val.arr ?? [val]) {
40351
+ const sub = this.whereFromObject(x);
40352
+ w.conj.push(...sub.conj);
40353
+ w.or.push(...sub.or);
40354
+ w.unknown = w.unknown ?? sub.unknown;
40355
+ }
40356
+ continue;
40357
+ }
40358
+ if (k === "OR") {
40359
+ w.or.push((val.arr ?? [val]).map((x) => this.whereFromObject(x)));
40360
+ continue;
40361
+ }
40362
+ if (k === "NOT") continue;
40363
+ if (val.obj) {
40364
+ const sub = this.whereFromObject(val);
40365
+ if (sub.conj.length || sub.or.length) w.conj.push({ col: k, nested: sub });
40366
+ else w.conj.push({ col: k, val });
40367
+ continue;
40368
+ }
40369
+ w.conj.push({ col: k, val });
40370
+ }
40371
+ return w;
40372
+ }
40373
+ /** How a where condition limits a lookup: by the request (keyed), by the caller (scoped), or by the caller's identity. */
40374
+ judgeWhere(w) {
40375
+ const out = { keyed: null, scoped: null, byIdentity: null, unknown: w.unknown };
40376
+ const visit = (wh, path) => {
40377
+ for (const c of wh.conj) {
40378
+ if (c.nested) {
40379
+ visit(c.nested, [...path, c.col]);
40380
+ continue;
40381
+ }
40382
+ const v = c.val;
40383
+ 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 };
40384
+ if (v?.unknown?.length && !out.keyed && !out.unknown) out.unknown = `${[...path, c.col].join(".")} comes from ${v.unknown[0].says}, which Thunder cannot follow`;
40385
+ if (v?.ident?.length && !v.input?.length) {
40386
+ const ev = v.ident[0];
40387
+ const col = c.col;
40388
+ const ownerish = OWNER_FIELD.test(col) || OWNER_FIELD.test(ev.field ?? "") || path.some((p) => OWNER_FIELD.test(p));
40389
+ if (col === "id" && !path.length && (ev.field === "id" || ev.field == null || /Id$/.test(ev.field ?? ""))) {
40390
+ if (!out.byIdentity) out.byIdentity = { says: `${col} = ${ev.says}` };
40391
+ } else if (ownerish && !out.scoped) out.scoped = { says: `${[...path, col].join(".")} = ${ev.says}` };
40392
+ }
40393
+ if (v?.recFields?.length && !v.input?.length) out.fromRecord = uniq(out.fromRecord, v.recFields.map((f) => f.rec));
40394
+ }
40395
+ for (const group of wh.or) {
40396
+ const judged = group.map((g) => this.judgeWhere(g));
40397
+ if (!out.keyed) out.keyed = judged.find((j) => j.keyed)?.keyed ?? null;
40398
+ if (!out.scoped && judged.length && judged.every((j) => j.scoped)) out.scoped = judged[0].scoped;
40399
+ 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`;
40400
+ if (!out.unknown) out.unknown = judged.find((j) => j.unknown)?.unknown ?? null;
40401
+ }
40402
+ };
40403
+ visit(w, []);
40404
+ return out;
40405
+ }
40406
+ makeLookup({ client, model, op, kind, where, st, ctx, line, varName }) {
40407
+ const j = this.judgeWhere(where);
40408
+ const rec2 = 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 });
40409
+ if (j.scoped && j.fromRecord?.length) rec2.links = j.fromRecord;
40410
+ if (j.scoped && /OrThrow$/.test(op)) {
40411
+ const ev = { says: `${model}.${op} stops unless it belongs to the caller`, file: ctx.file, line };
40412
+ for (const r of j.fromRecord ?? []) guardRec(st, r, ev);
40413
+ if (j.keyed?.value) st.guards.set(`key:${j.keyed.value}`, ev);
40414
+ }
40415
+ if (kind === "change") this.sink("change", { recs: [rec2] }, st, ctx, line, `${op === "delete" || /delete|del|remove/i.test(op) ? "deletes" : "changes"} ${model ?? "a record"}`);
40416
+ return { recs: [rec2] };
40417
+ }
40418
+ prismaOp({ client, model, op }, args, st, ctx, line) {
40419
+ if (!PRISMA_ALL.has(op)) return this.unresolvedCall(`${client.label}.${model}.${op}`, `${op} is not a database call Thunder knows`, args, st, ctx, line);
40420
+ if (op === "create" || op === "createMany") return { recs: [this.newRec({ model, op, kind: "create", file: ctx.file, line })] };
40421
+ const opts = args[0];
40422
+ const where = this.whereFromObject(opts?.obj?.get("where"));
40423
+ if (opts && !opts.obj && hasData(opts)) where.unknown = "the query options are a value Thunder cannot see into";
40424
+ if (!opts?.obj?.has("where") && opts?.obj) {
40425
+ }
40426
+ const kind = PRISMA_WRITE.has(op) ? "change" : "read";
40427
+ return this.makeLookup({ client, model, op, kind, where, st, ctx, line });
40428
+ }
40429
+ dbMethod({ client, prop }, argNodes, evalArgs, st, ctx, line) {
40430
+ 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")) {
40431
+ return this.rawSql(client, evalArgs(), st, ctx, line, prop.includes("execute") ? "change" : null);
40432
+ }
40433
+ const a = evalArgs();
40434
+ if (["select", "selectDistinct", "selectFrom"].includes(prop)) return { drizzle: { client, kind: "read", table: null, where: null, line } };
40435
+ 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 } };
40436
+ if (prop === "insert" || prop === "insertInto") return { drizzle: { client, kind: "create", table: this.tableName(a[0], argNodes[0]), line } };
40437
+ if (prop === "$connect" || prop === "$disconnect" || prop === "end" || prop === "release" || prop === "connect") return {};
40438
+ return this.unresolvedCall(`${client.label}.${prop}`, `${client.label}.${prop} is not a database call Thunder knows`, a, st, ctx, line);
40439
+ }
40440
+ tableName(v, node2) {
40441
+ if (!v) return null;
40442
+ if (typeof v.lit === "string") return v.lit;
40443
+ if (node2?.type === "Id") return node2.name;
40444
+ if (node2?.type === "Member") return node2.prop;
40445
+ return v.tableName ?? v.global ?? v.opaqueName ?? null;
40446
+ }
40447
+ // Drizzle conditions: eq(t.col, v), and(...), or(...), inArray(t.col, [...]).
40448
+ drizzleWhere(v) {
40449
+ const w = { conj: [], or: [], unknown: null };
40450
+ if (!v) return w;
40451
+ if (v.cond) {
40452
+ if (v.cond.op === "and") for (const x of v.cond.args) {
40453
+ const s = this.drizzleWhere(x);
40454
+ w.conj.push(...s.conj);
40455
+ w.or.push(...s.or);
40456
+ w.unknown = w.unknown ?? s.unknown;
40457
+ }
40458
+ else if (v.cond.op === "or") w.or.push(v.cond.args.map((x) => this.drizzleWhere(x)));
40459
+ else if (v.cond.op === "eq") w.conj.push({ col: v.cond.col, val: v.cond.val });
40460
+ else if (v.cond.op === "raw") {
40461
+ const s = v.cond.where;
40462
+ w.conj.push(...s.conj);
40463
+ w.or.push(...s.or);
40464
+ w.unknown = w.unknown ?? s.unknown;
40465
+ }
40466
+ return w;
40467
+ }
40468
+ if (v.obj) return this.whereFromObject(v);
40469
+ if (hasData(v)) w.unknown = "the where condition is a value Thunder cannot see into";
40470
+ return w;
40471
+ }
40472
+ drizzleStep(d, prop, args, st, ctx, line, argNodes = []) {
40473
+ if (prop === "from" || prop === "selectFrom") return { drizzle: { ...d, table: this.tableName(args[0], argNodes[0]) } };
40474
+ if (prop === "where") {
40475
+ const where = this.drizzleWhere(args[0]);
40476
+ const next = { ...d, where };
40477
+ 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 } };
40478
+ return { drizzle: next, ...this.drizzleRec(next, st, ctx, line) };
40479
+ }
40480
+ if (["set", "values", "returning", "onConflictDoNothing", "onConflictDoUpdate"].includes(prop)) return { drizzle: d };
40481
+ if (["limit", "offset", "orderBy", "groupBy", "innerJoin", "leftJoin", "rightJoin", "fullJoin", "having", "execute", "all", "get", "then", "prepare", "selectAll", "executeTakeFirst", "executeTakeFirstOrThrow"].includes(prop)) {
40482
+ if (prop === "selectAll" || prop === "executeTakeFirst" || prop === "executeTakeFirstOrThrow" || prop === "execute") return { drizzle: d, ...this.drizzleRec(d, st, ctx, line) };
40483
+ return { drizzle: d, ...d.where ? this.drizzleRec(d, st, ctx, line) : {} };
40484
+ }
40485
+ return { drizzle: d };
40486
+ }
40487
+ drizzleRec(d, st, ctx, line) {
40488
+ if (d.kind !== "read") return {};
40489
+ if (d._rec) return { recs: [d._rec] };
40490
+ 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 });
40491
+ d._rec = v.recs[0];
40492
+ return v;
40493
+ }
40494
+ drizzleRel({ client, table, op }, args, st, ctx, line) {
40495
+ if (!["findFirst", "findMany"].includes(op)) return {};
40496
+ const opts = args[0];
40497
+ let whereVal = opts?.obj?.get("where");
40498
+ if (whereVal?.fn) {
40499
+ const ops = { obj: new Map(["eq", "and", "or", "inArray", "ne"].map((k) => [k, { global: k }])) };
40500
+ whereVal = this.callFunction(whereVal.fn, [{ table: { name: table }, tableName: table }, ops], st, ctx, line);
40501
+ }
40502
+ const where = this.drizzleWhere(whereVal);
40503
+ return this.makeLookup({ client, model: table, op, kind: "read", where, st, ctx, line });
40504
+ }
40505
+ knexStep(k, prop, args, st, ctx, line) {
40506
+ const addConds = () => {
40507
+ if (args.length === 1 && args[0].obj) {
40508
+ const w = this.whereFromObject(args[0]);
40509
+ return [...k.conds, ...w.conj];
40510
+ }
40511
+ if (args.length >= 2 && typeof args[0].lit === "string") return [...k.conds, { col: args[0].lit.split(".").pop(), val: args[args.length - 1] }];
40512
+ if (args[0]?.fn) return [...k.conds, { col: "?", val: { unknown: [{ says: "a where callback", file: ctx.file, line }] } }];
40513
+ return [...k.conds, { col: "?", val: dataOf(args[0] ?? {}) }];
40514
+ };
40515
+ if (prop === "where" || prop === "andWhere") return { knex: { ...k, conds: addConds() } };
40516
+ if (prop === "orWhere") return { knex: { ...k, hasOr: true } };
40517
+ if (["first", "select", "pluck", "then", "limit", "orderBy", "returning", "count", "join", "leftJoin", "innerJoin", "offset"].includes(prop)) {
40518
+ const where = { conj: k.conds, or: [], unknown: k.hasOr ? "the query has an OR Thunder does not judge" : null };
40519
+ if (k._rec) return { knex: k, recs: [k._rec] };
40520
+ const v = this.makeLookup({ client: k.client, model: k.table, op: prop, kind: "read", where, st, ctx, line });
40521
+ k._rec = v.recs[0];
40522
+ return { knex: k, ...v };
40523
+ }
40524
+ if (["update", "del", "delete", "increment", "decrement"].includes(prop)) {
40525
+ const where = { conj: k.conds, or: [], unknown: k.hasOr ? "the query has an OR Thunder does not judge" : null };
40526
+ return this.makeLookup({ client: k.client, model: k.table, op: prop, kind: "change", where, st, ctx, line });
40527
+ }
40528
+ if (prop === "insert") return {};
40529
+ return { knex: k };
40530
+ }
40531
+ mongooseOp({ model }, op, args, st, ctx, line) {
40532
+ const kind = MONGOOSE_OPS.get(op) === "write" ? "change" : "read";
40533
+ let where;
40534
+ if (/ById/.test(op)) where = { conj: [{ col: "_id", val: args[0] ?? {} }], or: [], unknown: null };
40535
+ else where = this.whereFromObject(args[0]);
40536
+ return this.makeLookup({ client: { label: model }, model, op, kind, where, st, ctx, line });
40537
+ }
40538
+ // Raw SQL from a string, a template, or sql`…`. Conditions after WHERE are read as col = value.
40539
+ rawSql(client, args, st, ctx, line, forceKind = null) {
40540
+ const q2 = args[0] ?? {};
40541
+ let text2 = null;
40542
+ const holes = [];
40543
+ if (typeof q2.lit === "string") text2 = q2.lit;
40544
+ else if (q2.tpl) text2 = q2.tpl.parts.map((p) => p.text != null ? p.text : (holes.push(p.val), `\0${holes.length - 1}\0`)).join("");
40545
+ else if (q2.sqlText != null) {
40546
+ text2 = q2.sqlText;
40547
+ holes.push(...q2.sqlHoles);
40548
+ }
40549
+ const params = args[1]?.arr ?? args.slice(1);
40550
+ if (text2 == null) {
40551
+ const v = joinAll(args.map(dataOf));
40552
+ if (!hasData(v)) return {};
40553
+ const rec2 = 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" });
40554
+ return { recs: [rec2] };
40555
+ }
40556
+ const kindWord = (text2.match(/^\s*(\w+)/)?.[1] ?? "").toUpperCase();
40557
+ const kind = forceKind ?? (kindWord === "UPDATE" || kindWord === "DELETE" ? "change" : kindWord === "INSERT" ? "create" : "read");
40558
+ if (kind === "create") return {};
40559
+ const table = text2.match(/\b(?:from|update|into)\s+["`[]?(\w+)/i)?.[1] ?? null;
40560
+ const whereText = text2.split(/\bwhere\b/i)[1]?.split(/\b(order\s+by|group\s+by|limit|returning|offset)\b/i)[0] ?? "";
40561
+ const where = { conj: [], or: [], unknown: null };
40562
+ if (/\bor\b/i.test(whereText)) where.unknown = "the WHERE has an OR Thunder does not judge";
40563
+ let qIndex = 0;
40564
+ const re = /([\w."`[\]]+)\s*=\s*(\$(\d+)|\?|:(\w+)|@(\w+)|\u0000(\d+)\u0000)/g;
40565
+ for (const m of whereText.matchAll(re)) {
40566
+ const col = m[1].replace(/["`[\]]/g, "").split(".").pop();
40567
+ let val = {};
40568
+ if (m[3]) val = params[Number(m[3]) - 1] ?? {};
40569
+ else if (m[2] === "?") val = params[qIndex++] ?? {};
40570
+ else if (m[6] != null) val = holes[Number(m[6])] ?? {};
40571
+ else if (m[4] || m[5]) {
40572
+ const o = params[0];
40573
+ val = o?.obj?.get(m[4] ?? m[5]) ?? {};
40574
+ }
40575
+ where.conj.push({ col, val });
40576
+ }
40577
+ return this.makeLookup({ client, model: table, op: "sql", kind, where, st, ctx, line });
40578
+ }
40579
+ tagged(e, st, ctx) {
40580
+ const tag = this.expr(e.tag, st, ctx);
40581
+ const parts = e.tpl.parts.map((p) => p.expr ? this.expr(p.expr, st, ctx) : null);
40582
+ const tplVal = { tpl: { parts: e.tpl.parts.map((p, i) => p.expr ? { val: parts[i] } : { text: p.text }) } };
40583
+ const name = e.tag.type === "Id" ? e.tag.name : e.tag.prop;
40584
+ if (tag.isDb || name === "sql" || /^\$(queryRaw|executeRaw)$/.test(name ?? "") || e.tag.type === "Member" && this.expr(e.tag.object, cloneState(st), ctx).isDb) {
40585
+ const text2 = e.tpl.parts.map((p, i) => p.expr ? `\0${i}\0` : p.text).join("");
40586
+ 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);
40587
+ const holes = parts.map((p) => p ?? {});
40588
+ const conj = [];
40589
+ const re = /([\w."`]+)?\s*\u0000(\d+)\u0000\s*=\s*\u0000(\d+)\u0000|([\w."`]+)\s*=\s*\u0000(\d+)\u0000/g;
40590
+ for (const m of text2.matchAll(re)) {
40591
+ if (m[2] != null) {
40592
+ const hole = e.tpl.parts[Number(m[2])]?.expr;
40593
+ const r = holes[Number(m[3])];
40594
+ conj.push({ col: hole?.type === "Member" ? hole.prop : "?", val: r });
40595
+ } else conj.push({ col: m[4].replace(/["`]/g, "").split(".").pop(), val: holes[Number(m[5])] });
40596
+ }
40597
+ return { cond: { op: "raw", where: { conj, or: [], unknown: /\bor\b/i.test(text2) ? "the condition has an OR Thunder does not judge" : null } } };
40598
+ }
40599
+ return joinAll(parts.filter(Boolean).map(dataOf));
40600
+ }
40601
+ // ── Sinks ──
40602
+ sink(kind, val, st, ctx, line, says, status) {
40603
+ if (!ctx.route) return;
40604
+ if (typeof status === "number" && status >= 400 && kind === "response") return;
40605
+ ctx.route.sinks.push({ kind, val, state: cloneState(st), file: ctx.file, line, says });
40606
+ }
40607
+ };
40608
+ var DRIZZLE_OPS = /* @__PURE__ */ new Set(["eq", "and", "or", "inArray"]);
40609
+ var baseCall = Analyzer.prototype.call;
40610
+ Analyzer.prototype.call = function call(e, st, ctx) {
40611
+ if (e.callee.type === "Id" && DRIZZLE_OPS.has(e.callee.name)) {
40612
+ const f = this.lookup(e.callee.name, st, ctx, e.line);
40613
+ if (f.global || f.pkg?.startsWith("drizzle-orm") || f.opaque) {
40614
+ const args = e.args.map((a) => this.expr(a.type === "Spread" ? a.arg : a, st, ctx));
40615
+ if (e.callee.name === "eq") return { cond: { op: "eq", col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
40616
+ if (e.callee.name === "inArray") return { cond: { op: "eq", col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
40617
+ return { cond: { op: e.callee.name, args }, ...joinAll(args.map(dataOf)) };
40618
+ }
40619
+ }
40620
+ return baseCall.call(this, e, st, ctx);
40621
+ };
40622
+ function columnOf(node2, val) {
40623
+ if (node2?.type === "Member" && node2.prop) return node2.prop;
40624
+ return val?.column ?? "?";
40625
+ }
40626
+ function walkAll(node2, visit) {
40627
+ if (!node2 || typeof node2 !== "object") return;
40628
+ if (Array.isArray(node2)) {
40629
+ for (const x of node2) walkAll(x, visit);
40630
+ return;
40631
+ }
40632
+ if (node2.type) visit(node2);
40633
+ for (const [k, v] of Object.entries(node2)) if (k !== "line" && v && typeof v === "object") walkAll(v, visit);
40634
+ }
40635
+ function nextRoutePath(file) {
40636
+ const m = file.match(/(?:^|\/)app\/(.*)\/route\.(?:ts|js|mts|tsx)$/);
40637
+ if (!m) return null;
40638
+ return "/" + m[1].split("/").filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@")).map((s) => s.replace(/^\[\.\.\.(.+)\]$/, "*$1").replace(/^\[(.+)\]$/, ":$1")).join("/");
40639
+ }
40640
+ function pagesApiPath(file) {
40641
+ const m = file.match(/(?:^|\/)pages\/(api\/.*)\.(?:ts|js)$/);
40642
+ if (!m) return null;
40643
+ return "/" + m[1].replace(/\/index$/, "").split("/").map((s) => s.replace(/^\[(.+)\]$/, ":$1")).join("/");
40644
+ }
40645
+ function findRoutes(project) {
40646
+ const routes = [];
40647
+ for (const m of project.files.values()) {
40648
+ const uses = [];
40649
+ walkAll(m.ast.body, (n) => {
40650
+ if (n.type !== "Call" || n.callee.type !== "Member") return;
40651
+ const prop = n.callee.prop;
40652
+ const recv = n.callee.object;
40653
+ const recvName = recv.type === "Id" ? recv.name : recv.type === "Member" ? recv.prop : null;
40654
+ if (prop === "use") {
40655
+ uses.push({ recv: recvName, line: n.line, args: n.args });
40656
+ return;
40657
+ }
40658
+ if (prop === "route" && n.args[0]?.type === "Obj") {
40659
+ const o = new Map(n.args[0].props.map((p) => [p.key, p.value]));
40660
+ const method = o.get("method"), url = o.get("url") ?? o.get("path"), handler2 = o.get("handler");
40661
+ 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 });
40662
+ return;
40663
+ }
40664
+ if (!METHODS.has(prop) || !n.args.length) return;
40665
+ const first = n.args[0];
40666
+ const path = first.type === "Lit" && typeof first.value === "string" ? first.value : first.type === "Tpl" && first.parts.length === 1 ? first.parts[0].text : null;
40667
+ if (path == null || !(path.startsWith("/") || path === "" || path === "*")) return;
40668
+ if (n.args.length < 2) return;
40669
+ const handler = n.args[n.args.length - 1];
40670
+ const middle = n.args.slice(1, -1);
40671
+ const opts = middle.find((x) => x.type === "Obj");
40672
+ const mw = middle.filter((x) => x.type !== "Obj").flatMap((x) => x.type === "Arr" ? x.elems.filter(Boolean) : [x]);
40673
+ if (opts) {
40674
+ 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]);
40675
+ }
40676
+ 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";
40677
+ routes.push({ framework, method: prop === "del" ? "DELETE" : prop.toUpperCase(), path, file: m.path, line: n.line, handler, middleware: mw, recv: recvName });
40678
+ });
40679
+ 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)));
40680
+ const nextPath = nextRoutePath(m.path);
40681
+ if (nextPath) {
40682
+ for (const [exported, local] of m.exports) {
40683
+ if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(exported) || typeof local !== "string") continue;
40684
+ const b = m.bindings.get(local);
40685
+ if (!b) continue;
40686
+ const handler = b.kind === "fn" ? b.node : b.node;
40687
+ routes.push({ framework: "next", method: exported, path: nextPath, file: m.path, line: handler?.line ?? 1, handler, middleware: [], uses: [] });
40688
+ }
40689
+ }
40690
+ const apiPath = pagesApiPath(m.path);
40691
+ if (apiPath && m.exports.has("default")) {
40692
+ const local = m.exports.get("default");
40693
+ const b = typeof local === "string" ? m.bindings.get(local) : null;
40694
+ 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: [] });
40695
+ }
40696
+ }
40697
+ return routes;
40698
+ }
40699
+ function analyzeRoute(an, project, r) {
40700
+ const m = project.files.get(r.file);
40701
+ const route = { sinks: [] };
40702
+ const ctx = { file: r.file, depth: 0, route, returnsSend: false };
40703
+ const st = newState(new Scope(m.scope), { returns: [] });
40704
+ const notes = [];
40705
+ const reqName = (fn) => {
40706
+ const p = fn?.params?.[0];
40707
+ return p?.type === "Id" ? p.name : "req";
40708
+ };
40709
+ 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);
40710
+ let handlerFn = handlerVal.fn ?? null;
40711
+ let wrapperName = null;
40712
+ if (!handlerFn && r.handler.type === "Call") {
40713
+ const inner = r.handler.args.find((a) => a.type === "Arrow") ?? null;
40714
+ const calleeName = r.handler.callee.type === "Id" ? r.handler.callee.name : r.handler.callee.prop;
40715
+ wrapperName = calleeName;
40716
+ if (inner) handlerFn = { node: inner, scope: st.scope, file: r.file, name: "the handler" };
40717
+ else if (r.handler.args[0]) {
40718
+ const v = an.expr(r.handler.args[0], st, ctx);
40719
+ handlerFn = v.fn ?? null;
40720
+ }
40721
+ }
40722
+ 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 };
40723
+ const node2 = handlerFn.node;
40724
+ const fw = r.framework;
40725
+ const args = [];
40726
+ if (fw === "hono") args.push({ ctx: true });
40727
+ else if (fw === "next") {
40728
+ args.push({ isReq: { name: reqName(node2) } });
40729
+ args.push({ obj: /* @__PURE__ */ new Map([["params", { isParams: true }]]), isParamsCtx: true });
40730
+ } else {
40731
+ args.push({ isReq: { name: reqName(node2) } });
40732
+ const resP = node2.params?.[1];
40733
+ args.push({ isRes: { name: resP?.type === "Id" ? resP.name : "res", status: null } });
40734
+ args.push({ reqNext: true });
40735
+ }
40736
+ if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName) && !MAYBE_GUARD_MIDDLEWARE.test(wrapperName)) {
40737
+ const usual = fw === "hono" ? 1 : fw === "next" ? 2 : 3;
40738
+ for (let i = usual; i < (node2.params?.length ?? 0); i++) args[i] = { ident: [{ says: `the caller from ${wrapperName}`, file: r.file, line: r.line, field: null }] };
40739
+ if (fw === "next") for (let i = 1; i < usual; i++) args[i] = args[i] ?? {};
40740
+ }
40741
+ const mwNodes = [...(r.uses ?? []).flatMap((u) => u.args.filter((a) => !(a.type === "Lit"))), ...r.middleware ?? []];
40742
+ if (wrapperName && (MAYBE_GUARD_MIDDLEWARE.test(wrapperName) || !AUTH_MIDDLEWARE.test(wrapperName)) && !/^(async|asyncHandler|catchAsync|wrap|handler|tryCatch|withErrorHandling|errorHandler|withErrors|safe)$/i.test(wrapperName)) {
40743
+ const wv = an.lookup(wrapperName, st, ctx, r.line);
40744
+ 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 });
40745
+ } else if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName)) st.identity = { says: `${wrapperName}(\u2026)`, file: r.file, line: r.line };
40746
+ let s = st;
40747
+ for (const mwNode of mwNodes) {
40748
+ 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";
40749
+ const base2 = label.split(".").pop();
40750
+ if (BENIGN_MIDDLEWARE.test(label) || BENIGN_MIDDLEWARE.test(base2)) continue;
40751
+ const roleish = ROLE_FN.test(base2) || /admin|role|permission|scope/i.test(label);
40752
+ const v = mwNode.type === "Arrow" ? { fn: { node: mwNode, scope: st.scope, file: r.file, name: "a middleware" } } : an.expr(mwNode, s, ctx);
40753
+ if (v.fn && (v.fn.node.params?.length ?? 0) >= 2) {
40754
+ const mctx = { ...ctx, depth: 1 };
40755
+ const ms = cloneState(s);
40756
+ ms.calledNext = false;
40757
+ try {
40758
+ an.callFunction(v.fn, args, ms, mctx, mwNode.line);
40759
+ if (ms.calledNext) {
40760
+ ms.calledNext = false;
40761
+ s = ms;
40762
+ } else s.unresolved.push({ says: `${label}`, why: `the middleware ${label} never visibly calls next()`, file: r.file, line: mwNode.line });
40763
+ } catch (err) {
40764
+ if (err.limit) throw err;
40765
+ s.unresolved.push({ says: `${label}`, why: `Thunder could not follow the middleware ${label}`, file: r.file, line: mwNode.line });
40766
+ }
40767
+ if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
40768
+ if (roleish && !s.role) s.role = { says: label, file: r.file, line: mwNode.line };
40769
+ continue;
40770
+ }
40771
+ if (roleish) {
40772
+ if (!s.role) s.role = { says: label, file: r.file, line: mwNode.line };
40773
+ if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
40774
+ continue;
40775
+ }
40776
+ if (MAYBE_GUARD_MIDDLEWARE.test(label)) {
40777
+ 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 });
40778
+ continue;
40779
+ }
40780
+ if (AUTH_MIDDLEWARE.test(label)) {
40781
+ if (!s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
40782
+ continue;
40783
+ }
40784
+ s.unresolved.push({ says: label, why: `the route runs ${label} first, and Thunder cannot see what it checks`, file: r.file, line: mwNode.line });
40785
+ }
40786
+ ctx.returnsSend = fw === "fastify" || fw === "hono" && false;
40787
+ const hctx = { ...ctx, depth: 0, returnsSend: ctx.returnsSend };
40788
+ const frame = { returns: [] };
40789
+ const hs = cloneState(s);
40790
+ hs.scope = new Scope(handlerFn.scope);
40791
+ hs.frame = frame;
40792
+ (node2.params ?? []).forEach((p, i) => an.bindPattern(p, args[i] ?? {}, hs.scope, hs, hctx, true));
40793
+ if (node2.body?.type === "Block") an.block(node2.body.body, hs, hctx);
40794
+ else if (node2.body) {
40795
+ const v = an.expr(node2.body, hs, hctx);
40796
+ if (hctx.returnsSend) an.sink("response", v, hs, hctx, node2.line, "gives it back as the response");
40797
+ }
40798
+ return { route, notes };
40799
+ }
40800
+ function judgePath(sink, rec2) {
40801
+ const st = sink.state;
40802
+ const steps = [];
40803
+ const at2 = (x) => ({ file: x.file ?? sink.file, line: x.line ?? null });
40804
+ if (rec2.keyed) steps.push({ kind: "input", says: `takes ${rec2.keyed.says.replace(/^.* = /, "")} from the request`, ...at2(rec2.keyed) });
40805
+ 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 });
40806
+ steps.push({ kind: rec2.kind === "change" ? "change" : "lookup", says: `${rec2.kind === "change" ? "changes" : "reads"} ${rec2.model ?? "a record"} with ${rec2.op}${rec2.keyed ? ` where ${rec2.keyed.says}` : ""}${rec2.scoped ? ` and ${rec2.scoped.says}` : ""}`, file: rec2.file, line: rec2.line });
40807
+ const respond = { kind: sink.kind === "change" ? "change" : "response", says: sink.says, file: sink.file, line: sink.line };
40808
+ const result = (verdict2, why, guard) => {
40809
+ if (guard) steps.push({ kind: "guard", says: guard.says, file: guard.file ?? rec2.file, line: guard.line ?? rec2.line });
40810
+ if (sink.kind !== "change") steps.push(respond);
40811
+ return { verdict: verdict2, why, steps, record: rec2.model ?? null, lines: [...new Set(steps.map((x) => x.line).filter(Boolean))].sort((x, y) => x - y) };
40812
+ };
40813
+ if (!rec2.keyed && rec2.byIdentity) return result("guarded", `the record is chosen by the caller (${rec2.byIdentity.says}), not by the request`);
40814
+ if (rec2.scoped) return result("guarded", `the lookup is limited to the caller: ${rec2.scoped.says}`, { says: `limits it to the caller: ${rec2.scoped.says}`, file: rec2.file, line: rec2.line });
40815
+ const g = st.guards.get(rec2.id) ?? (rec2.keyed?.value ? st.guards.get(`key:${rec2.keyed.value}`) : null);
40816
+ if (g) return result("guarded", `${g.says} before ${sink.kind === "change" ? "changing it" : "answering"}`, g);
40817
+ if (!rec2.keyed && !rec2.unknownWhere) return null;
40818
+ if (rec2.clientScoped) return result("cannot tell", `it uses a database client made for the caller (${rec2.clientScoped.says}); Thunder cannot see whether it filters by tenant`);
40819
+ if (rec2.unknownWhere) return result("cannot tell", rec2.unknownWhere);
40820
+ if (st.unresolved.length) {
40821
+ const u = st.unresolved[0];
40822
+ return result("cannot tell", `${u.why} (${u.file}, line ${u.line})${st.unresolved.length > 1 ? `, and ${st.unresolved.length - 1} more` : ""}`);
40823
+ }
40824
+ 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`);
40825
+ return result("unguarded", `no step between the request and the ${sink.kind === "change" ? "change" : "response"} limits ${rec2.model ?? "the record"} to the caller`);
40826
+ }
40827
+ function judgeUnknown(sink, u) {
40828
+ const st = sink.state;
40829
+ const steps = [
40830
+ { kind: "stopped", says: `${u.says} could not be followed: ${u.why}`, file: u.file, line: u.line },
40831
+ { kind: "response", says: sink.says, file: sink.file, line: sink.line }
40832
+ ];
40833
+ if (st.identity) steps.unshift({ kind: "identity", says: `knows the caller from ${st.identity.says}`, file: st.identity.file, line: st.identity.line });
40834
+ return { verdict: "cannot tell", why: `it answers with what ${u.says} gives back, and ${u.why}`, steps, record: null, lines: [u.line, sink.line] };
40835
+ }
40836
+ var RANK = { unguarded: 3, "cannot tell": 2, guarded: 1 };
40837
+ function accessFlow(files, { maxRoutes = 2e3 } = {}) {
40838
+ const project = new Project(files);
40839
+ const routes = findRoutes(project).slice(0, maxRoutes);
40840
+ const out = [];
40841
+ for (const r of routes) {
40842
+ const an = new Analyzer(project);
40843
+ let res;
40844
+ try {
40845
+ res = analyzeRoute(an, project, r);
40846
+ } catch (err) {
40847
+ if (!err.limit) throw err;
40848
+ 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: [] });
40849
+ continue;
40850
+ }
40851
+ if (res.stopped) {
40852
+ 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: [] });
40853
+ continue;
40854
+ }
40855
+ const paths = [];
40856
+ const seen = /* @__PURE__ */ new Set();
40857
+ for (const sink of res.route.sinks) {
40858
+ for (const rec2 of sink.val.recs ?? []) {
40859
+ if (rec2.kind === "create") continue;
40860
+ const key = `${rec2.id}@${sink.line}`;
40861
+ if (seen.has(key)) continue;
40862
+ seen.add(key);
40863
+ const p = judgePath(sink, rec2);
40864
+ if (p) paths.push(p);
40865
+ }
40866
+ if (!(sink.val.recs ?? []).some((rc) => rc.keyed || rc.unknownWhere)) {
40867
+ for (const u of sink.val.unknown ?? []) {
40868
+ const key = `${u.file}:${u.line}@${sink.line}`;
40869
+ if (seen.has(key)) continue;
40870
+ seen.add(key);
40871
+ paths.push(judgeUnknown(sink, u));
40872
+ }
40873
+ }
40874
+ }
40875
+ paths.sort((a, b) => RANK[b.verdict] - RANK[a.verdict]);
40876
+ const worst = paths[0]?.verdict ?? null;
40877
+ const identity = res.route.sinks.map((x) => x.state.identity).find(Boolean) ?? null;
40878
+ out.push({
40879
+ method: r.method,
40880
+ path: r.path,
40881
+ framework: r.framework,
40882
+ file: r.file,
40883
+ line: r.line,
40884
+ verdict: worst,
40885
+ why: worst ? paths[0].why : "it reads or changes no stored record chosen by the request",
40886
+ identity: identity ? { says: identity.says, file: identity.file, line: identity.line } : null,
40887
+ paths
40888
+ });
40889
+ }
40890
+ const count2 = (v) => out.filter((x) => x.verdict === v).length;
40891
+ return {
40892
+ schema: ACCESS_SCHEMA,
40893
+ routes: out,
40894
+ summary: { routes: out.length, guarded: count2("guarded"), unguarded: count2("unguarded"), cannotTell: count2("cannot tell"), noLookup: count2(null) },
40895
+ unread: project.failures
40896
+ };
40897
+ }
40898
+ function ownershipWords(route) {
40899
+ if (!route || !route.verdict) return null;
40900
+ if (route.verdict === "guarded") {
40901
+ const g = route.paths.flatMap((p) => p.steps).find((s) => s.kind === "guard");
40902
+ return `Ownership: checked${g?.line ? ` (line ${g.line})` : ""}: ${route.paths[0].why}`;
40903
+ }
40904
+ if (route.verdict === "unguarded") return `No ownership check on this path (lines ${route.paths[0].lines.join(", ")}): ${route.paths[0].why}`;
40905
+ return `Ownership: Thunder cannot tell: ${route.paths[0].why}`;
40906
+ }
40907
+
37918
40908
  // src/model.mjs
37919
40909
  var MODEL_SCHEMA = "thunder-model-v1";
37920
40910
  var THING_LANGUAGES = ["python", "typescript", "javascript", "java", "csharp", "kotlin", "php", "go", "rust", "ruby", "sql", "c", "cpp", "swift", "r", "powershell"];
@@ -37933,6 +40923,7 @@ function startValue(expr, params = {}) {
37933
40923
  if (/^(True|true)$/.test(e)) return "yes at first";
37934
40924
  if (/^(False|false)$/.test(e)) return "no at first";
37935
40925
  if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
40926
+ if (/^-?\d+(\.\d+)?(?:[mMfFdDlL]|[uU][lL]?|[lL][uU])$/.test(e)) return `${e.replace(/[a-zA-Z]+$/, "")} at first`;
37936
40927
  if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes3(e)}" at first`;
37937
40928
  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*)$/);
37938
40929
  if (en) return `${words11(en[1])} at first`;
@@ -38476,7 +41467,7 @@ function youGiveOf(item4) {
38476
41467
  }
38477
41468
  return given;
38478
41469
  }
38479
- var dirOf2 = (p) => String(p).includes("/") ? String(p).slice(0, String(p).lastIndexOf("/")) : "";
41470
+ var dirOf3 = (p) => String(p).includes("/") ? String(p).slice(0, String(p).lastIndexOf("/")) : "";
38480
41471
  function resolveAcrossFiles(pending, things, links, linkKeys) {
38481
41472
  const add = (p, to) => {
38482
41473
  const key = `${p.from}>${to}>${p.l.kind}>${p.l.line}`;
@@ -38486,13 +41477,13 @@ function resolveAcrossFiles(pending, things, links, linkKeys) {
38486
41477
  }
38487
41478
  };
38488
41479
  const resources = things.filter((t) => t.kind === "resource" && t.address);
38489
- const byDirAddr = new Map(resources.map((t) => [`${dirOf2(t.file)}|${t.address}`, t.id]));
41480
+ const byDirAddr = new Map(resources.map((t) => [`${dirOf3(t.file)}|${t.address}`, t.id]));
38490
41481
  const byAddr = /* @__PURE__ */ new Map();
38491
41482
  for (const t of resources) byAddr.set(t.address, [...byAddr.get(t.address) ?? [], t]);
38492
41483
  const oneDir = (hits, dir) => {
38493
- const here = hits.filter((t) => dirOf2(t.file) === dir);
41484
+ const here = hits.filter((t) => dirOf3(t.file) === dir);
38494
41485
  if (here.length) return here;
38495
- return new Set(hits.map((t) => dirOf2(t.file))).size === 1 ? hits : [];
41486
+ return new Set(hits.map((t) => dirOf3(t.file))).size === 1 ? hits : [];
38496
41487
  };
38497
41488
  for (const p of pending) {
38498
41489
  const to = p.l.to;
@@ -38640,14 +41631,14 @@ function thunderModel(files, { name = "app" } = {}) {
38640
41631
  if (from && to && !linkKeys.has(key)) {
38641
41632
  linkKeys.add(key);
38642
41633
  links.push({ from, to, kind: l.kind, file: l.file, line: l.line });
38643
- } else if (from && !to && (language === "terraform" || language === "kubernetes" || language === "docker-compose")) pending.push({ dir: dirOf2(f.path), from, l, language });
41634
+ } else if (from && !to && (language === "terraform" || language === "kubernetes" || language === "docker-compose")) pending.push({ dir: dirOf3(f.path), from, l, language });
38644
41635
  }
38645
41636
  }
38646
41637
  }
38647
41638
  if (pending.length) resolveAcrossFiles(pending, things, links, linkKeys);
38648
41639
  const dockerImages = things.filter((t) => t.resourceType === "docker-image");
38649
41640
  for (const t of things) for (const im of t.images ?? []) {
38650
- const hits = dockerImages.filter((d) => dirOf2(d.address.slice("image:".length)).split("/").pop() === im.name);
41641
+ const hits = dockerImages.filter((d) => dirOf3(d.address.slice("image:".length)).split("/").pop() === im.name);
38651
41642
  const key = hits.length === 1 && `${t.id}>${hits[0].id}>uses>${im.line}`;
38652
41643
  if (key && !linkKeys.has(key)) {
38653
41644
  linkKeys.add(key);
@@ -38714,6 +41705,20 @@ function thunderModel(files, { name = "app" } = {}) {
38714
41705
  } catch (e) {
38715
41706
  unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` });
38716
41707
  }
41708
+ const routeMembers = members.filter((m) => m.route && /^(typescript|javascript)$/i.test(m.language ?? ""));
41709
+ if (routeMembers.length) {
41710
+ try {
41711
+ const access = accessFlow(files.filter((f) => /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(f.path)));
41712
+ for (const r of access.routes) {
41713
+ if (!r.verdict) continue;
41714
+ 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);
41715
+ if (m) m.ownership = { verdict: r.verdict, says: ownershipWords(r), why: r.why, paths: r.paths };
41716
+ }
41717
+ model.access = { schema: access.schema, summary: access.summary };
41718
+ } catch (e) {
41719
+ unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Ownership on routes could not be checked: ${e.message}` });
41720
+ }
41721
+ }
38717
41722
  return model;
38718
41723
  }
38719
41724
  function flowLines(flow, depth = 1, note = null, full = false) {
@@ -38788,6 +41793,7 @@ function modelText(model, id2, { note = null, full = false } = {}) {
38788
41793
  const lines = [`${m.label}${owner && m.kind !== "setup" ? ` (${owner.label})` : ""}${m.kind === "rule" ? ": a rule" : ""}`];
38789
41794
  if (m.when) lines.push(` ${m.when}`);
38790
41795
  else if (m.route) lines.push(` When someone calls ${m.route}`);
41796
+ if (m.ownership) lines.push(` ${m.ownership.says}`);
38791
41797
  if (m.doc) lines.push(` Author's note: ${m.doc}`);
38792
41798
  if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(", ")}`);
38793
41799
  if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
@@ -39029,7 +42035,11 @@ function readLevel(model, level, focus, { full = false } = {}) {
39029
42035
  return {
39030
42036
  ...base2,
39031
42037
  ...about,
39032
- ...thing?.doc ?? model.files[0]?.purpose ? { purpose: thing?.doc ?? model.files[0]?.purpose } : {},
42038
+ // (A file's own description describes that file: the whole app takes one only when it is one file.)
42039
+ ...(() => {
42040
+ const p = thing ? thing.doc ?? model.files.find((f) => f.path === thing.file)?.purpose : model.files.length === 1 ? model.files[0]?.purpose : null;
42041
+ return p ? { purpose: p } : {};
42042
+ })(),
39033
42043
  things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === "thing" && !t.screen)).map(thingCard),
39034
42044
  resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === "resource")).map(resourceCard),
39035
42045
  ...thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] },
@@ -39063,6 +42073,7 @@ function readLevel(model, level, focus, { full = false } = {}) {
39063
42073
  usedBy,
39064
42074
  tryable: !!member.rule,
39065
42075
  ...member.rule ? { rule: member.rule } : {},
42076
+ ...member.ownership ? { ownership: member.ownership } : {},
39066
42077
  source: "Read from code by the Thunder compiler, with no AI."
39067
42078
  };
39068
42079
  }
@@ -39126,9 +42137,9 @@ function linkRepos(read) {
39126
42137
  for (const q2 of repo.requests) {
39127
42138
  if (q2.base === "this app" && repo.routes.some((r) => methodOk(r.method, q2.method) && pathMatch(r.segs, q2.segs) >= 0)) continue;
39128
42139
  const from = end(repo, q2);
39129
- const call = `${q2.method} ${q2.path}`;
42140
+ const call2 = `${q2.method} ${q2.path}`;
39130
42141
  if (GENERIC_PATHS.has(q2.path) || !distinctive(q2.segs)) {
39131
- notLinked.push({ kind: "http", call, from, why: GENERIC_PATHS.has(q2.path) ? `every service has ${q2.path}, so matching it to one repository would be a guess` : `${q2.path} has no fixed part to match on` });
42142
+ notLinked.push({ kind: "http", call: call2, from, why: GENERIC_PATHS.has(q2.path) ? `every service has ${q2.path}, so matching it to one repository would be a guess` : `${q2.path} has no fixed part to match on` });
39132
42143
  continue;
39133
42144
  }
39134
42145
  const matches3 = [];
@@ -39145,8 +42156,8 @@ function linkRepos(read) {
39145
42156
  const { other, r } = top[0];
39146
42157
  links.push({ kind: "http", method: q2.method, path: q2.path, route: `${r.method} ${r.path}`, base: q2.base, from, to: end(other, r) });
39147
42158
  } else if (top.length > 1) {
39148
- notLinked.push({ kind: "http", call, from, why: `${top.length} routes match equally (${top.map((x) => `${x.other.name}: ${x.r.method} ${x.r.path}`).join("; ")}), so none is chosen` });
39149
- } else notLinked.push({ kind: "http", call, from, why: q2.base === "this app" ? `no route Thunder read, in this repository or the others traced, handles ${call}` : `no route Thunder read in the traced repositories handles ${call}` });
42159
+ notLinked.push({ kind: "http", call: call2, from, why: `${top.length} routes match equally (${top.map((x) => `${x.other.name}: ${x.r.method} ${x.r.path}`).join("; ")}), so none is chosen` });
42160
+ } else notLinked.push({ kind: "http", call: call2, from, why: q2.base === "this app" ? `no route Thunder read, in this repository or the others traced, handles ${call2}` : `no route Thunder read in the traced repositories handles ${call2}` });
39150
42161
  }
39151
42162
  for (const p of repo.publishes) {
39152
42163
  const from = end(repo, p);
@@ -40429,9 +43440,9 @@ function buildGuard(ast, { denyResults, mask: mask2 = "[redacted]" } = {}) {
40429
43440
  const isDenied = (result) => denySet ? denySet.has(String(result)) : DENY_RE.test(String(result ?? "").replace(/[^A-Za-z]/g, ""));
40430
43441
  const isSecretKey2 = (k) => secretFields.has(k) || SENSITIVE_NAME.test(k);
40431
43442
  const decisions = new Map((ast.decisions || []).map((d) => [d.name, d]));
40432
- const MAX_DEPTH = 100;
43443
+ const MAX_DEPTH2 = 100;
40433
43444
  function redact(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
40434
- if (depth > MAX_DEPTH) return value;
43445
+ if (depth > MAX_DEPTH2) return value;
40435
43446
  if (Array.isArray(value)) return value.map((v) => redact(v, seen, depth + 1));
40436
43447
  if (value && typeof value === "object") {
40437
43448
  if (seen.has(value)) return value;
@@ -40529,11 +43540,11 @@ function renderMarker(meta, language = "typescript", { token = OPEN_TOKEN } = {}
40529
43540
  const close = `${c} </${token}>`;
40530
43541
  return { open, close };
40531
43542
  }
40532
- var norm3 = (s) => String(s ?? "").trim().replace(/\s+/g, " ").toLowerCase();
40533
- var sortedNorm = (arr) => (arr || []).map(norm3).filter(Boolean).sort();
43543
+ var norm4 = (s) => String(s ?? "").trim().replace(/\s+/g, " ").toLowerCase();
43544
+ var sortedNorm = (arr) => (arr || []).map(norm4).filter(Boolean).sort();
40534
43545
  function contractHash(ast) {
40535
43546
  const canonical = {
40536
- mission: norm3(ast.mission),
43547
+ mission: norm4(ast.mission),
40537
43548
  inputs: sortedNorm((ast.inputs || []).map((i) => `${i.name}:${i.type}`)),
40538
43549
  outputs: sortedNorm((ast.outputs || []).map((o) => `${o.name}:${o.type}`)),
40539
43550
  requires: sortedNorm(ast.requires),
@@ -40543,8 +43554,8 @@ function contractHash(ast) {
40543
43554
  errors: sortedNorm((ast.errors || []).map((e) => e.name)),
40544
43555
  verify: sortedNorm(ast.verify),
40545
43556
  architecture: sortedNorm(ast.architecture),
40546
- risk: norm3(ast.implementation?.risk),
40547
- approval: norm3(ast.implementation?.approval)
43557
+ risk: norm4(ast.implementation?.risk),
43558
+ approval: norm4(ast.implementation?.approval)
40548
43559
  };
40549
43560
  return sha256(JSON.stringify(canonical));
40550
43561
  }
@@ -40960,7 +43971,7 @@ function thunderizeFiles(files, { name = "app" } = {}) {
40960
43971
  var SAME_SCHEMA = "thunder-same-v1";
40961
43972
  var MAX_CASES = 4096;
40962
43973
  var nameKey = (name) => String(name).replace(/[_\s-]/g, "").toLowerCase();
40963
- var norm4 = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
43974
+ var norm5 = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
40964
43975
  var stemKey = (path) => nameKey(String(path).replace(/\.[^./]+$/, "").replace(/\\/g, "/"));
40965
43976
  function compact(it, key, file, language) {
40966
43977
  const base2 = { key, file, language, name: it.name, kind: it.kind, line: it.line, route: it.route, element: visualFor(it).element };
@@ -41057,7 +44068,7 @@ function stepSignature(code3) {
41057
44068
  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(" ");
41058
44069
  }
41059
44070
  var flatSteps = (steps, depth = 0) => (steps || []).flatMap((s) => [
41060
- { sig: `${depth}:${s.restates ? "code" : s.kind}:${s.restates || s.kind === "other" ? "" : norm4(s.says)}`, code: stepSignature(s.code), raw: String(s.code ?? ""), text: s.restates || s.kind === "other" ? `\`${s.code ?? s.says}\`` : s.says },
44071
+ { sig: `${depth}:${s.restates ? "code" : s.kind}:${s.restates || s.kind === "other" ? "" : norm5(s.says)}`, code: stepSignature(s.code), raw: String(s.code ?? ""), text: s.restates || s.kind === "other" ? `\`${s.code ?? s.says}\`` : s.says },
41061
44072
  ...flatSteps(s.children, depth + 1)
41062
44073
  ]);
41063
44074
  function compareItems(o, n) {
@@ -41569,13 +44580,13 @@ function valueChanges(o, n) {
41569
44580
  if (onlyA.length === 1 && onlyB.length === 1) return ` (${onlyA[0]} became ${onlyB[0]})`;
41570
44581
  return ` (values ${onlyA.length ? `${onlyA.slice(0, 4).join(", ")} removed` : ""}${onlyA.length && onlyB.length ? ", " : ""}${onlyB.length ? `${onlyB.slice(0, 4).join(", ")} added` : ""})`;
41571
44582
  }
41572
- function compareMember(o, n, items) {
44583
+ function compareMember(o, n, items, { extracted = false } = {}) {
41573
44584
  const subject = subjectOf(n);
41574
44585
  const sameCode = sameTokens(o.tokens, n.tokens);
41575
44586
  const sameThunder = o.sig === n.sig;
41576
44587
  const renamedOrMoved = [];
41577
44588
  if (o.m.file !== n.m.file) renamedOrMoved.push(`moved from ${o.m.file} to ${n.m.file}`);
41578
- if (nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? "") === (n.m.route ?? "")) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
44589
+ if (!extracted && nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? "") === (n.m.route ?? "")) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
41579
44590
  const moveKind = o.m.file !== n.m.file && nameKey(o.m.name) === nameKey(n.m.name) ? "moved" : "renamed";
41580
44591
  const formOnly = (why) => items.push(item3(
41581
44592
  renamedOrMoved.length ? moveKind : "form",
@@ -41720,6 +44731,22 @@ function enclosingName(lines, line) {
41720
44731
  }
41721
44732
  return null;
41722
44733
  }
44734
+ function mostlyIn(a, b) {
44735
+ const words14 = (ts) => ts.map((t) => t.t).filter((t) => /\w/.test(t));
44736
+ const have = /* @__PURE__ */ new Map();
44737
+ for (const t of words14(b)) have.set(t, (have.get(t) || 0) + 1);
44738
+ const want = words14(a);
44739
+ if (want.length < 12) return false;
44740
+ let hit = 0;
44741
+ for (const t of want) {
44742
+ const c = have.get(t) || 0;
44743
+ if (c) {
44744
+ hit++;
44745
+ have.set(t, c - 1);
44746
+ }
44747
+ }
44748
+ return hit / want.length >= 0.75;
44749
+ }
41723
44750
  function thunderReview(oldFiles, newFiles) {
41724
44751
  detailsCache = /* @__PURE__ */ new WeakMap();
41725
44752
  const A = side(oldFiles || []), B = side(newFiles || []);
@@ -41769,8 +44796,26 @@ function thunderReview(oldFiles, newFiles) {
41769
44796
  o.paired = true;
41770
44797
  }
41771
44798
  }
44799
+ const movedInto = /* @__PURE__ */ new Map();
44800
+ for (const [o, n] of pairs2) {
44801
+ const named2 = new Set(n.tokens.map((t) => t.t));
44802
+ const target = leftB().find((b) => b.m.file === n.m.file && b.m.kind !== "not-read" && named2.has(b.m.name) && b.m.name !== n.m.name && mostlyIn(o.tokens, b.tokens));
44803
+ if (target) {
44804
+ used.add(target);
44805
+ movedInto.set(o, target);
44806
+ }
44807
+ }
41772
44808
  let unchanged = 0;
41773
- for (const [o, n] of pairs2) if (compareMember(o, n, items) === "unchanged") unchanged++;
44809
+ for (const [o, n] of pairs2) {
44810
+ const into = movedInto.get(o);
44811
+ if (!into) {
44812
+ if (compareMember(o, n, items) === "unchanged") unchanged++;
44813
+ continue;
44814
+ }
44815
+ const now = n.text.slice(1).map((l) => l.trim()).filter(Boolean);
44816
+ items.push(item3("moved-into", "meaning", subjectOf(n), whereOf2(n), `Its steps moved to ${subjectOf(into)}, a new function it now runs; what changed in them is listed under ${subjectOf(into)}.`, { before: null, after: now }));
44817
+ compareMember(o, into, items, { extracted: true });
44818
+ }
41774
44819
  for (const o of leftA()) items.push(item3("removed", "meaning", subjectOf(o), whereOf2(o), `Removed ${KIND_WORD[o.m.kind] ?? "function"}: ${subjectOf(o)}.`, { before: o.text, after: null }));
41775
44820
  for (const n of leftB()) items.push(item3(
41776
44821
  "added",
@@ -43292,11 +46337,11 @@ function opSetCondition(ctx, edit) {
43292
46337
  did.push("turned the question around");
43293
46338
  }
43294
46339
  if (edit.addClause != null) {
43295
- const join4 = edit.addClause.join || "and";
43296
- if (join4 !== "and" && join4 !== "or") refuse('A new part joins with "and" or "or".');
46340
+ const join6 = edit.addClause.join || "and";
46341
+ if (join6 !== "and" && join6 !== "or") refuse('A new part joins with "and" or "or".');
43297
46342
  const part = exprFrom(edit.addClause.when, ctx.language, "condition");
43298
- test = test.kind === "logic" && test.op === join4 ? { ...test, operands: [...test.operands, part] } : { kind: "logic", op: join4, operands: [test, part] };
43299
- did.push(`added "${join4} ${sayFull(part)}"`);
46343
+ test = test.kind === "logic" && test.op === join6 ? { ...test, operands: [...test.operands, part] } : { kind: "logic", op: join6, operands: [test, part] };
46344
+ did.push(`added "${join6} ${sayFull(part)}"`);
43300
46345
  }
43301
46346
  if (edit.removeClause != null) {
43302
46347
  if (test.kind !== "logic") refuse("This question has one part; remove the question instead (removeStep).");
@@ -44212,6 +47257,440 @@ function planOnly(original, list3) {
44212
47257
  }
44213
47258
  return plans;
44214
47259
  }
47260
+
47261
+ // src/passport-fs.mjs
47262
+ var import_node_child_process4 = require("node:child_process");
47263
+ var import_node_fs4 = require("node:fs");
47264
+ var import_node_path5 = require("node:path");
47265
+
47266
+ // src/passport.mjs
47267
+ var PASSPORT_SCHEMA = "thunder-passport-v1";
47268
+ var ALWAYS_NOT_VERIFIED = [
47269
+ "Deployment: how it is configured and run in a real environment.",
47270
+ "External services: real providers, their answers, and their outages (tests use what the code was given).",
47271
+ "More than one process or machine: anything kept in memory is not shared between copies.",
47272
+ "Load and timing: behavior under many requests at once, beyond what the tests ran."
47273
+ ];
47274
+ var MAX_BEHAVIOR = 60;
47275
+ var fileHash = (source) => sha256(String(source));
47276
+ var EFFECT = { find: "reads", save: "writes", send: "sends", ask: "calls another part", redirect: "sends the person to" };
47277
+ function effectKind(node2) {
47278
+ if (node2.does === "save" && /^(Deletes|Removes)\b/.test(node2.text || "")) return "deletes";
47279
+ return EFFECT[node2.does] ?? null;
47280
+ }
47281
+ function assemblePassport({ parts, change = null, runs = [], purpose = null, extra = [], builtAt = (/* @__PURE__ */ new Date()).toISOString(), thunder = null }) {
47282
+ const hashes = /* @__PURE__ */ new Map();
47283
+ for (const p of parts) for (const f of p.files) hashes.set(`${p.name}/${f.path}`, { part: p.name, file: f.path, sha256: fileHash(f.source) });
47284
+ const inputOf = (part, file) => hashes.get(`${part}/${file}`) ?? { part, file, sha256: null };
47285
+ const partInputs = (name) => [...hashes.values()].filter((h) => h.part === name);
47286
+ const models = new Map(parts.map((p) => [p.name, thunderModel(p.files.filter((f) => !f.manifest), { name: p.name })]));
47287
+ const changed = (p, file) => (p.changes ?? []).find((c) => c.file === file);
47288
+ const behavior = [], effects = [], notRead = [];
47289
+ for (const p of parts) {
47290
+ const model = models.get(p.name);
47291
+ for (const m of model.members) {
47292
+ if (m.kind === "setup" || isTestFile(m.file)) continue;
47293
+ const c = change ? changed(p, m.file) : null;
47294
+ if (change && !(c && (c.status === "added" || c.ranges.some(([a, b]) => a <= m.lines[1] && b >= m.lines[0])))) continue;
47295
+ const item4 = { part: p.name, file: m.file, lines: m.lines, name: m.label, kind: m.kind, ...c ? { change: c.status } : {} };
47296
+ if (m.kind === "not-read") {
47297
+ notRead.push({ part: p.name, file: m.file, line: m.lines[0], what: `${m.label}: Thunder does not read this yet` });
47298
+ continue;
47299
+ }
47300
+ let text2 = "";
47301
+ try {
47302
+ text2 = modelText(model, m.id).trim();
47303
+ } catch {
47304
+ text2 = "";
47305
+ }
47306
+ behavior.push({ ...item4, text: text2 });
47307
+ for (const nd of m.flow?.nodes ?? []) {
47308
+ const kind = effectKind(nd);
47309
+ if (kind) effects.push({ part: p.name, file: m.file, line: nd.line ?? m.lines[0], in: m.label, kind, says: nd.text, how: "detected", basis: "read from code; nothing was run" });
47310
+ if (nd.does === "code" && nd.line != null) notRead.push({ part: p.name, file: m.file, line: nd.line, what: `shown as code: ${String(nd.text).slice(0, 100)}` });
47311
+ }
47312
+ }
47313
+ for (const u of model.unknowns ?? []) {
47314
+ if (isTestFile(u.file)) continue;
47315
+ const c = change ? changed(p, u.file) : null;
47316
+ if (change && !(c && (c.status === "added" || c.ranges.some(([a, b]) => u.line >= a && u.line <= b)))) continue;
47317
+ const owner = model.members.find((m) => m.file === u.file && m.lines[0] <= u.line && m.lines[1] >= u.line);
47318
+ notRead.push({ part: p.name, file: u.file, line: u.line, what: owner ? `${owner.label}: ${u.why}` : u.why });
47319
+ }
47320
+ }
47321
+ const order = (a, b) => `${a.part}/${a.file}`.localeCompare(`${b.part}/${b.file}`) || (a.lines?.[0] ?? a.line ?? 0) - (b.lines?.[0] ?? b.line ?? 0);
47322
+ behavior.sort(order);
47323
+ effects.sort(order);
47324
+ notRead.sort(order);
47325
+ {
47326
+ const seen = /* @__PURE__ */ new Set();
47327
+ notRead.splice(0, notRead.length, ...notRead.filter((x) => {
47328
+ const k = `${x.part}/${x.file}:${x.line}`;
47329
+ if (seen.has(k)) return false;
47330
+ seen.add(k);
47331
+ return true;
47332
+ }));
47333
+ }
47334
+ const shownBehavior = behavior.slice(0, MAX_BEHAVIOR);
47335
+ const trace = buildTrace(parts.map((p) => ({ name: p.name, sha: p.sha ?? null, dirty: !!p.dirty, files: p.files.filter((f) => !f.manifest) })));
47336
+ const links = trace.links.map((l) => ({ kind: l.kind, says: l.kind === "http" ? `${l.from.repo} calls ${l.to.repo}: ${l.method} ${l.path} (handled by ${l.to.label ?? l.route})` : `${l.from.repo} publishes ${l.event}, and ${l.to.repo} listens`, from: l.from.cite, to: l.to.cite }));
47337
+ const services = [];
47338
+ for (const r of trace.repos) for (const q2 of r.requests ?? []) if (q2.base && q2.base !== "this app") services.push({ part: r.name, calls: `${q2.method} ${q2.base}${q2.path}`, at: `${r.name}:${q2.file}:${q2.line}` });
47339
+ const evidence2 = [];
47340
+ const add = (x) => evidence2.push({ id: `e${evidence2.length + 1}`, ...x });
47341
+ for (const r of runs) {
47342
+ const passed = r.exitCode === 0;
47343
+ const tail = String(r.output ?? "").replace(/\s+$/, "").split("\n").slice(-12).join("\n");
47344
+ add({
47345
+ kind: "test-run",
47346
+ status: passed ? "passed" : "failed",
47347
+ claim: `\`${r.command}\`${r.part ? ` in ${r.part}` : ""} exited with ${r.exitCode}${passed ? "" : " (a failure)"}.`,
47348
+ basis: { command: r.command, cwd: r.cwd, exitCode: r.exitCode, outputDigest: fileHash(r.output ?? ""), outputTail: tail },
47349
+ scope: "Only what these tests exercise. Thunder did not measure which lines or paths they cover.",
47350
+ inputs: r.part ? partInputs(r.part) : [...hashes.values()]
47351
+ });
47352
+ }
47353
+ for (const l of trace.links) {
47354
+ add({
47355
+ kind: "trace-link",
47356
+ status: "read",
47357
+ claim: l.kind === "http" ? `${l.from.repo} calls ${l.to.repo} with ${l.method} ${l.path}, and ${l.to.repo} handles it.` : `${l.from.repo} publishes "${l.event}", and ${l.to.repo} listens for it.`,
47358
+ basis: { from: l.from.cite, to: l.to.cite, rules: `thunder-trace rules v${trace.rulesVersion}` },
47359
+ scope: "Read from code; nothing was run. It does not show that the call succeeds or what it answers.",
47360
+ inputs: [inputOf(l.from.repo, l.from.file), inputOf(l.to.repo, l.to.file)]
47361
+ });
47362
+ }
47363
+ let review = null;
47364
+ if (change) {
47365
+ const oldFiles = [], newFiles = [], changedInputs = [];
47366
+ for (const p of parts) for (const c of p.changes ?? []) {
47367
+ if (c.old != null) oldFiles.push({ path: `${p.name}/${c.file}`, source: c.old });
47368
+ const now = p.files.find((f) => f.path === c.file);
47369
+ if (now && c.status !== "removed") {
47370
+ newFiles.push({ path: `${p.name}/${c.file}`, source: now.source });
47371
+ changedInputs.push(inputOf(p.name, c.file));
47372
+ }
47373
+ }
47374
+ review = thunderReview(oldFiles, newFiles);
47375
+ add({
47376
+ kind: "review",
47377
+ status: "read",
47378
+ claim: `What the change does, read from both versions: ${review.says}`,
47379
+ basis: { base: change.base, head: change.head, schema: review.schema, meaning: review.summary.meaning, risk: review.summary.risk, form: review.summary.form },
47380
+ scope: "What the code says before and after; not whether it runs or is right.",
47381
+ inputs: changedInputs
47382
+ });
47383
+ }
47384
+ for (const x of extra) add({ ...x, inputs: (x.inputs ?? []).map((i) => i.sha256 ? i : inputOf(i.part, i.file)) });
47385
+ const tested = new Set(runs.filter((r) => r.part).map((r) => r.part));
47386
+ const anyUnscoped = runs.some((r) => !r.part);
47387
+ const untested = anyUnscoped ? [] : parts.filter((p) => !tested.has(p.name)).map((p) => ({ part: p.name, what: `No tests were run in ${p.name}.` }));
47388
+ const notLinked = trace.notLinked.map((n) => ({ kind: n.kind, call: n.call, at: n.from.cite, why: n.why }));
47389
+ const unknowns = {
47390
+ notRead,
47391
+ notLinked,
47392
+ untested,
47393
+ ...behavior.length > MAX_BEHAVIOR ? { notShown: `${behavior.length - MAX_BEHAVIOR} more actions and rules are not listed (the first ${MAX_BEHAVIOR} are).` } : {},
47394
+ notVerified: [...ALWAYS_NOT_VERIFIED, ...runs.filter((r) => r.exitCode !== 0).map((r) => `\`${r.command}\` failed, so what it tests is not verified.`)]
47395
+ };
47396
+ const changedFiles = change ? parts.flatMap((p) => (p.changes ?? []).map((c) => ({ part: p.name, file: c.file, status: c.status }))) : [];
47397
+ const body2 = {
47398
+ schema: PASSPORT_SCHEMA,
47399
+ subject: { kind: change ? "change" : "feature", parts: parts.map((p) => ({ name: p.name, path: p.path ?? p.name, sha: p.sha ?? null, dirty: !!p.dirty })) },
47400
+ purpose: purpose?.text ? { stated: true, text: purpose.text, source: purpose.source ?? "given when the passport was built" } : { stated: false, text: "not stated", source: null },
47401
+ behavior: shownBehavior,
47402
+ dependencies: { files: [...hashes.values()], links, packages: parts.flatMap((p) => p.packages ?? []), services },
47403
+ effects,
47404
+ evidence: evidence2,
47405
+ unknowns,
47406
+ history: { base: change?.base ?? null, head: change?.head ?? null, changedFiles, thunder }
47407
+ };
47408
+ const summary2 = summarize2(body2);
47409
+ return { ...body2, summary: summary2, history: { ...body2.history, builtAt }, fingerprint: sha256(JSON.stringify({ ...body2, summary: summary2 })) };
47410
+ }
47411
+ function summarize2(p) {
47412
+ const by = (s) => p.evidence.filter((e) => e.status === s).length;
47413
+ const u = p.unknowns;
47414
+ return {
47415
+ claims: p.evidence.length,
47416
+ passed: by("passed"),
47417
+ failed: by("failed"),
47418
+ readFromCode: by("read"),
47419
+ unknowns: u.notRead.length + u.notLinked.length + u.untested.length,
47420
+ notVerified: u.notVerified.length
47421
+ };
47422
+ }
47423
+ function checkPassport(passport, { read }) {
47424
+ if (passport?.schema !== PASSPORT_SCHEMA) throw new Error("this is not a Thunder passport (thunder-passport-v1).");
47425
+ const cache = /* @__PURE__ */ new Map();
47426
+ const now = (part, file) => {
47427
+ const k = `${part}/${file}`;
47428
+ if (!cache.has(k)) {
47429
+ const s = read(part, file);
47430
+ cache.set(k, s == null ? null : fileHash(s));
47431
+ }
47432
+ return cache.get(k);
47433
+ };
47434
+ const items = passport.evidence.map((e) => {
47435
+ if (!e.inputs?.length) return { id: e.id, kind: e.kind, claim: e.claim, freshness: "unknown", changed: [] };
47436
+ const changed = [];
47437
+ for (const i of e.inputs) {
47438
+ const h = now(i.part, i.file);
47439
+ if (h == null) changed.push({ part: i.part, file: i.file, now: "missing" });
47440
+ else if (h !== i.sha256) changed.push({ part: i.part, file: i.file, now: "changed" });
47441
+ }
47442
+ return { id: e.id, kind: e.kind, claim: e.claim, freshness: changed.length ? "stale" : "current", changed };
47443
+ });
47444
+ const files = passport.dependencies.files.map((f) => ({ ...f, now: now(f.part, f.file) })).filter((f) => f.now !== f.sha256).map((f) => ({ part: f.part, file: f.file, now: f.now == null ? "missing" : "changed" }));
47445
+ return { schema: "thunder-passport-check-v1", current: items.filter((x) => x.freshness === "current").length, stale: items.filter((x) => x.freshness === "stale").length, items, changedFiles: files };
47446
+ }
47447
+ var MARK2 = { passed: "\u2713", failed: "\u2717", read: "\u25CB" };
47448
+ var STATUS_WORDS = { passed: "ran and passed", failed: "ran and failed", read: "read from code, not run" };
47449
+ function renderPassportSummary(p) {
47450
+ const s = p.summary;
47451
+ const L = [
47452
+ `Thunder passport (${p.subject.kind}): ${p.subject.parts.map((x) => x.name).join(", ")}`,
47453
+ `Purpose: ${p.purpose.stated ? p.purpose.text : "not stated"}`,
47454
+ `${s.claims} claim${s.claims === 1 ? "" : "s"} with evidence (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), ${s.unknowns} unknown${s.unknowns === 1 ? "" : "s"}, ${s.notVerified} not verified`,
47455
+ "",
47456
+ "Evidence"
47457
+ ];
47458
+ for (const e of p.evidence) L.push(` ${MARK2[e.status] ?? "\u25CB"} ${STATUS_WORDS[e.status] ?? e.status}: ${e.claim}`);
47459
+ if (!p.evidence.length) L.push(" (none: nothing in this passport is verified)");
47460
+ L.push("", "Not verified");
47461
+ for (const x of p.unknowns.notVerified) L.push(` \u25CB ${x}`);
47462
+ if (p.unknowns.untested.length) for (const x of p.unknowns.untested) L.push(` \u25CB ${x.what}`);
47463
+ return L.join("\n");
47464
+ }
47465
+ function renderPassportMarkdown(p) {
47466
+ const s = p.summary;
47467
+ const L = [
47468
+ `# Thunder passport: ${p.subject.parts.map((x) => x.name).join(", ")}`,
47469
+ "",
47470
+ `A ${p.subject.kind === "change" ? `change${p.history.base ? ` from \`${String(p.history.base).slice(0, 12)}\`` : ""}` : "snapshot"}. **${s.claims} claims with evidence** (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), **${s.unknowns} unknowns**, **${s.notVerified} not verified**. This is an evidence record, not a certificate: each claim says what it rests on and what it does not cover.`,
47471
+ "",
47472
+ "## Purpose",
47473
+ "",
47474
+ p.purpose.stated ? `${p.purpose.text}
47475
+
47476
+ (Source: ${p.purpose.source}.)` : "Not stated. Thunder never guesses what a change is for.",
47477
+ ""
47478
+ ];
47479
+ const evidenceList = (list3) => {
47480
+ for (const e of list3) {
47481
+ L.push(`- ${MARK2[e.status] ?? "\u25CB"} ${e.claim}`);
47482
+ const b = e.basis;
47483
+ L.push(` - Basis: ${b.command ? `\`${b.command}\` in \`${b.cwd}\`, exit ${b.exitCode}, output ${String(b.outputDigest).slice(0, 19)}\u2026` : b.from ? `${b.from} \u2192 ${b.to}` : b.base ? `review of ${String(b.base).slice(0, 12)} \u2192 ${String(b.head ?? "working tree").slice(0, 12)}` : JSON.stringify(b)}`);
47484
+ L.push(` - Does not cover: ${e.scope}`);
47485
+ L.push(` - Depends on ${e.inputs.length} file${e.inputs.length === 1 ? "" : "s"} (by content hash)`);
47486
+ }
47487
+ };
47488
+ const ran = p.evidence.filter((e) => e.status === "passed"), failedRuns = p.evidence.filter((e) => e.status === "failed"), readOnly = p.evidence.filter((e) => e.status !== "passed" && e.status !== "failed");
47489
+ L.push("## Verified by running (ran and passed)", "");
47490
+ if (ran.length) evidenceList(ran);
47491
+ else L.push("Nothing was run, so nothing here is verified by running.");
47492
+ if (failedRuns.length) {
47493
+ L.push("", "## Ran and failed", "");
47494
+ evidenceList(failedRuns);
47495
+ }
47496
+ L.push("", "## Read from code (not run)", "");
47497
+ if (readOnly.length) evidenceList(readOnly);
47498
+ else L.push("None.");
47499
+ L.push("", "## Not verified", "", ...p.unknowns.notVerified.map((x) => `- ${x}`), ...p.unknowns.untested.map((x) => `- ${x.what}`), "");
47500
+ L.push("## Behavior", "");
47501
+ for (const b of p.behavior) {
47502
+ L.push(`### ${b.name} (${b.part}/${b.file}, lines ${b.lines[0]}\u2013${b.lines[1]}${b.change ? `, ${b.change}` : ""})`, "", "```text", b.text || "(no reading)", "```", "");
47503
+ }
47504
+ if (p.unknowns.notShown) L.push(p.unknowns.notShown, "");
47505
+ L.push("## Effects (detected in code, not observed)", "");
47506
+ for (const e of p.effects) L.push(`- ${e.in} **${e.kind}**: ${e.says} (${e.part}/${e.file}:${e.line})`);
47507
+ if (!p.effects.length) L.push("None detected.");
47508
+ L.push("", "## Dependencies", "", ...p.dependencies.links.map((l) => `- ${l.says} (${l.from} \u2192 ${l.to})`));
47509
+ if (p.dependencies.packages.length) L.push(...p.dependencies.packages.map((x) => `- package ${x.name}${x.version ? ` ${x.version}` : ""} (${x.from})`));
47510
+ if (p.dependencies.services.length) L.push(...p.dependencies.services.map((x) => `- calls ${x.calls} (${x.at})`));
47511
+ L.push(`- ${p.dependencies.files.length} files read, each recorded by content hash`, "");
47512
+ L.push("## Unknowns", "");
47513
+ for (const x of p.unknowns.notRead) L.push(`- not read: ${x.what} (${x.part}/${x.file}:${x.line})`);
47514
+ for (const x of p.unknowns.notLinked) L.push(`- not linked: ${x.call}: ${x.why} (${x.at})`);
47515
+ if (!p.unknowns.notRead.length && !p.unknowns.notLinked.length) L.push("Nothing Thunder failed to read or link.");
47516
+ L.push("", "## History", "", `- Base: ${p.history.base ?? "(none: a snapshot)"}`, `- Head: ${p.history.head ?? "(working tree)"}`, ...p.history.changedFiles.map((c) => `- ${c.status}: ${c.part}/${c.file}`), `- Built: ${p.history.builtAt}${p.history.thunder ? ` with Thunder ${p.history.thunder}` : ""}`, `- Fingerprint: ${p.fingerprint}`, "");
47517
+ return L.join("\n");
47518
+ }
47519
+
47520
+ // src/passport-fs.mjs
47521
+ var git3 = (dir, args) => {
47522
+ try {
47523
+ return (0, import_node_child_process4.execFileSync)("git", ["-C", dir, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 256 * 1024 * 1024 });
47524
+ } catch {
47525
+ return null;
47526
+ }
47527
+ };
47528
+ var SKIP2 = /* @__PURE__ */ new Set(["node_modules", ".git", "bin", "obj", "dist", "build", "__pycache__", ".venv", "venv", "target", ".next"]);
47529
+ function packagesIn(root) {
47530
+ const out = [];
47531
+ const walk = (dir, depth) => {
47532
+ if (depth > 4) return;
47533
+ let names = [];
47534
+ try {
47535
+ names = (0, import_node_fs4.readdirSync)(dir).sort();
47536
+ } catch {
47537
+ return;
47538
+ }
47539
+ for (const n of names) {
47540
+ if (SKIP2.has(n)) continue;
47541
+ const full = (0, import_node_path5.join)(dir, n);
47542
+ let st;
47543
+ try {
47544
+ st = (0, import_node_fs4.statSync)(full);
47545
+ } catch {
47546
+ continue;
47547
+ }
47548
+ if (st.isDirectory()) {
47549
+ walk(full, depth + 1);
47550
+ continue;
47551
+ }
47552
+ const rel2 = (0, import_node_path5.relative)(root, full).split("\\").join("/");
47553
+ try {
47554
+ if (n === "package.json") {
47555
+ const j = JSON.parse((0, import_node_fs4.readFileSync)(full, "utf8"));
47556
+ for (const k of ["dependencies", "devDependencies"]) for (const [name, version] of Object.entries(j[k] ?? {})) out.push({ name, version: String(version), from: rel2, ...k === "devDependencies" ? { dev: true } : {} });
47557
+ } else if (n === "requirements.txt") {
47558
+ for (const line of (0, import_node_fs4.readFileSync)(full, "utf8").split("\n")) {
47559
+ const m = line.replace(/#.*/, "").trim().match(/^([A-Za-z0-9_.-]+)\s*(.*)$/);
47560
+ if (m) out.push({ name: m[1], ...m[2] ? { version: m[2] } : {}, from: rel2 });
47561
+ }
47562
+ } else if (/\.csproj$/.test(n)) {
47563
+ for (const m of (0, import_node_fs4.readFileSync)(full, "utf8").matchAll(/<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?/g)) out.push({ name: m[1], ...m[2] ? { version: m[2] } : {}, from: rel2 });
47564
+ }
47565
+ } catch {
47566
+ }
47567
+ }
47568
+ };
47569
+ walk(root, 0);
47570
+ return out;
47571
+ }
47572
+ function changesSince(root, base2) {
47573
+ const prefix = git3(root, ["rev-parse", "--show-prefix"])?.trim() ?? "";
47574
+ const diff = git3(root, ["diff", "--unified=0", "--no-color", "--no-renames", base2, "--", "."]) ?? "";
47575
+ const byFile = /* @__PURE__ */ new Map();
47576
+ let cur = null;
47577
+ for (const line of diff.split("\n")) {
47578
+ let m;
47579
+ if (m = line.match(/^diff --git a\/(.+) b\/(.+)$/)) {
47580
+ cur = { file: m[2], ranges: [], status: "changed" };
47581
+ byFile.set(cur.file, cur);
47582
+ } else if (cur && line.startsWith("new file mode")) cur.status = "added";
47583
+ else if (cur && line.startsWith("deleted file mode")) cur.status = "removed";
47584
+ else if (cur && (m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/))) {
47585
+ const start = Number(m[1]), n = m[2] === void 0 ? 1 : Number(m[2]);
47586
+ cur.ranges.push(n === 0 ? [Math.max(1, start), Math.max(1, start)] : [start, start + n - 1]);
47587
+ }
47588
+ }
47589
+ for (const f of (git3(root, ["ls-files", "--others", "--exclude-standard", "--", "."]) ?? "").split("\n").filter(Boolean)) {
47590
+ const file = prefix + f;
47591
+ if (!byFile.has(file)) byFile.set(file, { file, ranges: [], status: "added" });
47592
+ }
47593
+ const out = [];
47594
+ for (const c of byFile.values()) {
47595
+ if (!c.file.startsWith(prefix)) continue;
47596
+ const old = c.status === "added" ? null : git3(root, ["show", `${base2}:${c.file}`]);
47597
+ out.push({ file: c.file.slice(prefix.length), status: c.status, ranges: c.ranges, old: old == null || old.includes("\0") ? null : old });
47598
+ }
47599
+ return out.sort((a, b) => a.file.localeCompare(b.file));
47600
+ }
47601
+ function accessEvidence(report, partOf = () => null) {
47602
+ const words14 = { guarded: "checks that the record belongs to the caller on every path", unguarded: "has a path with no ownership check (every step was followed)", "cannot tell": "cannot be told: Thunder could not follow every step", "cannot-tell": "cannot be told: Thunder could not follow every step" };
47603
+ return (report?.routes ?? []).filter((r) => r.verdict).map((r) => {
47604
+ const part = r.part ?? partOf(r.file);
47605
+ const files = [...new Set([r.file, ...(r.paths ?? []).flatMap((x) => (x.steps ?? []).map((st) => st.file))].filter(Boolean))];
47606
+ return {
47607
+ kind: "access-flow",
47608
+ status: "read",
47609
+ claim: `${r.method && r.path ? `${r.method} ${r.path}` : r.route ?? "A route"}${part ? ` in ${part}` : ""} ${words14[r.verdict] ?? `has the verdict "${r.verdict}"`}.`,
47610
+ basis: { schema: report.schema ?? "thunder-access-v1", verdict: r.verdict, at: r.file ? `${part ? `${part}:` : ""}${r.file}${r.line ? `:${r.line}` : ""}` : null, why: r.why ?? null },
47611
+ scope: "Read from code by the ownership check; nothing was run. Only the frameworks and data libraries it supports, and only these files.",
47612
+ inputs: part ? files.map((file) => ({ part, file })) : []
47613
+ };
47614
+ });
47615
+ }
47616
+ function buildPassport({ parts, base: base2 = null, head = null, run = [], purpose = null, evidence: evidence2 = [], access = null, relativeTo = process.cwd(), builtAt, timeoutMs = 20 * 60 * 1e3 } = {}) {
47617
+ if (!parts?.length) throw new Error("name at least one folder to describe.");
47618
+ const names = /* @__PURE__ */ new Set();
47619
+ const read = parts.map((dir) => {
47620
+ const root = (0, import_node_path5.resolve)(dir);
47621
+ let ok = false;
47622
+ try {
47623
+ ok = (0, import_node_fs4.statSync)(root).isDirectory();
47624
+ } catch {
47625
+ }
47626
+ if (!ok) throw new Error(`${dir} is not a folder.`);
47627
+ const name = (0, import_node_path5.basename)(root);
47628
+ if (names.has(name)) throw new Error(`two parts are called "${name}"; give folders with different names.`);
47629
+ names.add(name);
47630
+ const top = git3(root, ["rev-parse", "--show-toplevel"])?.trim() ?? null;
47631
+ const sha = top ? git3(root, ["rev-parse", "HEAD"])?.trim() || null : null;
47632
+ const dirty = top ? !!git3(root, ["status", "--porcelain", "--", "."])?.trim() : false;
47633
+ if (head && top) {
47634
+ const want = git3(root, ["rev-parse", "--verify", `${head}^{commit}`])?.trim();
47635
+ if (!want) throw new Error(`${head} is not a commit in ${dir}.`);
47636
+ if (want !== sha) throw new Error(`the passport reads the files on disk, and ${dir} is not at ${head}. Check out ${head} first.`);
47637
+ }
47638
+ let changes;
47639
+ if (base2) {
47640
+ if (!top) throw new Error(`${dir} is not in a git repository, so there is no ${base2} to compare with.`);
47641
+ if (!git3(root, ["rev-parse", "--verify", `${base2}^{commit}`])?.trim()) throw new Error(`${base2} is not a commit in ${dir}.`);
47642
+ changes = changesSince(root, base2);
47643
+ }
47644
+ const files = collectReadableFiles(root).map((f) => ({ path: f.path, source: f.source }));
47645
+ return { name, root, path: (0, import_node_path5.relative)(relativeTo, root).split("\\").join("/") || ".", sha, dirty, files, packages: packagesIn(root), ...changes ? { changes } : {} };
47646
+ });
47647
+ const runs = run.map((spec) => {
47648
+ const m = String(spec).match(/^([A-Za-z0-9_.-]+):\s+(.+)$/);
47649
+ const part = m && read.find((p) => p.name === m[1]) ? m[1] : null;
47650
+ const command = part ? m[2] : String(spec);
47651
+ const cwd = part ? read.find((p) => p.name === part).root : process.cwd();
47652
+ const r = (0, import_node_child_process4.spawnSync)(`(${command}) 2>&1`, { shell: true, cwd, encoding: "utf8", timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });
47653
+ const exitCode = r.status ?? (r.error || r.signal ? 1 : 0);
47654
+ const output = `${r.stdout ?? ""}${r.error ? `
47655
+ (${r.error.message})` : ""}${r.signal ? `
47656
+ (stopped by ${r.signal})` : ""}`;
47657
+ return { command, part, cwd: (0, import_node_path5.relative)(relativeTo, cwd).split("\\").join("/") || ".", exitCode, output };
47658
+ });
47659
+ const extra = [];
47660
+ const partOf = (file) => {
47661
+ const hits = read.filter((p) => p.files.some((f) => f.path === file));
47662
+ return hits.length === 1 ? hits[0].name : null;
47663
+ };
47664
+ if (typeof access === "function") {
47665
+ for (const p of read) {
47666
+ try {
47667
+ extra.push(...accessEvidence(access(p.files), () => p.name));
47668
+ } catch {
47669
+ }
47670
+ }
47671
+ }
47672
+ for (const e of evidence2) {
47673
+ if (e?.schema === "thunder-access-v1") extra.push(...accessEvidence(e, partOf));
47674
+ else if (Array.isArray(e)) extra.push(...e.filter((x) => x && x.kind && x.claim && x.basis && x.scope).map((x) => ({ status: "read", ...x })));
47675
+ }
47676
+ const change = base2 ? { base: git3(read[0].root, ["rev-parse", base2])?.trim() ?? base2, head: head ? read[0].sha : read[0].sha ? `${read[0].sha}${read.some((p) => p.dirty) ? " (with uncommitted changes)" : ""}` : null } : null;
47677
+ return assemblePassport({ parts: read, change, runs, purpose, extra, builtAt, thunder: COMPILER_VERSION });
47678
+ }
47679
+ function checkPassportOnDisk(passport, { baseDir = process.cwd(), dirs = {} } = {}) {
47680
+ const where = new Map(passport.subject.parts.map((p) => [p.name, dirs[p.name] ? (0, import_node_path5.resolve)(dirs[p.name]) : (0, import_node_path5.resolve)(baseDir, p.path)]));
47681
+ return checkPassport(passport, {
47682
+ read: (part, file) => {
47683
+ const root = where.get(part);
47684
+ if (!root) return null;
47685
+ const full = (0, import_node_path5.join)(root, file);
47686
+ try {
47687
+ return (0, import_node_fs4.existsSync)(full) ? (0, import_node_fs4.readFileSync)(full, "utf8") : null;
47688
+ } catch {
47689
+ return null;
47690
+ }
47691
+ }
47692
+ });
47693
+ }
44215
47694
  // Annotate the CommonJS export names for ESM import in node:
44216
47695
  0 && (module.exports = {
44217
47696
  ACCESSIBILITY_CLASSIFICATION,
@@ -44280,6 +47759,7 @@ function planOnly(original, list3) {
44280
47759
  NODE_STATUSES,
44281
47760
  NODE_TYPES,
44282
47761
  OUTCOME_SCHEMA,
47762
+ PASSPORT_SCHEMA,
44283
47763
  PATCH_SCHEMA,
44284
47764
  PRIVACY_SCHEMA,
44285
47765
  PROMOTE_SCHEMA,
@@ -44335,6 +47815,7 @@ function planOnly(original, list3) {
44335
47815
  WRITE_STEPS_LANGUAGES,
44336
47816
  WRITE_STEPS_SCHEMA,
44337
47817
  acceptedRisks,
47818
+ accessEvidence,
44338
47819
  adoptRegion,
44339
47820
  analyzeDecision,
44340
47821
  analyzeDistributed,
@@ -44346,6 +47827,7 @@ function planOnly(original, list3) {
44346
47827
  approvalFor,
44347
47828
  approvalsFor,
44348
47829
  approveIntent,
47830
+ assemblePassport,
44349
47831
  atlasNode,
44350
47832
  autocorrectSource,
44351
47833
  backfillNodeField,
@@ -44362,6 +47844,7 @@ function planOnly(original, list3) {
44362
47844
  buildLifecycle,
44363
47845
  buildManifest,
44364
47846
  buildMissionIndex,
47847
+ buildPassport,
44365
47848
  buildProof,
44366
47849
  buildReport,
44367
47850
  buildReviewAtlas,
@@ -44369,6 +47852,8 @@ function planOnly(original, list3) {
44369
47852
  changedCases,
44370
47853
  checkDecisionCases,
44371
47854
  checkDrift,
47855
+ checkPassport,
47856
+ checkPassportOnDisk,
44372
47857
  classify,
44373
47858
  collectReadableFiles,
44374
47859
  compileExpr,
@@ -44496,6 +47981,8 @@ function planOnly(original, list3) {
44496
47981
  renderMarkdown,
44497
47982
  renderMarker,
44498
47983
  renderMermaid,
47984
+ renderPassportMarkdown,
47985
+ renderPassportSummary,
44499
47986
  renderReview,
44500
47987
  renderReviewBrief,
44501
47988
  renderReviewComment,