walkdiff 0.8.0 → 0.10.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/walkdiff.mjs CHANGED
@@ -14,6 +14,7 @@ import { LineCounter, isMap, isPair, isScalar, isSeq, parseAllDocuments } from "
14
14
  import Anthropic from "@anthropic-ai/sdk";
15
15
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
16
16
  import { inflateRawSync } from "node:zlib";
17
+ import { setTimeout } from "node:timers/promises";
17
18
  import { createServer } from "node:http";
18
19
  import { DatabaseSync } from "node:sqlite";
19
20
  // packages/engine/src/git.ts
@@ -320,7 +321,11 @@ const SourceLanguage = {
320
321
  Rust: "rust",
321
322
  TypeScript: "typescript",
322
323
  Tsx: "tsx",
323
- Python: "python"
324
+ Python: "python",
325
+ Go: "go",
326
+ Java: "java",
327
+ C: "c",
328
+ Cpp: "cpp"
324
329
  };
325
330
  const UnitKind = {
326
331
  Function: "function",
@@ -335,6 +340,12 @@ const UnitKind = {
335
340
  Constant: "constant",
336
341
  Macro: "macro",
337
342
  Module: "module",
343
+ /** A group of tests, such as `describe("parser", () => …)`. Its tests and hooks are units of their own. */
344
+ TestSuite: "testSuite",
345
+ /** One test, such as `it("reads includes", () => …)`. */
346
+ Test: "test",
347
+ /** Setup or teardown around tests, such as `beforeEach(() => …)`. */
348
+ TestHook: "testHook",
338
349
  /** Everything in a file outside its top-level definitions: imports, top-level statements. */
339
350
  ModuleScope: "moduleScope"
340
351
  };
@@ -878,6 +889,7 @@ function isBehaviourChange(change) {
878
889
  case UnitChangeKind.MovedOut: return false;
879
890
  }
880
891
  }
892
+ UnitKind.TestSuite, UnitKind.Test, UnitKind.TestHook;
881
893
  /** Places using this unit that the PR did not change. */
882
894
  function untouchedReferences(unit) {
883
895
  if (unit.impact?.status !== UnitImpactStatus.Traced) return [];
@@ -1588,6 +1600,79 @@ function countChangedLines(content) {
1588
1600
  deletions
1589
1601
  };
1590
1602
  }
1603
+ // packages/engine/src/syntax/declarators.ts
1604
+ /**
1605
+ * C and C++ write a declared name inside nested declarators that read like its type:
1606
+ * `char *(*handlers[4])(int)` wraps `handlers` in pointer, array and function declarators.
1607
+ * These helpers find the name, and for a function the declarator listing its parameters.
1608
+ */
1609
+ const NAME_TYPES = /* @__PURE__ */ new Set([
1610
+ "identifier",
1611
+ "field_identifier",
1612
+ "type_identifier",
1613
+ "destructor_name",
1614
+ "operator_name",
1615
+ "operator_cast",
1616
+ "qualified_identifier",
1617
+ "template_function"
1618
+ ]);
1619
+ const WRAPPER_TYPES = /* @__PURE__ */ new Set([
1620
+ "parenthesized_declarator",
1621
+ "reference_declarator",
1622
+ "variadic_declarator",
1623
+ "attributed_declarator"
1624
+ ]);
1625
+ const FUNCTION_DECLARATOR = "function_declarator";
1626
+ const QUALIFIED_NAME = "qualified_identifier";
1627
+ const TEMPLATE_FUNCTION = "template_function";
1628
+ const TEMPLATE_TYPE$1 = "template_type";
1629
+ const SCOPE_SEPARATOR = "::";
1630
+ /** The name a declaration, definition or typedef declares through its first declarator. */
1631
+ function declaredName(declaration) {
1632
+ const chain = declaratorChain(declaration);
1633
+ const last = chain.at(-1);
1634
+ if (last === void 0 || !NAME_TYPES.has(last.type)) return void 0;
1635
+ const parent = chain.at(-2);
1636
+ const functionDeclarator = parent?.type === FUNCTION_DECLARATOR ? parent : void 0;
1637
+ return {
1638
+ ...splitQualifiedName(last),
1639
+ functionDeclarator
1640
+ };
1641
+ }
1642
+ function declaratorChain(declaration) {
1643
+ const chain = [];
1644
+ for (let current = declaration.childForFieldName("declarator"); current !== null; current = innerDeclarator(current)) {
1645
+ chain.push(current);
1646
+ if (NAME_TYPES.has(current.type)) break;
1647
+ }
1648
+ return chain;
1649
+ }
1650
+ function innerDeclarator(declarator) {
1651
+ return declarator.childForFieldName("declarator") ?? (WRAPPER_TYPES.has(declarator.type) ? declarator.firstNamedChild : null);
1652
+ }
1653
+ function splitQualifiedName(node) {
1654
+ const scopes = [];
1655
+ let current = node;
1656
+ for (let inner = qualifiedParts(current); inner !== void 0; inner = qualifiedParts(current)) {
1657
+ if (inner.scope !== null) scopes.push(scopeName(inner.scope));
1658
+ current = inner.name;
1659
+ }
1660
+ return {
1661
+ name: current.type === TEMPLATE_FUNCTION ? current.childForFieldName("name")?.text ?? current.text : current.text,
1662
+ nameNode: current,
1663
+ owner: scopes.length === 0 ? void 0 : scopes.join(SCOPE_SEPARATOR)
1664
+ };
1665
+ }
1666
+ function qualifiedParts(node) {
1667
+ const name = node.type === QUALIFIED_NAME ? node.childForFieldName("name") : null;
1668
+ return name === null ? void 0 : {
1669
+ scope: node.childForFieldName("scope"),
1670
+ name
1671
+ };
1672
+ }
1673
+ function scopeName(scope) {
1674
+ return scope.type === TEMPLATE_TYPE$1 ? scope.childForFieldName("name")?.text ?? scope.text : scope.text;
1675
+ }
1591
1676
  // packages/engine/src/syntax/languageSpec.ts
1592
1677
  /** How a caller supplies a parameter, or a marker in the list that changes how later ones are supplied. */
1593
1678
  const ParameterKind = {
@@ -1612,10 +1697,10 @@ const IdentifierUseKind = {
1612
1697
  /** The name on its own: `parse(input)`, `Size`. */
1613
1698
  Bare: "bare"
1614
1699
  };
1615
- const BARE_USE = { kind: IdentifierUseKind.Bare };
1700
+ const BARE_USE$1 = { kind: IdentifierUseKind.Bare };
1616
1701
  function classifyWithGrammar(leaf, grammar) {
1617
1702
  const parent = leaf.parent;
1618
- if (parent === null) return BARE_USE;
1703
+ if (parent === null) return BARE_USE$1;
1619
1704
  const member = grammar.member.get(parent.type);
1620
1705
  if (member !== void 0 && isField(parent, member[0], leaf)) return {
1621
1706
  kind: IdentifierUseKind.Member,
@@ -1629,7 +1714,7 @@ function classifyWithGrammar(leaf, grammar) {
1629
1714
  const label = grammar.labels.get(parent.type);
1630
1715
  if (label !== void 0 && isField(parent, label, leaf) || isBindingWithGrammar(leaf, grammar)) return;
1631
1716
  if (isField(parent, "name", leaf) && !grammar.nameIsUse.has(parent.type)) return;
1632
- return BARE_USE;
1717
+ return BARE_USE$1;
1633
1718
  }
1634
1719
  function isBindingWithGrammar(leaf, grammar) {
1635
1720
  const parent = leaf.parent;
@@ -1652,17 +1737,18 @@ function namedDefinition(node, kind) {
1652
1737
  const MAX_CALLEE_TEXT = 40;
1653
1738
  const LAST_SEGMENT = /[\p{L}\p{N}_$]+$/u;
1654
1739
  const RECEIVER_PARAMETER = /\b(self|cls)$|^this$/;
1740
+ const NO_PARAMETERS = "void";
1655
1741
  function extractShape(grammar, definition) {
1656
1742
  const fn = grammar.functionNode(definition);
1657
1743
  const calls = callNames(grammar, fn);
1658
1744
  const bailOuts = calls.list.filter((name) => grammar.errorCalls.has(name)).length;
1659
- const parameterNodes = parameterNodesOf(fn);
1660
- const parameters = new Map(parameterNodes.map((node) => [squeeze(parameterName(node)), squeeze(node.text)]));
1745
+ const slots = parameterNodesOf(grammar.signatureNode(fn)).flatMap(parameterSlots);
1746
+ const parameters = new Map(slots.map((slot) => [slot.name, slot.text]));
1661
1747
  const branches = fn.descendantsOfType([...grammar.branchTypes]).length;
1662
1748
  return {
1663
1749
  parameters,
1664
- signature: parameterNodes.map((node) => signatureParameter(grammar, node)),
1665
- returnType: typeText(fn.childForFieldName("return_type")),
1750
+ signature: slots.map((slot) => signatureParameter(grammar, slot)),
1751
+ returnType: typeText(fn.childForFieldName(grammar.returnTypeField)),
1666
1752
  calls: new Set(calls.list),
1667
1753
  errorPaths: fn.descendantsOfType([...grammar.errorTypes]).length + bailOuts,
1668
1754
  branches,
@@ -1714,37 +1800,55 @@ function factsBetween(before, after) {
1714
1800
  function parameterNodesOf(fn) {
1715
1801
  const list = fn.childForFieldName("parameters");
1716
1802
  const single = fn.childForFieldName("parameter");
1717
- return (list === null ? single === null ? [] : [single] : list.namedChildren).filter((node) => node !== null && !node.type.includes("comment"));
1803
+ return (list === null ? single === null ? [] : [single] : list.namedChildren).filter((node) => node !== null && !node.type.includes("comment") && node.text !== NO_PARAMETERS);
1804
+ }
1805
+ function parameterSlots(node) {
1806
+ const names = node.childrenForFieldName("name").filter((name) => name !== null);
1807
+ if (names.length < 2) return [{
1808
+ name: squeeze$1(parameterName(node)),
1809
+ text: squeeze$1(node.text),
1810
+ node
1811
+ }];
1812
+ const type = node.childForFieldName("type")?.text ?? "";
1813
+ return names.map((name) => ({
1814
+ name: name.text,
1815
+ text: squeeze$1(`${name.text} ${type}`),
1816
+ node
1817
+ }));
1718
1818
  }
1719
- function signatureParameter(grammar, node) {
1720
- const name = squeeze(parameterName(node)).replace(/^\*+/, "");
1819
+ function signatureParameter(grammar, slot) {
1820
+ const name = slot.name.replace(/^\*+/, "");
1721
1821
  return {
1722
1822
  name,
1723
- kind: RECEIVER_PARAMETER.test(name) ? ParameterKind.Receiver : grammar.parameterKind(node),
1724
- type: typeText(node.childForFieldName("type"))
1823
+ kind: RECEIVER_PARAMETER.test(name) ? ParameterKind.Receiver : grammar.parameterKind(slot.node),
1824
+ type: typeText(slot.node.childForFieldName("type"))
1725
1825
  };
1726
1826
  }
1727
1827
  function typeText(node) {
1728
- return squeeze(node?.text ?? "").replace(/^:\s*/, "") || null;
1828
+ return squeeze$1(node?.text ?? "").replace(/^:\s*/, "") || null;
1729
1829
  }
1730
1830
  function parameterName(node) {
1731
- const named = node.childForFieldName("pattern") ?? node.childForFieldName("name");
1831
+ const named = node.childForFieldName("pattern") ?? node.childForFieldName("name") ?? declaratorName(node) ?? declaredName(node)?.nameNode ?? null;
1732
1832
  if (named !== null) return named.text;
1733
1833
  return node.type.includes("typed") ? node.firstNamedChild?.text ?? node.text : node.text;
1734
1834
  }
1835
+ function declaratorName(node) {
1836
+ return node.namedChildren.find((child) => child?.type === "variable_declarator")?.childForFieldName("name") ?? null;
1837
+ }
1735
1838
  function callNames(grammar, fn) {
1736
1839
  return { list: fn.descendantsOfType([...grammar.calls.keys()]).flatMap((call) => {
1737
1840
  const syntax = call === null ? void 0 : grammar.calls.get(call.type);
1738
1841
  const callee = syntax === void 0 ? null : call?.childForFieldName(syntax.calleeField) ?? null;
1739
- return syntax === void 0 || callee === null ? [] : [`${calleeName(callee)}${syntax.suffix}`];
1842
+ const name = callee === null ? void 0 : calleeName(callee);
1843
+ return syntax === void 0 || name === void 0 ? [] : [`${name}${syntax.suffix}`];
1740
1844
  }) };
1741
1845
  }
1742
1846
  function calleeName(callee) {
1743
1847
  const text = callee.text.replace(/\s+/g, "");
1744
1848
  if (text.length <= MAX_CALLEE_TEXT && !text.includes("(")) return text;
1745
- return LAST_SEGMENT.exec(text)?.[0] ?? text.slice(0, MAX_CALLEE_TEXT);
1849
+ return LAST_SEGMENT.exec(text)?.[0];
1746
1850
  }
1747
- function squeeze(text) {
1851
+ function squeeze$1(text) {
1748
1852
  return text.replace(/\s+/g, " ").trim();
1749
1853
  }
1750
1854
  // packages/engine/src/syntax/definitions.ts
@@ -1758,6 +1862,7 @@ const CLOSING_BRACKETS = /* @__PURE__ */ new Set([
1758
1862
  "}",
1759
1863
  ">"
1760
1864
  ]);
1865
+ const TEST_TITLE_SEPARATOR = " › ";
1761
1866
  /** Extracts the file's units. Must run inside `withSyntaxTree`: it reads nodes of a live tree. */
1762
1867
  function extractUnits(spec, tree, source) {
1763
1868
  const walker = new DefinitionWalker(spec, spec.publicDefinitions(tree.rootNode));
@@ -1805,7 +1910,9 @@ var DefinitionWalker = class {
1805
1910
  const outer = this.#spec.outerNode(node);
1806
1911
  const nodes = [...this.#attachedPrefix(outer), outer];
1807
1912
  const first = nodes.at(0) ?? outer;
1808
- const qualifiedName = container === void 0 ? header.name : `${container.childPrefix}${this.#spec.separator}${header.name}`;
1913
+ const separator = container?.kind === UnitKind.TestSuite ? TEST_TITLE_SEPARATOR : this.#spec.separator;
1914
+ const prefix = [container?.childPrefix, header.owner].filter((part) => part !== void 0).join(this.#spec.separator);
1915
+ const qualifiedName = prefix === "" ? header.name : `${prefix}${separator}${header.name}`;
1809
1916
  return {
1810
1917
  header,
1811
1918
  node,
@@ -1866,6 +1973,12 @@ function toDefinition(spec, raw, lines) {
1866
1973
  text: outline(lines, startLine - 1, endLine - 1, raw.children),
1867
1974
  elidesNestedUnits: raw.children.length > 0
1868
1975
  },
1976
+ wholeSnapshot: {
1977
+ startLine,
1978
+ endLine,
1979
+ text: lines.slice(startLine - 1, endLine).join("\n"),
1980
+ elidesNestedUnits: false
1981
+ },
1869
1982
  codeTokens: code.map((token) => token.text),
1870
1983
  shape: raw.header.kind === UnitKind.Function || raw.header.kind === UnitKind.Method ? extractShape(spec.shape, raw.node) : void 0,
1871
1984
  fingerprints: {
@@ -1961,6 +2074,545 @@ function hashFull(tokens) {
1961
2074
  function hashTexts(texts) {
1962
2075
  return createHash("sha1").update(texts.join(TOKEN_SEPARATOR)).digest("hex");
1963
2076
  }
2077
+ // packages/engine/src/syntax/cFamily.ts
2078
+ const KIND_BY_SPECIFIER = /* @__PURE__ */ new Map([
2079
+ ["class_specifier", UnitKind.Class],
2080
+ ["struct_specifier", UnitKind.Struct],
2081
+ ["union_specifier", UnitKind.Struct],
2082
+ ["enum_specifier", UnitKind.Enum]
2083
+ ]);
2084
+ const CLASS_KINDS = /* @__PURE__ */ new Set([UnitKind.Class, UnitKind.Struct]);
2085
+ const CONTAINERS$5 = /* @__PURE__ */ new Set([
2086
+ UnitKind.Module,
2087
+ UnitKind.Class,
2088
+ UnitKind.Struct
2089
+ ]);
2090
+ const OPAQUE_NODE_TYPES$2 = /* @__PURE__ */ new Set([
2091
+ "compound_statement",
2092
+ "lambda_expression",
2093
+ "friend_declaration"
2094
+ ]);
2095
+ const TYPEDEF = "type_definition";
2096
+ const TEMPLATE = "template_declaration";
2097
+ const FIELD_LIST = "field_declaration_list";
2098
+ const NAMESPACE = "namespace_definition";
2099
+ const ACCESS_SPECIFIER = "access_specifier";
2100
+ const PUBLIC_ACCESS = "public";
2101
+ const PRIVATE_ACCESS = "private";
2102
+ const STATIC = "static";
2103
+ const NAME_WRAPPERS = /* @__PURE__ */ new Set([
2104
+ "qualified_identifier",
2105
+ "destructor_name",
2106
+ "template_function"
2107
+ ]);
2108
+ const DECLARING_PARENTS = /* @__PURE__ */ new Set(["function_declarator", TYPEDEF]);
2109
+ const BARE_USE = { kind: IdentifierUseKind.Bare };
2110
+ const MACRO_NAME = /^[A-Z][A-Z\d_]*$/;
2111
+ const TEST_MACROS = /* @__PURE__ */ new Set([
2112
+ "TEST",
2113
+ "TEST_F",
2114
+ "TEST_P",
2115
+ "TYPED_TEST",
2116
+ "TYPED_TEST_P",
2117
+ "BOOST_AUTO_TEST_CASE",
2118
+ "BOOST_FIXTURE_TEST_CASE",
2119
+ "BOOST_DATA_TEST_CASE"
2120
+ ]);
2121
+ const TEMPLATE_TYPE = "template_type";
2122
+ const MAX_SPECIALIZATION_NAME = 60;
2123
+ const ELLIPSIS = "…";
2124
+ const IMPLICITLY_INVOKED$1 = /^(?:main$|operator\b|~)/;
2125
+ const IDENTIFIER_GRAMMAR$5 = {
2126
+ member: /* @__PURE__ */ new Map([["field_expression", ["field", "argument"]]]),
2127
+ path: /* @__PURE__ */ new Map([["qualified_identifier", ["name", "scope"]]]),
2128
+ nameIsUse: /* @__PURE__ */ new Set(),
2129
+ labels: /* @__PURE__ */ new Map(),
2130
+ bindings: /* @__PURE__ */ new Map([
2131
+ ["parameter_declaration", "declarator"],
2132
+ ["optional_parameter_declaration", "declarator"],
2133
+ ["declaration", "declarator"],
2134
+ ["init_declarator", "declarator"],
2135
+ ["pointer_declarator", "declarator"],
2136
+ ["array_declarator", "declarator"],
2137
+ ["reference_declarator", null],
2138
+ ["variadic_declarator", null],
2139
+ ["for_range_loop", "declarator"]
2140
+ ])
2141
+ };
2142
+ function describe$4(node, container) {
2143
+ switch (node.type) {
2144
+ case "function_definition": return describeFunctionDefinition(node, container);
2145
+ case "declaration":
2146
+ case "field_declaration": return describeDeclaration(node, container);
2147
+ case TYPEDEF: return describeTypedef(node);
2148
+ case "alias_declaration": return namedDefinition(node, UnitKind.TypeAlias);
2149
+ case NAMESPACE: return namedDefinition(node, UnitKind.Module);
2150
+ case "preproc_function_def": return namedDefinition(node, UnitKind.Macro);
2151
+ case "preproc_def": return node.childForFieldName("value") === null ? void 0 : namedDefinition(node, UnitKind.Macro);
2152
+ default: return describeSpecifier(node);
2153
+ }
2154
+ }
2155
+ function describeFunctionDefinition(node, container) {
2156
+ const declared = declaredName(node);
2157
+ const call = declared?.functionDeclarator;
2158
+ if (!(declared !== void 0 && call !== void 0 && node.childForFieldName("type") === null && MACRO_NAME.test(declared.name))) return describeFunction(declared, container);
2159
+ if (container !== void 0 && CLASS_KINDS.has(container.kind) && !isConstructorOf(container, declared.name)) return void 0;
2160
+ return {
2161
+ kind: TEST_MACROS.has(declared.name) ? UnitKind.Test : UnitKind.Function,
2162
+ name: squeeze(call.text),
2163
+ nameNode: declared.nameNode
2164
+ };
2165
+ }
2166
+ function isConstructorOf(container, name) {
2167
+ return container.childPrefix === name || container.childPrefix.endsWith(`::${name}`);
2168
+ }
2169
+ function describeFunction(declared, container) {
2170
+ if (declared === void 0) return void 0;
2171
+ const header = {
2172
+ kind: declared.owner !== void 0 || container !== void 0 && CLASS_KINDS.has(container.kind) ? UnitKind.Method : UnitKind.Function,
2173
+ name: declared.name,
2174
+ nameNode: declared.nameNode
2175
+ };
2176
+ return declared.owner === void 0 ? header : {
2177
+ ...header,
2178
+ owner: declared.owner
2179
+ };
2180
+ }
2181
+ function describeDeclaration(node, container) {
2182
+ const declared = declaredName(node);
2183
+ if (declared?.functionDeclarator !== void 0) return describeFunction(declared, container);
2184
+ const isFileScope = container === void 0 || container.kind === UnitKind.Module;
2185
+ const declaresOneVariable = node.type === "declaration" && node.childrenForFieldName("declarator").length === 1;
2186
+ return declared === void 0 || !isFileScope || !declaresOneVariable ? void 0 : {
2187
+ kind: UnitKind.Constant,
2188
+ name: declared.name,
2189
+ nameNode: declared.nameNode
2190
+ };
2191
+ }
2192
+ function describeTypedef(node) {
2193
+ const declared = declaredName(node);
2194
+ if (declared === void 0) return void 0;
2195
+ const type = node.childForFieldName("type");
2196
+ return {
2197
+ kind: (type?.childForFieldName("body") === null ? void 0 : KIND_BY_SPECIFIER.get(type?.type ?? "")) ?? UnitKind.TypeAlias,
2198
+ name: declared.name,
2199
+ nameNode: declared.nameNode
2200
+ };
2201
+ }
2202
+ function describeSpecifier(node) {
2203
+ const kind = KIND_BY_SPECIFIER.get(node.type);
2204
+ const nameNode = node.childForFieldName("name");
2205
+ const definesBody = node.childForFieldName("body") !== null;
2206
+ if (kind === void 0 || nameNode === null || !definesBody || node.parent?.type === TYPEDEF) return void 0;
2207
+ if (nameNode.type !== TEMPLATE_TYPE) return {
2208
+ kind,
2209
+ name: nameNode.text,
2210
+ nameNode
2211
+ };
2212
+ return {
2213
+ kind,
2214
+ name: specializationName(nameNode),
2215
+ nameNode: nameNode.childForFieldName("name") ?? nameNode
2216
+ };
2217
+ }
2218
+ function specializationName(type) {
2219
+ const template = type.childForFieldName("name")?.text ?? "";
2220
+ const kept = [];
2221
+ for (const argument of type.childForFieldName("arguments")?.namedChildren ?? []) {
2222
+ const text = squeeze(argument?.text ?? "");
2223
+ if (kept.length > 0 && `${template}<${[...kept, text].join(", ")}>`.length > MAX_SPECIALIZATION_NAME) {
2224
+ kept.push(ELLIPSIS);
2225
+ break;
2226
+ }
2227
+ kept.push(text);
2228
+ }
2229
+ return `${template}<${kept.join(", ")}>`;
2230
+ }
2231
+ function squeeze(text) {
2232
+ return text.replace(/\s+/g, " ");
2233
+ }
2234
+ function outerNode$2(node) {
2235
+ return node.parent?.type === TEMPLATE ? node.parent : node;
2236
+ }
2237
+ function isPublicDefinition(node, _name, container) {
2238
+ if (container !== void 0 && CLASS_KINDS.has(container.kind)) return memberAccess(node, container.kind) === PUBLIC_ACCESS;
2239
+ return !outerNode$2(node).namedChildren.some((child) => child?.type === "storage_class_specifier" && child.text === STATIC) && !isInAnonymousNamespace(node);
2240
+ }
2241
+ function memberAccess(node, containerKind) {
2242
+ for (let sibling = memberOfClass(node).previousNamedSibling; sibling !== null; sibling = sibling.previousNamedSibling) if (sibling.type === ACCESS_SPECIFIER) return sibling.text;
2243
+ return containerKind === UnitKind.Struct ? PUBLIC_ACCESS : PRIVATE_ACCESS;
2244
+ }
2245
+ function memberOfClass(node) {
2246
+ let member = node;
2247
+ while (member.parent !== null && member.parent.type !== FIELD_LIST) member = member.parent;
2248
+ return member;
2249
+ }
2250
+ function isInAnonymousNamespace(node) {
2251
+ for (let ancestor = node.parent; ancestor !== null; ancestor = ancestor.parent) if (ancestor.type === NAMESPACE && ancestor.childForFieldName("name") === null) return true;
2252
+ return false;
2253
+ }
2254
+ function classifyIdentifier(leaf) {
2255
+ if (declaresName(leaf)) return void 0;
2256
+ const parent = leaf.parent;
2257
+ if (parent !== null && KIND_BY_SPECIFIER.has(parent.type) && parent.childForFieldName("body") === null) return BARE_USE;
2258
+ return classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$5);
2259
+ }
2260
+ function declaresName(leaf) {
2261
+ let name = leaf;
2262
+ while (name.parent !== null && NAME_WRAPPERS.has(name.parent.type) && name.parent.childForFieldName("scope")?.id !== name.id) name = name.parent;
2263
+ const parent = name.parent;
2264
+ return parent !== null && DECLARING_PARENTS.has(parent.type) && parent.childForFieldName("declarator")?.id === name.id;
2265
+ }
2266
+ function parameterKind$4(parameter) {
2267
+ if (parameter.type === "variadic_parameter" || parameter.type === "variadic_parameter_declaration") return ParameterKind.Rest;
2268
+ return parameter.type === "optional_parameter_declaration" ? ParameterKind.Optional : ParameterKind.Required;
2269
+ }
2270
+ function makeSpec$1(language, grammar) {
2271
+ return {
2272
+ language,
2273
+ grammar,
2274
+ separator: "::",
2275
+ describe: describe$4,
2276
+ outerNode: outerNode$2,
2277
+ isAttachedPrefix: () => false,
2278
+ isContainer: (kind) => CONTAINERS$5.has(kind),
2279
+ isOpaque: (node) => OPAQUE_NODE_TYPES$2.has(node.type),
2280
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2281
+ normalizeLeaf: (leaf) => leaf.text,
2282
+ publicDefinitions: () => isPublicDefinition,
2283
+ identifierTypes: /* @__PURE__ */ new Set([
2284
+ "identifier",
2285
+ "field_identifier",
2286
+ "type_identifier",
2287
+ "namespace_identifier"
2288
+ ]),
2289
+ classifyIdentifier,
2290
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2291
+ callsMembersByBareName: true,
2292
+ functionScopeTypes: /* @__PURE__ */ new Set(["function_definition", "lambda_expression"]),
2293
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$5),
2294
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$1.test(methodName),
2295
+ shape: {
2296
+ functionNode: (definition) => definition,
2297
+ signatureNode: (fn) => declaredName(fn)?.functionDeclarator ?? fn,
2298
+ returnTypeField: "type",
2299
+ parameterKind: parameterKind$4,
2300
+ calls: /* @__PURE__ */ new Map([["call_expression", {
2301
+ calleeField: "function",
2302
+ suffix: ""
2303
+ }], ["new_expression", {
2304
+ calleeField: "type",
2305
+ suffix: ""
2306
+ }]]),
2307
+ errorCalls: /* @__PURE__ */ new Set([
2308
+ "exit",
2309
+ "abort",
2310
+ "_Exit",
2311
+ "quick_exit",
2312
+ "std::exit",
2313
+ "std::abort",
2314
+ "std::terminate",
2315
+ "std::quick_exit"
2316
+ ]),
2317
+ errorTypes: ["throw_statement"],
2318
+ branchTypes: [
2319
+ "if_statement",
2320
+ "for_statement",
2321
+ "for_range_loop",
2322
+ "while_statement",
2323
+ "do_statement",
2324
+ "case_statement",
2325
+ "conditional_expression",
2326
+ "catch_clause"
2327
+ ],
2328
+ nestingTypes: [
2329
+ "if_statement",
2330
+ "for_statement",
2331
+ "for_range_loop",
2332
+ "while_statement",
2333
+ "do_statement",
2334
+ "switch_statement",
2335
+ "try_statement"
2336
+ ],
2337
+ logicalTypes: ["binary_expression"],
2338
+ logicalOperators: /* @__PURE__ */ new Set([
2339
+ "&&",
2340
+ "||",
2341
+ "and",
2342
+ "or"
2343
+ ])
2344
+ }
2345
+ };
2346
+ }
2347
+ const cSpec = makeSpec$1(SourceLanguage.C, "tree-sitter-c/tree-sitter-c.wasm");
2348
+ const cppSpec = makeSpec$1(SourceLanguage.Cpp, "tree-sitter-cpp/tree-sitter-cpp.wasm");
2349
+ // packages/engine/src/syntax/go.ts
2350
+ const KIND_BY_TYPE_NODE = /* @__PURE__ */ new Map([["struct_type", UnitKind.Struct], ["interface_type", UnitKind.Interface]]);
2351
+ const GROUPED_DECLARATIONS = /* @__PURE__ */ new Set([
2352
+ "type_declaration",
2353
+ "const_declaration",
2354
+ "var_declaration"
2355
+ ]);
2356
+ const VALUE_SPECS = /* @__PURE__ */ new Set(["const_spec", "var_spec"]);
2357
+ const CONTAINERS$4 = /* @__PURE__ */ new Set([UnitKind.Interface]);
2358
+ const PROGRAM_PACKAGE = "main";
2359
+ const EXPORTED_NAME = /^\p{Lu}/u;
2360
+ const IDENTIFIER_GRAMMAR$4 = {
2361
+ member: /* @__PURE__ */ new Map([["selector_expression", ["field", "operand"]]]),
2362
+ path: /* @__PURE__ */ new Map([["qualified_type", ["name", "package"]]]),
2363
+ nameIsUse: /* @__PURE__ */ new Set(),
2364
+ labels: /* @__PURE__ */ new Map([["keyed_element", "key"]]),
2365
+ bindings: /* @__PURE__ */ new Map([
2366
+ ["parameter_declaration", "name"],
2367
+ ["variadic_parameter_declaration", "name"],
2368
+ ["var_spec", "name"],
2369
+ ["const_spec", "name"]
2370
+ ])
2371
+ };
2372
+ function describe$3(node, container) {
2373
+ switch (node.type) {
2374
+ case "function_declaration": return namedDefinition(node, UnitKind.Function);
2375
+ case "method_declaration": return describeMethod(node);
2376
+ case "method_elem": return container?.kind === UnitKind.Interface ? namedDefinition(node, UnitKind.Method) : void 0;
2377
+ case "type_spec": return namedDefinition(node, KIND_BY_TYPE_NODE.get(node.childForFieldName("type")?.type ?? "") ?? UnitKind.TypeAlias);
2378
+ case "type_alias": return namedDefinition(node, UnitKind.TypeAlias);
2379
+ default: return VALUE_SPECS.has(node.type) && container === void 0 ? describeValue(node) : void 0;
2380
+ }
2381
+ }
2382
+ function describeMethod(node) {
2383
+ const header = namedDefinition(node, UnitKind.Method);
2384
+ const receiverType = node.childForFieldName("receiver")?.namedChildren.at(0)?.childForFieldName("type");
2385
+ const owner = receiverType === null || receiverType === void 0 ? void 0 : typeName(receiverType);
2386
+ return header === void 0 || owner === void 0 ? header : {
2387
+ ...header,
2388
+ owner
2389
+ };
2390
+ }
2391
+ function typeName(type) {
2392
+ if (type.type === "type_identifier") return type.text;
2393
+ const inner = type.type === "pointer_type" ? type.namedChildren.at(0) : type.type === "generic_type" ? type.childForFieldName("type") : void 0;
2394
+ return inner === null || inner === void 0 ? void 0 : typeName(inner);
2395
+ }
2396
+ function describeValue(spec) {
2397
+ const names = spec.childrenForFieldName("name");
2398
+ const nameNode = names.at(0);
2399
+ if (names.length !== 1 || nameNode === null || nameNode === void 0) return void 0;
2400
+ return {
2401
+ kind: (spec.childForFieldName("value")?.namedChildren.at(0))?.type === "func_literal" ? UnitKind.Function : UnitKind.Constant,
2402
+ name: nameNode.text,
2403
+ nameNode
2404
+ };
2405
+ }
2406
+ function outerNode$1(node) {
2407
+ const parent = node.parent;
2408
+ return parent !== null && GROUPED_DECLARATIONS.has(parent.type) && parent.namedChildren.filter((child) => child?.type !== "comment").length === 1 ? parent : node;
2409
+ }
2410
+ function publicDefinitions$1(root) {
2411
+ if (root.namedChildren.find((child) => child?.type === "package_clause")?.namedChildren.at(0)?.text === PROGRAM_PACKAGE) return () => false;
2412
+ return (node, name) => {
2413
+ const owner = node.type === "method_declaration" ? describeMethod(node)?.owner : void 0;
2414
+ return EXPORTED_NAME.test(name) && (owner === void 0 || EXPORTED_NAME.test(owner));
2415
+ };
2416
+ }
2417
+ function parameterKind$3(parameter) {
2418
+ return parameter.type === "variadic_parameter_declaration" ? ParameterKind.Rest : ParameterKind.Required;
2419
+ }
2420
+ const goSpec = {
2421
+ language: SourceLanguage.Go,
2422
+ grammar: "tree-sitter-go/tree-sitter-go.wasm",
2423
+ separator: ".",
2424
+ describe: describe$3,
2425
+ outerNode: outerNode$1,
2426
+ isAttachedPrefix: () => false,
2427
+ isContainer: (kind) => CONTAINERS$4.has(kind),
2428
+ isOpaque: (node) => node.type === "func_literal" || node.type === "block",
2429
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2430
+ normalizeLeaf: (leaf) => leaf.text,
2431
+ publicDefinitions: publicDefinitions$1,
2432
+ identifierTypes: /* @__PURE__ */ new Set([
2433
+ "identifier",
2434
+ "field_identifier",
2435
+ "type_identifier"
2436
+ ]),
2437
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2438
+ selfReceivers: /* @__PURE__ */ new Set(),
2439
+ callsMembersByBareName: false,
2440
+ functionScopeTypes: /* @__PURE__ */ new Set([
2441
+ "function_declaration",
2442
+ "method_declaration",
2443
+ "func_literal"
2444
+ ]),
2445
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2446
+ isImplicitlyInvoked: () => false,
2447
+ shape: {
2448
+ functionNode: (definition) => definition,
2449
+ signatureNode: (fn) => fn,
2450
+ returnTypeField: "result",
2451
+ parameterKind: parameterKind$3,
2452
+ calls: /* @__PURE__ */ new Map([["call_expression", {
2453
+ calleeField: "function",
2454
+ suffix: ""
2455
+ }]]),
2456
+ errorCalls: /* @__PURE__ */ new Set([
2457
+ "panic",
2458
+ "log.Fatal",
2459
+ "log.Fatalf",
2460
+ "log.Fatalln",
2461
+ "log.Panic",
2462
+ "log.Panicf",
2463
+ "os.Exit"
2464
+ ]),
2465
+ errorTypes: [],
2466
+ branchTypes: [
2467
+ "if_statement",
2468
+ "for_statement",
2469
+ "expression_case",
2470
+ "type_case",
2471
+ "communication_case"
2472
+ ],
2473
+ nestingTypes: [
2474
+ "if_statement",
2475
+ "for_statement",
2476
+ "expression_switch_statement",
2477
+ "type_switch_statement",
2478
+ "select_statement"
2479
+ ],
2480
+ logicalTypes: ["binary_expression"],
2481
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2482
+ }
2483
+ };
2484
+ // packages/engine/src/syntax/java.ts
2485
+ const KIND_BY_NODE_TYPE$2 = /* @__PURE__ */ new Map([
2486
+ ["class_declaration", UnitKind.Class],
2487
+ ["record_declaration", UnitKind.Class],
2488
+ ["interface_declaration", UnitKind.Interface],
2489
+ ["annotation_type_declaration", UnitKind.Interface],
2490
+ ["enum_declaration", UnitKind.Enum],
2491
+ ["method_declaration", UnitKind.Method],
2492
+ ["constructor_declaration", UnitKind.Method],
2493
+ ["compact_constructor_declaration", UnitKind.Method],
2494
+ ["annotation_type_element_declaration", UnitKind.Method]
2495
+ ]);
2496
+ const CONTAINERS$3 = /* @__PURE__ */ new Set([
2497
+ UnitKind.Class,
2498
+ UnitKind.Interface,
2499
+ UnitKind.Enum
2500
+ ]);
2501
+ const OPAQUE_NODE_TYPES$1 = /* @__PURE__ */ new Set([
2502
+ "object_creation_expression",
2503
+ "lambda_expression",
2504
+ "enum_constant",
2505
+ "block"
2506
+ ]);
2507
+ const PUBLIC_MODIFIER = "public";
2508
+ const PRIVATE_MODIFIER = "private";
2509
+ const IMPLICITLY_PUBLIC_CONTAINERS = /* @__PURE__ */ new Set([UnitKind.Interface]);
2510
+ const IMPLICITLY_INVOKED = /* @__PURE__ */ new Set([
2511
+ "toString",
2512
+ "equals",
2513
+ "hashCode",
2514
+ "close",
2515
+ "compareTo",
2516
+ "main",
2517
+ "finalize"
2518
+ ]);
2519
+ const IDENTIFIER_GRAMMAR$3 = {
2520
+ member: /* @__PURE__ */ new Map([
2521
+ ["method_invocation", ["name", "object"]],
2522
+ ["field_access", ["field", "object"]],
2523
+ ["method_reference", ["name", "object"]]
2524
+ ]),
2525
+ path: /* @__PURE__ */ new Map([["scoped_type_identifier", ["name", "scope"]], ["scoped_identifier", ["name", "scope"]]]),
2526
+ nameIsUse: /* @__PURE__ */ new Set(),
2527
+ labels: /* @__PURE__ */ new Map([["element_value_pair", "key"]]),
2528
+ bindings: /* @__PURE__ */ new Map([
2529
+ ["formal_parameter", "name"],
2530
+ ["variable_declarator", "name"],
2531
+ ["catch_formal_parameter", "name"],
2532
+ ["enhanced_for_statement", "name"],
2533
+ ["inferred_parameters", null],
2534
+ ["lambda_expression", "parameters"]
2535
+ ])
2536
+ };
2537
+ function describe$2(node) {
2538
+ const kind = KIND_BY_NODE_TYPE$2.get(node.type);
2539
+ return kind === void 0 ? void 0 : namedDefinition(node, kind);
2540
+ }
2541
+ function modifierWords(node) {
2542
+ const modifiers = node.namedChildren.find((child) => child?.type === "modifiers");
2543
+ return new Set(modifiers?.children.filter((child) => child !== null && !child.isNamed).map((child) => child?.text ?? "") ?? []);
2544
+ }
2545
+ function isPublicMember$1(node, _name, container) {
2546
+ const words = modifierWords(node);
2547
+ if (container !== void 0 && IMPLICITLY_PUBLIC_CONTAINERS.has(container.kind)) return !words.has(PRIVATE_MODIFIER);
2548
+ return words.has(PUBLIC_MODIFIER);
2549
+ }
2550
+ function parameterKind$2(parameter) {
2551
+ if (parameter.type === "spread_parameter") return ParameterKind.Rest;
2552
+ return parameter.type === "receiver_parameter" ? ParameterKind.Receiver : ParameterKind.Required;
2553
+ }
2554
+ const javaSpec = {
2555
+ language: SourceLanguage.Java,
2556
+ grammar: "tree-sitter-java/tree-sitter-java.wasm",
2557
+ separator: ".",
2558
+ describe: describe$2,
2559
+ outerNode: (node) => node,
2560
+ isAttachedPrefix: () => false,
2561
+ isContainer: (kind) => CONTAINERS$3.has(kind),
2562
+ isOpaque: (node) => OPAQUE_NODE_TYPES$1.has(node.type),
2563
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2564
+ normalizeLeaf: (leaf) => leaf.text,
2565
+ publicDefinitions: () => isPublicMember$1,
2566
+ identifierTypes: /* @__PURE__ */ new Set(["identifier", "type_identifier"]),
2567
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2568
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2569
+ callsMembersByBareName: true,
2570
+ functionScopeTypes: /* @__PURE__ */ new Set([
2571
+ "method_declaration",
2572
+ "constructor_declaration",
2573
+ "compact_constructor_declaration",
2574
+ "lambda_expression"
2575
+ ]),
2576
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2577
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED.has(methodName),
2578
+ shape: {
2579
+ functionNode: (definition) => definition,
2580
+ signatureNode: (fn) => fn,
2581
+ returnTypeField: "type",
2582
+ parameterKind: parameterKind$2,
2583
+ calls: /* @__PURE__ */ new Map([["method_invocation", {
2584
+ calleeField: "name",
2585
+ suffix: ""
2586
+ }], ["object_creation_expression", {
2587
+ calleeField: "type",
2588
+ suffix: ""
2589
+ }]]),
2590
+ errorCalls: /* @__PURE__ */ new Set(),
2591
+ errorTypes: ["throw_statement"],
2592
+ branchTypes: [
2593
+ "if_statement",
2594
+ "for_statement",
2595
+ "enhanced_for_statement",
2596
+ "while_statement",
2597
+ "do_statement",
2598
+ "switch_label",
2599
+ "catch_clause",
2600
+ "ternary_expression"
2601
+ ],
2602
+ nestingTypes: [
2603
+ "if_statement",
2604
+ "for_statement",
2605
+ "enhanced_for_statement",
2606
+ "while_statement",
2607
+ "do_statement",
2608
+ "switch_expression",
2609
+ "try_statement",
2610
+ "try_with_resources_statement"
2611
+ ],
2612
+ logicalTypes: ["binary_expression"],
2613
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2614
+ }
2615
+ };
1964
2616
  // packages/engine/src/syntax/python.ts
1965
2617
  const CONTAINERS$2 = /* @__PURE__ */ new Set([UnitKind.Class]);
1966
2618
  const IDENTIFIER_GRAMMAR$2 = {
@@ -2015,11 +2667,14 @@ const pythonSpec = {
2015
2667
  identifierTypes: /* @__PURE__ */ new Set(["identifier"]),
2016
2668
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$2),
2017
2669
  selfReceivers: /* @__PURE__ */ new Set(["self", "cls"]),
2670
+ callsMembersByBareName: false,
2018
2671
  functionScopeTypes: /* @__PURE__ */ new Set(["function_definition", "lambda"]),
2019
2672
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$2),
2020
2673
  isImplicitlyInvoked: (methodName) => DUNDER_METHOD.test(methodName),
2021
2674
  shape: {
2022
2675
  functionNode: (definition) => definition,
2676
+ signatureNode: (fn) => fn,
2677
+ returnTypeField: "return_type",
2023
2678
  parameterKind: parameterKind$1,
2024
2679
  calls: /* @__PURE__ */ new Map([["call", {
2025
2680
  calleeField: "function",
@@ -2107,11 +2762,14 @@ const rustSpec = {
2107
2762
  ]),
2108
2763
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$1),
2109
2764
  selfReceivers: /* @__PURE__ */ new Set(["self", "Self"]),
2765
+ callsMembersByBareName: false,
2110
2766
  functionScopeTypes: /* @__PURE__ */ new Set(["function_item", "closure_expression"]),
2111
2767
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$1),
2112
2768
  isImplicitlyInvoked: (methodName) => methodName === "drop",
2113
2769
  shape: {
2114
2770
  functionNode: (definition) => definition,
2771
+ signatureNode: (fn) => fn,
2772
+ returnTypeField: "return_type",
2115
2773
  parameterKind: (parameter) => parameter.type === "self_parameter" ? ParameterKind.Receiver : parameter.type === "variadic_parameter" ? ParameterKind.Rest : ParameterKind.Required,
2116
2774
  calls: /* @__PURE__ */ new Map([["call_expression", {
2117
2775
  calleeField: "function",
@@ -2161,6 +2819,102 @@ function describeImpl(node) {
2161
2819
  nameNode: null
2162
2820
  };
2163
2821
  }
2822
+ // packages/engine/src/syntax/testCalls.ts
2823
+ const KIND_BY_WORD = /* @__PURE__ */ new Map([
2824
+ ["describe", UnitKind.TestSuite],
2825
+ ["suite", UnitKind.TestSuite],
2826
+ ["context", UnitKind.TestSuite],
2827
+ ["fdescribe", UnitKind.TestSuite],
2828
+ ["xdescribe", UnitKind.TestSuite],
2829
+ ["it", UnitKind.Test],
2830
+ ["test", UnitKind.Test],
2831
+ ["specify", UnitKind.Test],
2832
+ ["fit", UnitKind.Test],
2833
+ ["xit", UnitKind.Test],
2834
+ ["beforeEach", UnitKind.TestHook],
2835
+ ["afterEach", UnitKind.TestHook],
2836
+ ["beforeAll", UnitKind.TestHook],
2837
+ ["afterAll", UnitKind.TestHook],
2838
+ ["before", UnitKind.TestHook],
2839
+ ["after", UnitKind.TestHook]
2840
+ ]);
2841
+ const MODIFIERS = /* @__PURE__ */ new Set([
2842
+ "only",
2843
+ "skip",
2844
+ "todo",
2845
+ "concurrent",
2846
+ "sequential",
2847
+ "fails",
2848
+ "each",
2849
+ "skipIf",
2850
+ "runIf",
2851
+ "serial",
2852
+ "parallel",
2853
+ "fixme"
2854
+ ]);
2855
+ const CALLBACK_TYPES = /* @__PURE__ */ new Set(["arrow_function", "function_expression"]);
2856
+ const TITLE_TYPES = /* @__PURE__ */ new Set(["string", "template_string"]);
2857
+ /** A statement such as `describe("parser", () => {…})`, as a unit. */
2858
+ function describeTestStatement(statement) {
2859
+ const call = statement.type === "expression_statement" ? testCall(statement.namedChildren.at(0) ?? null) : void 0;
2860
+ if (call === void 0) return void 0;
2861
+ if (call.kind === UnitKind.TestHook || call.title === void 0) return {
2862
+ kind: call.kind,
2863
+ name: call.words.join("."),
2864
+ nameNode: null
2865
+ };
2866
+ return {
2867
+ kind: call.kind,
2868
+ name: titleText(call.title),
2869
+ nameNode: titleNameNode(call.title)
2870
+ };
2871
+ }
2872
+ /**
2873
+ * Whether a node the walker would otherwise skip leads into a suite's callback, where its tests
2874
+ * are: the suite's call, the callback passed to it, and the callback's body.
2875
+ */
2876
+ function leadsIntoTestSuite(node) {
2877
+ if (node.type === "call_expression") return testCall(node)?.kind === UnitKind.TestSuite;
2878
+ if (CALLBACK_TYPES.has(node.type)) return isSuiteCallback(node);
2879
+ const parent = node.parent;
2880
+ return node.type === "statement_block" && parent !== null && CALLBACK_TYPES.has(parent.type) && isSuiteCallback(parent);
2881
+ }
2882
+ function isSuiteCallback(callback) {
2883
+ const call = callback.parent?.parent ?? null;
2884
+ return callback.parent?.type === "arguments" && testCall(call)?.callback.id === callback.id && testCall(call)?.kind === UnitKind.TestSuite;
2885
+ }
2886
+ function testCall(node) {
2887
+ if (node?.type !== "call_expression") return void 0;
2888
+ const words = calleeWords(node.childForFieldName("function"));
2889
+ const kind = KIND_BY_WORD.get(words.at(-1) ?? "");
2890
+ if (kind === void 0 || !KIND_BY_WORD.has(words.at(0) ?? "")) return void 0;
2891
+ const args = node.childForFieldName("arguments")?.namedChildren.filter((arg) => arg !== null) ?? [];
2892
+ const callback = args.find((arg) => CALLBACK_TYPES.has(arg.type));
2893
+ if (callback === void 0) return void 0;
2894
+ const first = args.at(0);
2895
+ return {
2896
+ kind,
2897
+ words,
2898
+ title: first === void 0 || first.id === callback.id ? void 0 : first,
2899
+ callback
2900
+ };
2901
+ }
2902
+ function calleeWords(callee) {
2903
+ if (callee === null) return [];
2904
+ if (callee.type === "identifier") return [callee.text];
2905
+ if (callee.type === "call_expression") return calleeWords(callee.childForFieldName("function"));
2906
+ if (callee.type !== "member_expression") return [];
2907
+ const property = callee.childForFieldName("property")?.text ?? "";
2908
+ const object = calleeWords(callee.childForFieldName("object"));
2909
+ return MODIFIERS.has(property) ? object : [...object, property];
2910
+ }
2911
+ function titleText(title) {
2912
+ return TITLE_TYPES.has(title.type) ? title.text.slice(1, -1) : title.text;
2913
+ }
2914
+ function titleNameNode(title) {
2915
+ const fragments = title.namedChildren.filter((child) => child?.type === "string_fragment");
2916
+ return fragments.length === 1 ? fragments.at(0) ?? null : null;
2917
+ }
2164
2918
  // packages/engine/src/syntax/typescript.ts
2165
2919
  const KIND_BY_NODE_TYPE = /* @__PURE__ */ new Map([
2166
2920
  ["function_declaration", UnitKind.Function],
@@ -2186,7 +2940,11 @@ const MODULE_LEVEL_PARENTS = /* @__PURE__ */ new Set([
2186
2940
  "export_statement",
2187
2941
  "statement_block"
2188
2942
  ]);
2189
- const CONTAINERS = /* @__PURE__ */ new Set([UnitKind.Class, UnitKind.Module]);
2943
+ const CONTAINERS = /* @__PURE__ */ new Set([
2944
+ UnitKind.Class,
2945
+ UnitKind.Module,
2946
+ UnitKind.TestSuite
2947
+ ]);
2190
2948
  const OPAQUE_NODE_TYPES = /* @__PURE__ */ new Set([
2191
2949
  "call_expression",
2192
2950
  "arrow_function",
@@ -2216,6 +2974,7 @@ const FUNCTION_SCOPE_TYPES = /* @__PURE__ */ new Set([
2216
2974
  "method_definition"
2217
2975
  ]);
2218
2976
  function describe$1(node, container) {
2977
+ if (node.type === "expression_statement") return describeTestStatement(node);
2219
2978
  if (node.type === "variable_declarator") return describeVariable(node, container);
2220
2979
  if (node.type === "public_field_definition") {
2221
2980
  const value = node.childForFieldName("value");
@@ -2250,6 +3009,7 @@ const EXPORT_BOUNDARIES = /* @__PURE__ */ new Set(["program", "statement_block"]
2250
3009
  function publicDefinitions(root) {
2251
3010
  const exported = locallyExportedNames(root);
2252
3011
  return (node, name, container) => {
3012
+ if (node.type === "expression_statement") return false;
2253
3013
  if (container?.kind === UnitKind.Class) return isPublicMember(node);
2254
3014
  return isInsideExportStatement(node) || container === void 0 && exported.has(name);
2255
3015
  };
@@ -2290,7 +3050,7 @@ function makeSpec(language, grammar) {
2290
3050
  outerNode,
2291
3051
  isAttachedPrefix: (node) => node.type === "decorator",
2292
3052
  isContainer: (kind) => CONTAINERS.has(kind),
2293
- isOpaque: (node) => OPAQUE_NODE_TYPES.has(node.type) && node.parent?.type !== "internal_module",
3053
+ isOpaque: (node) => OPAQUE_NODE_TYPES.has(node.type) && node.parent?.type !== "internal_module" && !leadsIntoTestSuite(node),
2294
3054
  childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2295
3055
  normalizeLeaf: (leaf) => STRING_DELIMITERS.has(leaf.type) && leaf.parent?.type === "string" ? "\"" : leaf.text,
2296
3056
  publicDefinitions,
@@ -2302,11 +3062,14 @@ function makeSpec(language, grammar) {
2302
3062
  ]),
2303
3063
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR),
2304
3064
  selfReceivers: /* @__PURE__ */ new Set(["this"]),
3065
+ callsMembersByBareName: false,
2305
3066
  functionScopeTypes: FUNCTION_SCOPE_TYPES,
2306
3067
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR),
2307
3068
  isImplicitlyInvoked: (methodName) => methodName === "constructor",
2308
3069
  shape: {
2309
3070
  functionNode: (definition) => definition.childForFieldName("value") ?? definition,
3071
+ signatureNode: (fn) => fn,
3072
+ returnTypeField: "return_type",
2310
3073
  parameterKind,
2311
3074
  calls: /* @__PURE__ */ new Map([["call_expression", {
2312
3075
  calleeField: "function",
@@ -2359,16 +3122,31 @@ const SPEC_BY_EXTENSION = /* @__PURE__ */ new Map([
2359
3122
  [".cjs", tsxSpec],
2360
3123
  [".jsx", tsxSpec],
2361
3124
  [".py", pythonSpec],
2362
- [".pyi", pythonSpec]
3125
+ [".pyi", pythonSpec],
3126
+ [".go", goSpec],
3127
+ [".java", javaSpec],
3128
+ [".c", cSpec],
3129
+ [".h", cppSpec],
3130
+ [".cc", cppSpec],
3131
+ [".cpp", cppSpec],
3132
+ [".cxx", cppSpec],
3133
+ [".c++", cppSpec],
3134
+ [".hh", cppSpec],
3135
+ [".hpp", cppSpec],
3136
+ [".hxx", cppSpec],
3137
+ [".h++", cppSpec],
3138
+ [".inl", cppSpec],
3139
+ [".ipp", cppSpec],
3140
+ [".tpp", cppSpec]
2363
3141
  ]);
2364
3142
  function languageSpecFor(path) {
2365
3143
  return SPEC_BY_EXTENSION.get(extname(path).toLowerCase());
2366
3144
  }
2367
3145
  [...SPEC_BY_EXTENSION.keys()];
2368
- const ECMASCRIPT_LANGUAGES = /* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]);
3146
+ const LANGUAGE_FAMILIES = [/* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]), /* @__PURE__ */ new Set([SourceLanguage.C, SourceLanguage.Cpp])];
2369
3147
  /** Whether code in one language can refer to units defined in the other. */
2370
3148
  function canReferenceAcross(a, b) {
2371
- return a === b || ECMASCRIPT_LANGUAGES.has(a) && ECMASCRIPT_LANGUAGES.has(b);
3149
+ return a === b || LANGUAGE_FAMILIES.some((family) => family.has(a) && family.has(b));
2372
3150
  }
2373
3151
  // packages/engine/src/syntax/parser.ts
2374
3152
  const require = createRequire(import.meta.url);
@@ -2545,10 +3323,10 @@ async function listSourceFiles(repoDir, commit) {
2545
3323
  }
2546
3324
  /** Matches any of `names` where it is a whole identifier, not part of a longer one. */
2547
3325
  function wordMatcher(names) {
2548
- const alternatives = [...names].sort((a, b) => b.length - a.length).map(escapeRegExp);
3326
+ const alternatives = [...names].sort((a, b) => b.length - a.length).map(escapeRegExp$1);
2549
3327
  return new RegExp(`(?<!${IDENTIFIER_CHAR})(?:${alternatives.join("|")})(?!${IDENTIFIER_CHAR})`, "gu");
2550
3328
  }
2551
- function escapeRegExp(text) {
3329
+ function escapeRegExp$1(text) {
2552
3330
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2553
3331
  }
2554
3332
  // packages/engine/src/impact/identifierUses.ts
@@ -2714,6 +3492,7 @@ function targetsIn(file) {
2714
3492
  spec: file.spec,
2715
3493
  searchedName,
2716
3494
  container: unit.kind === UnitKind.Method ? containerTypeName(unit.qualifiedName, file.spec.separator) : void 0,
3495
+ containerArguments: unit.kind === UnitKind.Method ? templateArguments(containerPath(unit.qualifiedName, file.spec.separator) ?? "") : void 0,
2717
3496
  ownLines: after === void 0 ? void 0 : {
2718
3497
  first: after.startLine,
2719
3498
  last: after.endLine
@@ -2785,13 +3564,27 @@ function referenceConfidence(use, target, caller, spec) {
2785
3564
  case IdentifierUseKind.Member: {
2786
3565
  const qualifier = use.kind === IdentifierUseKind.Path ? use.qualifier : use.receiver;
2787
3566
  if (container === void 0) return use.kind === IdentifierUseKind.Path && qualifiesModuleOf(use.qualifier, target.path) ? ReferenceConfidence.Likely : ReferenceConfidence.Possible;
2788
- if (simpleTypeName(qualifier) === container) return ReferenceConfidence.Exact;
2789
- if (spec.selfReceivers.has(qualifier)) return (caller === void 0 ? void 0 : containerTypeName(caller.qualifiedName, spec.separator)) === container ? ReferenceConfidence.Exact : void 0;
3567
+ if (simpleTypeName(qualifier) === container) return isOtherSpecialization(qualifier, target) ? ReferenceConfidence.Possible : ReferenceConfidence.Exact;
3568
+ if (spec.selfReceivers.has(qualifier)) return isCalledFromItsContainer(caller, target, spec) ? ReferenceConfidence.Exact : void 0;
2790
3569
  return use.kind === IdentifierUseKind.Path ? void 0 : ReferenceConfidence.Possible;
2791
3570
  }
2792
- case IdentifierUseKind.Bare: return container === void 0 ? ReferenceConfidence.Likely : void 0;
3571
+ case IdentifierUseKind.Bare:
3572
+ if (container === void 0) return ReferenceConfidence.Likely;
3573
+ return spec.callsMembersByBareName && isCalledFromItsContainer(caller, target, spec) ? ReferenceConfidence.Likely : void 0;
2793
3574
  }
2794
3575
  }
3576
+ function isCalledFromItsContainer(caller, target, spec) {
3577
+ const callerContainer = caller === void 0 ? void 0 : containerPath(caller.qualifiedName, spec.separator);
3578
+ return callerContainer !== void 0 && simpleTypeName(callerContainer) === target.container && !isOtherSpecialization(callerContainer, target);
3579
+ }
3580
+ function isOtherSpecialization(path, target) {
3581
+ const pathArguments = templateArguments(path);
3582
+ return pathArguments !== void 0 && target.containerArguments !== void 0 && pathArguments !== target.containerArguments;
3583
+ }
3584
+ function templateArguments(path) {
3585
+ return TRAILING_TEMPLATE_ARGUMENTS.exec(path)?.[0].replace(/\s+/g, "");
3586
+ }
3587
+ const TRAILING_TEMPLATE_ARGUMENTS = /<.*>$/;
2795
3588
  const RELATIVE_PATH_ROOTS = /* @__PURE__ */ new Set([
2796
3589
  "crate",
2797
3590
  "self",
@@ -2847,8 +3640,12 @@ function byReviewPriority(a, b) {
2847
3640
  }
2848
3641
  /** `Size::new` → `Size`; `<Size as fmt::Display>::fmt` → `Size`; `Parser.parse` → `Parser`. */
2849
3642
  function containerTypeName(qualifiedName, separator) {
3643
+ const path = containerPath(qualifiedName, separator);
3644
+ return path === void 0 ? void 0 : simpleTypeName(path);
3645
+ }
3646
+ function containerPath(qualifiedName, separator) {
2850
3647
  const cut = qualifiedName.lastIndexOf(separator);
2851
- return cut === -1 ? void 0 : simpleTypeName(qualifiedName.slice(0, cut));
3648
+ return cut === -1 ? void 0 : qualifiedName.slice(0, cut);
2852
3649
  }
2853
3650
  /** Reduces a type path to its bare name: `<Foo as Trait>`, `crate::a::Foo<T>` → `Foo`. */
2854
3651
  function simpleTypeName(path) {
@@ -2860,7 +3657,7 @@ const TEST_PATHS = [
2860
3657
  /(^|\/)(tests?|__tests__|spec|specs)\//,
2861
3658
  /\.(test|spec)\.[cm]?[jt]sx?$/,
2862
3659
  /(^|\/)test_[^/]*\.py$/,
2863
- /_test\.(py|rs)$/,
3660
+ /_test\.(py|rs|go|c|cc|cpp|cxx)$/,
2864
3661
  /(^|\/)tests?\.rs$/
2865
3662
  ];
2866
3663
  const TEST_UNIT = /(^|::|\.)tests?(::|\.)|(^|::|\.)test_|^Test/;
@@ -2891,7 +3688,7 @@ async function mentionsInCode(repoDir, head, names) {
2891
3688
  return new Map(specific.map(([name, files]) => [name, files.flatMap((path) => mentionsIn(path, linesByPath.get(path) ?? [], name))]));
2892
3689
  }
2893
3690
  function mentionsIn(path, lines, name) {
2894
- const word = new RegExp(`(?<![\\p{L}\\p{N}_$])${escapeRegExp(name)}(?![\\p{L}\\p{N}_$])`, "u");
3691
+ const word = new RegExp(`(?<![\\p{L}\\p{N}_$])${escapeRegExp$1(name)}(?![\\p{L}\\p{N}_$])`, "u");
2895
3692
  return lines.flatMap((text, index) => word.test(text) && !COMMENT_LINE$1.test(text) ? [{
2896
3693
  path,
2897
3694
  line: index + 1,
@@ -3002,7 +3799,7 @@ function keyOf$1(pattern, line) {
3002
3799
  };
3003
3800
  }
3004
3801
  function isStillInFile(file, key) {
3005
- return new RegExp(`(?<![\\w-])${escapeRegExp(key)}(?![\\w-])`).test(file.after ?? "");
3802
+ return new RegExp(`(?<![\\w-])${escapeRegExp$1(key)}(?![\\w-])`).test(file.after ?? "");
3006
3803
  }
3007
3804
  const NAME_WORD = /[_-]|(?<=[a-z])(?=[A-Z])/;
3008
3805
  function endsInTheSameWord(a, b) {
@@ -3107,7 +3904,7 @@ function isRequiredRead(mention) {
3107
3904
  return READS_ENVIRONMENT.test(mention.text) && !READ_HAS_DEFAULT.test(mention.text);
3108
3905
  }
3109
3906
  function looksLikeKeyRead(mention, key) {
3110
- return new RegExp(`["'\`.]${escapeRegExp(key)}\\b`).test(mention.text);
3907
+ return new RegExp(`["'\`.]${escapeRegExp$1(key)}\\b`).test(mention.text);
3111
3908
  }
3112
3909
  const MONOREPO_PROJECT = /^(?:apps|packages|services|libs)\/[^/]+\//;
3113
3910
  function isInSameProject(mention, path) {
@@ -3204,7 +4001,8 @@ async function readLibrarySurface(repoDir, commit, changedPaths) {
3204
4001
  ecmascriptSurface(repository, pathsIn(SourceLanguage.TypeScript, SourceLanguage.Tsx)),
3205
4002
  pythonSurface(repository, pathsIn(SourceLanguage.Python))
3206
4003
  ]);
3207
- return (path, name) => rust(path, name) || ecmascript(path, name) || python(path, name);
4004
+ const go = goSurface(repository, pathsIn(SourceLanguage.Go));
4005
+ return (path, name) => rust(path, name) || ecmascript(path, name) || python(path, name) || go(path);
3208
4006
  }
3209
4007
  async function readTexts(repository, paths) {
3210
4008
  const unique = [...new Set(paths)];
@@ -3408,6 +4206,13 @@ async function pythonSurface(repository, paths) {
3408
4206
  return (!manifest.endsWith("pyproject.toml") || PYPROJECT_BUILDS.test(texts.get(manifest) ?? "")) && listedInDunderAll(texts.get(path), name);
3409
4207
  };
3410
4208
  }
4209
+ const GO_MODULE_MANIFEST = "go.mod";
4210
+ const GO_INTERNAL_FOLDER = "internal";
4211
+ const GO_TEST_FILE = /_test\.go$/;
4212
+ function goSurface(repository, paths) {
4213
+ const importable = new Set(paths.filter((path) => !GO_TEST_FILE.test(path) && !path.split("/").includes(GO_INTERNAL_FOLDER) && nearestManifest(repository.paths, path, [GO_MODULE_MANIFEST]) !== void 0));
4214
+ return (path) => importable.has(path);
4215
+ }
3411
4216
  // packages/engine/src/risk/migrationFiles.ts
3412
4217
  /**
3413
4218
  * Where frameworks keep database migrations: `migrations/` for db-migrate, knex, Sequelize,
@@ -3975,7 +4780,8 @@ function scanPublicApi(scan) {
3975
4780
  });
3976
4781
  }
3977
4782
  function apiUnitsOf(file, versions, surface) {
3978
- const bySnapshot = new Map([...versions.before?.definitions ?? [], ...versions.after?.definitions ?? []].map((definition) => [definition.snapshot, definition]));
4783
+ const definitions = [...versions.before?.definitions ?? [], ...versions.after?.definitions ?? []];
4784
+ const bySnapshot = new Map(definitions.flatMap((definition) => [[definition.snapshot, definition], [definition.wholeSnapshot, definition]]));
3979
4785
  const beforePath = "previousPath" in file.diff ? file.diff.previousPath : file.diff.path;
3980
4786
  return changedUnitsOf(file).flatMap((unit) => {
3981
4787
  if (!KIND_WORDS.has(unit.kind) || isTestUnit(unit.qualifiedName) || !("before" in unit.change)) return [];
@@ -4036,7 +4842,7 @@ function findingsForChange(api, file, versions, stillProvided) {
4036
4842
  function stillProvidedIn(versions, headText, namesAtHead) {
4037
4843
  const moduleScope = versions.after?.moduleScope.snapshot.text ?? "";
4038
4844
  return (name) => {
4039
- const escaped = escapeRegExp(name);
4845
+ const escaped = escapeRegExp$1(name);
4040
4846
  return namesAtHead.has(name) || new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`).test(moduleScope) || new RegExp(`["'\`]${escaped}["'\`]`).test(headText ?? "");
4041
4847
  };
4042
4848
  }
@@ -4088,7 +4894,7 @@ function hasOverloads(api, versions) {
4088
4894
  * `request` variable matches a function named `request`, so this looks for the call on the line.
4089
4895
  */
4090
4896
  function callSites(unit) {
4091
- const call = new RegExp(`(?<![\\w$])${escapeRegExp(unit.name)}\\s*(?:\\(|::<|<[^()]*>\\()`);
4897
+ const call = new RegExp(`(?<![\\w$])${escapeRegExp$1(unit.name)}\\s*(?:\\(|::<|<[^()]*>\\()`);
4092
4898
  return certainCallers(unit).filter((reference) => call.test(reference.snippet));
4093
4899
  }
4094
4900
  /** Who is affected, or as much as is known about it, as a sentence. */
@@ -4160,6 +4966,10 @@ async function scanBreakingChanges(scan) {
4160
4966
  const ECMASCRIPT = /* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]);
4161
4967
  const PYTHON = /* @__PURE__ */ new Set([SourceLanguage.Python]);
4162
4968
  const RUST = /* @__PURE__ */ new Set([SourceLanguage.Rust]);
4969
+ const GO = /* @__PURE__ */ new Set([SourceLanguage.Go]);
4970
+ const JAVA = /* @__PURE__ */ new Set([SourceLanguage.Java]);
4971
+ const C_FAMILY = /* @__PURE__ */ new Set([SourceLanguage.C, SourceLanguage.Cpp]);
4972
+ const CPP = /* @__PURE__ */ new Set([SourceLanguage.Cpp]);
4163
4973
  function rule(id, languages, severity, pattern, title, detail) {
4164
4974
  return {
4165
4975
  id,
@@ -4174,6 +4984,7 @@ function rule(id, languages, severity, pattern, title, detail) {
4174
4984
  const CODE_EXECUTION = "Runs a string as code. If any part of it can come from users or files, it is a code-injection hole.";
4175
4985
  const TLS_DISABLED = "Turns off certificate checks, so anyone on the network path can read or alter the traffic.";
4176
4986
  const SQL_INTERPOLATION = "SQL assembled from interpolated values is open to injection. Use bound parameters instead.";
4987
+ const SPAWNS_PROCESSES = "Check that no user input reaches the command or its arguments unchecked.";
4177
4988
  const API_RULES = [
4178
4989
  rule("js.eval", ECMASCRIPT, RiskSeverity.High, /\beval\s*\(/, "eval()", CODE_EXECUTION),
4179
4990
  rule("js.new-function", ECMASCRIPT, RiskSeverity.High, /\bnew\s+Function\s*\(/, "new Function()", CODE_EXECUTION),
@@ -4193,8 +5004,22 @@ const API_RULES = [
4193
5004
  rule("python.sql-format", PYTHON, RiskSeverity.Medium, /\.execute(?:many)?\s*\(\s*(?:f["']|["'][^"']*["']\s*(?:%|\.format\())/, "SQL from string formatting", SQL_INTERPOLATION),
4194
5005
  rule("rust.unsafe", RUST, RiskSeverity.Medium, /\bunsafe\s*(?:\{|fn\b|impl\b|trait\b)/, "unsafe code", "The compiler no longer checks memory safety here; review the invariants the code relies on."),
4195
5006
  rule("rust.transmute", RUST, RiskSeverity.Medium, /\b(?:mem::)?transmute\s*(?:::<|\()/, "mem::transmute", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour."),
4196
- rule("rust.command", RUST, RiskSeverity.Medium, /\bCommand::new\s*\(/, "Spawns processes", "Check that no user input reaches the command or its arguments unchecked."),
4197
- rule("rust.tls-disabled", RUST, RiskSeverity.High, /\bdanger_accept_invalid_(?:certs|hostnames)\s*\(\s*true/, "TLS verification disabled", TLS_DISABLED)
5007
+ rule("rust.command", RUST, RiskSeverity.Medium, /\bCommand::new\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5008
+ rule("rust.tls-disabled", RUST, RiskSeverity.High, /\bdanger_accept_invalid_(?:certs|hostnames)\s*\(\s*true/, "TLS verification disabled", TLS_DISABLED),
5009
+ rule("go.unsafe", GO, RiskSeverity.Medium, /\bunsafe\.(?:Pointer|Slice|String|StringData|SliceData|Add)\b/, "unsafe pointer use", "Go no longer checks types or bounds here; review the memory layout the code relies on."),
5010
+ rule("go.exec", GO, RiskSeverity.Medium, /\bexec\.Command(?:Context)?\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5011
+ rule("go.tls-disabled", GO, RiskSeverity.High, /\bInsecureSkipVerify\s*:\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5012
+ rule("go.unescaped-template", GO, RiskSeverity.Medium, /\btemplate\.(?:HTML|HTMLAttr|JS|JSStr|CSS|URL)\s*\(/, "Marks text as safe for a template", "html/template won't escape it; if any of it comes from users, that's cross-site scripting."),
5013
+ rule("go.sql-format", GO, RiskSeverity.Medium, /\.(?:Query|QueryRow|Exec)(?:Context)?\s*\([^)]*\bfmt\.Sprintf\s*\(/, "SQL from fmt.Sprintf", SQL_INTERPOLATION),
5014
+ rule("java.exec", JAVA, RiskSeverity.Medium, /\bgetRuntime\(\)\s*\.exec\s*\(|\bnew\s+ProcessBuilder\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5015
+ rule("java.deserialization", JAVA, RiskSeverity.Medium, /\bnew\s+ObjectInputStream\s*\(/, "Java deserialization", "Reading objects from a stream can run code chosen by whoever wrote it; never deserialize untrusted data."),
5016
+ rule("java.sql-concat", JAVA, RiskSeverity.Medium, /\.(?:executeQuery|executeUpdate|execute|prepareStatement|addBatch)\s*\(\s*"[^"]*"\s*\+/, "SQL built by concatenation", SQL_INTERPOLATION),
5017
+ rule("java.tls-disabled", JAVA, RiskSeverity.High, /\bNoopHostnameVerifier\b|\bALLOW_ALL_HOSTNAME_VERIFIER\b|\bsetHostnameVerifier\s*\(\s*\([^)]*\)\s*->\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5018
+ rule("c.unbounded-copy", C_FAMILY, RiskSeverity.Medium, /\b(?:strcpy|strcat|stpcpy|wcscpy|wcscat|sprintf|vsprintf|gets)\s*\(/, "Unbounded string copy", "Writes with no length limit, so input longer than the buffer overflows it. Use a bounded form such as snprintf."),
5019
+ rule("c.format-string", C_FAMILY, RiskSeverity.Medium, /\b(?:printf\s*\(|fprintf\s*\(\s*[\w.>-]+\s*,)\s*[A-Za-z_][\w.>-]*\s*\)/, "Format string from a variable", "If the text can come from users, conversions such as %n and %s in it read or write memory. Print it through \"%s\" instead."),
5020
+ rule("c.exec", C_FAMILY, RiskSeverity.Medium, /\b(?:system|popen|exec(?:l|lp|le|v|vp|vpe|ve))\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5021
+ rule("c.tls-disabled", C_FAMILY, RiskSeverity.High, /\bSSL_(?:CTX_)?set_verify\s*\([^,]+,\s*SSL_VERIFY_NONE\b|\bCURLOPT_SSL_VERIFY(?:PEER|HOST)\s*,\s*0/, "TLS verification disabled", TLS_DISABLED),
5022
+ rule("cpp.reinterpret-cast", CPP, RiskSeverity.Medium, /\breinterpret_cast\s*</, "reinterpret_cast", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour.")
4198
5023
  ];
4199
5024
  /**
4200
5025
  * Flags risky API uses on added lines of supported languages. A match only counts when it
@@ -4280,7 +5105,7 @@ async function findVulnerabilities(packages) {
4280
5105
  }
4281
5106
  const ids = [...new Set(affected.map((entry) => entry.id))];
4282
5107
  const details = /* @__PURE__ */ new Map();
4283
- for (const id of ids.slice(0, MAX_DETAILED_VULNERABILITIES)) details.set(id, vulnerabilitySchema.parse(await getJson$1(`${OSV_API}/vulns/${encodeURIComponent(id)}`)));
5108
+ for (const id of ids.slice(0, MAX_DETAILED_VULNERABILITIES)) details.set(id, vulnerabilitySchema.parse(await getJson$2(`${OSV_API}/vulns/${encodeURIComponent(id)}`)));
4284
5109
  return affected.map(({ package: entry, id }) => {
4285
5110
  return {
4286
5111
  package: entry,
@@ -4339,7 +5164,7 @@ async function postJson(url, body) {
4339
5164
  body: JSON.stringify(body)
4340
5165
  });
4341
5166
  }
4342
- async function getJson$1(url) {
5167
+ async function getJson$2(url) {
4343
5168
  return request(url, { method: "GET" });
4344
5169
  }
4345
5170
  async function request(url, init) {
@@ -4570,14 +5395,290 @@ const runScannerProcess = (binary, args, cwd) => new Promise((resolve) => {
4570
5395
  function firstErrorLine(result) {
4571
5396
  return result.stderr.split("\n").find((line) => line.trim() !== "")?.trim().slice(0, 200) ?? `exit code ${result.exitCode}`;
4572
5397
  }
4573
- // packages/engine/src/risk/dependencies/packages.ts
5398
+ // packages/engine/src/risk/dependencies/ecosystem.ts
4574
5399
  /** OSV's names for the package ecosystems the engine reads. */
4575
5400
  const Ecosystem = {
4576
5401
  Npm: "npm",
4577
5402
  Crates: "crates.io",
4578
- PyPI: "PyPI"
5403
+ PyPI: "PyPI",
5404
+ Go: "Go",
5405
+ Maven: "Maven"
4579
5406
  };
5407
+ // packages/engine/src/risk/dependencies/goModules.ts
5408
+ const INDIRECT_COMMENT = /\/\/\s*indirect\b/;
5409
+ const LINE_COMMENT = /\/\/.*$/;
5410
+ const DIRECTORY_PATH = /^(?:\.{1,2}[\\/]|[\\/]|[A-Za-z]:[\\/])/;
5411
+ const BLOCK_END = ")";
5412
+ /** Direct requirements, the ones the module's own code imports; a module replaced by a directory isn't fetched. */
5413
+ function parseGoMod(text) {
5414
+ const { requirements, replacements } = readGoMod(text);
5415
+ const declared = /* @__PURE__ */ new Map();
5416
+ for (const requirement of requirements) {
5417
+ if (requirement.indirect) continue;
5418
+ const replacement = replacementFor(replacements, requirement);
5419
+ declared.set(requirement.module, replacement?.kind === "directory" ? `path:${replacement.path}` : requirement.version);
5420
+ }
5421
+ return declared;
5422
+ }
5423
+ /** Every module version the build uses, replacements applied. */
5424
+ function goModLockfile(text) {
5425
+ const { requirements, replacements } = readGoMod(text);
5426
+ return requirements.flatMap((requirement) => {
5427
+ const replacement = replacementFor(replacements, requirement);
5428
+ if (replacement?.kind === "directory") return [];
5429
+ const used = replacement ?? requirement;
5430
+ return [{
5431
+ ecosystem: Ecosystem.Go,
5432
+ name: used.module,
5433
+ version: used.version
5434
+ }];
5435
+ });
5436
+ }
5437
+ function replacementFor(replacements, requirement) {
5438
+ return replacements.get(`${requirement.module}@${requirement.version}`) ?? replacements.get(requirement.module);
5439
+ }
5440
+ function readGoMod(text) {
5441
+ const requirements = [];
5442
+ const replacements = /* @__PURE__ */ new Map();
5443
+ let block;
5444
+ for (const rawLine of text.split("\n")) {
5445
+ const indirect = INDIRECT_COMMENT.test(rawLine);
5446
+ const line = rawLine.replace(LINE_COMMENT, "").trim();
5447
+ if (line === "") continue;
5448
+ if (block !== void 0 && line === BLOCK_END) {
5449
+ block = void 0;
5450
+ continue;
5451
+ }
5452
+ const words = line.split(/\s+/);
5453
+ const [directive, rest] = block === void 0 ? [words.at(0), words.slice(1)] : [block, words];
5454
+ if (block === void 0 && rest.length === 1 && rest.at(0) === "(") {
5455
+ block = directive;
5456
+ continue;
5457
+ }
5458
+ if (directive === "require") addRequirement(requirements, rest, indirect);
5459
+ if (directive === "replace") addReplacement(replacements, rest);
5460
+ }
5461
+ return {
5462
+ requirements,
5463
+ replacements
5464
+ };
5465
+ }
5466
+ function addRequirement(requirements, words, indirect) {
5467
+ const [module, version] = words;
5468
+ if (module !== void 0 && version !== void 0) requirements.push({
5469
+ module: unquote(module),
5470
+ version,
5471
+ indirect
5472
+ });
5473
+ }
5474
+ function addReplacement(replacements, words) {
5475
+ const arrow = words.indexOf("=>");
5476
+ const [module, version] = words.slice(0, arrow);
5477
+ const [target, targetVersion] = words.slice(arrow + 1);
5478
+ if (arrow === -1 || module === void 0 || target === void 0) return;
5479
+ const key = version === void 0 ? unquote(module) : `${unquote(module)}@${version}`;
5480
+ const path = unquote(target);
5481
+ if (DIRECTORY_PATH.test(path)) replacements.set(key, {
5482
+ kind: "directory",
5483
+ path
5484
+ });
5485
+ else if (targetVersion !== void 0) replacements.set(key, {
5486
+ kind: "module",
5487
+ module: path,
5488
+ version: targetVersion
5489
+ });
5490
+ }
5491
+ function unquote(word) {
5492
+ return word.replace(/^["`]|["`]$/g, "");
5493
+ }
5494
+ // packages/engine/src/risk/dependencies/fields.ts
5495
+ function isRecord(value) {
5496
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5497
+ }
5498
+ function field(value, key) {
5499
+ return isRecord(value) ? value[key] : void 0;
5500
+ }
5501
+ function stringField(value, key) {
5502
+ const found = field(value, key);
5503
+ return typeof found === "string" ? found : void 0;
5504
+ }
5505
+ function recordOrEmpty(value) {
5506
+ return isRecord(value) ? value : {};
5507
+ }
5508
+ // packages/engine/src/risk/dependencies/maven.ts
5509
+ const COMMENT_OPEN = "<!--";
5510
+ const COMMENT_CLOSE = "-->";
5511
+ const NOT_PROJECT_DEPENDENCIES = [
5512
+ /<dependencyManagement>[\s\S]*?<\/dependencyManagement>/g,
5513
+ /<build>[\s\S]*?<\/build>/g,
5514
+ /<reporting>[\s\S]*?<\/reporting>/g,
5515
+ /<exclusions>[\s\S]*?<\/exclusions>/g
5516
+ ];
5517
+ const DEPENDENCY = /<dependency>([\s\S]*?)<\/dependency>/g;
5518
+ const PROPERTIES = /<properties>([\s\S]*?)<\/properties>/g;
5519
+ const PROPERTY = /<([\w.-]+)>\s*([^<]*?)\s*<\/\1>/g;
5520
+ const PROPERTY_REFERENCE = /\$\{([^}]+)\}/g;
5521
+ const UNRESOLVED = "${";
5522
+ const NOT_EXACT_VERSION = /^[[(]|[,\s]|^(?:LATEST|RELEASE)$|^latest\.|\$|\+$/;
5523
+ const ANY_VERSION = "*";
5524
+ const INTERNAL_REQUIREMENT = "workspace:";
5525
+ const PROJECT_SECTIONS = [
5526
+ /<parent>[\s\S]*?<\/parent>/g,
5527
+ /<dependencies>[\s\S]*?<\/dependencies>/g,
5528
+ /<profiles>[\s\S]*?<\/profiles>/g
5529
+ ];
5530
+ function parsePom(text) {
5531
+ const { coordinates, ownGroup } = readPom(text);
5532
+ return new Map(coordinates.map((coordinate) => [coordinate.name, isInternal(coordinate, ownGroup) ? INTERNAL_REQUIREMENT : coordinate.version ?? ANY_VERSION]));
5533
+ }
5534
+ function pomLockfile(text) {
5535
+ const { coordinates, ownGroup } = readPom(text);
5536
+ return toLocked(coordinates.filter((coordinate) => !isInternal(coordinate, ownGroup)));
5537
+ }
5538
+ function isInternal(coordinate, ownGroup) {
5539
+ return ownGroup !== void 0 && coordinate.version === void 0 && coordinate.name.startsWith(`${ownGroup}:`);
5540
+ }
5541
+ function toDeclared(coordinates) {
5542
+ return new Map(coordinates.map((coordinate) => [coordinate.name, coordinate.version ?? ANY_VERSION]));
5543
+ }
5544
+ /** The coordinates that name one exact version, which is what OSV can check. */
5545
+ function toLocked(coordinates) {
5546
+ return coordinates.flatMap(({ name, version }) => version === void 0 || NOT_EXACT_VERSION.test(version) ? [] : [{
5547
+ ecosystem: Ecosystem.Maven,
5548
+ name,
5549
+ version
5550
+ }]);
5551
+ }
5552
+ function readPom(text) {
5553
+ const withoutComments = withoutXmlComments(text);
5554
+ const properties = readProperties(withoutComments);
5555
+ const projectOnly = withoutSections(withoutComments, NOT_PROJECT_DEPENDENCIES);
5556
+ return {
5557
+ coordinates: [...projectOnly.matchAll(DEPENDENCY)].flatMap((match) => {
5558
+ const body = match[1] ?? "";
5559
+ const written = elementText(body, "groupId");
5560
+ const group = written === void 0 ? void 0 : resolveProperties(written, properties);
5561
+ const artifact = elementText(body, "artifactId");
5562
+ if (group === void 0 || artifact === void 0) return [];
5563
+ const version = elementText(body, "version");
5564
+ return [{
5565
+ name: `${group}:${artifact}`,
5566
+ version: version === void 0 ? void 0 : resolveProperties(version, properties)
5567
+ }];
5568
+ }),
5569
+ ownGroup: elementText(withoutSections(projectOnly, PROJECT_SECTIONS), "groupId") ?? elementText(/<parent>([\s\S]*?)<\/parent>/.exec(withoutComments)?.[1] ?? "", "groupId")
5570
+ };
5571
+ }
5572
+ function withoutXmlComments(xml) {
5573
+ let text = xml;
5574
+ while (text.includes(COMMENT_OPEN)) text = withoutCommentsOnce(text);
5575
+ return text;
5576
+ }
5577
+ function withoutCommentsOnce(xml) {
5578
+ let kept = "";
5579
+ let position = 0;
5580
+ for (let open = xml.indexOf(COMMENT_OPEN); open !== -1; open = xml.indexOf(COMMENT_OPEN, position)) {
5581
+ kept += xml.slice(position, open);
5582
+ const close = xml.indexOf(COMMENT_CLOSE, open + 4);
5583
+ if (close === -1) return kept;
5584
+ position = close + 3;
5585
+ }
5586
+ return kept + xml.slice(position);
5587
+ }
5588
+ function withoutSections(xml, sections) {
5589
+ return sections.reduce((current, section) => current.replace(section, ""), xml);
5590
+ }
5591
+ function readProperties(pom) {
5592
+ const properties = /* @__PURE__ */ new Map();
5593
+ for (const section of pom.matchAll(PROPERTIES)) for (const [, key, value] of (section[1] ?? "").matchAll(PROPERTY)) if (key !== void 0 && value !== void 0) properties.set(key, value);
5594
+ return properties;
5595
+ }
5596
+ function resolveProperties(value, properties) {
5597
+ const resolved = value.replace(PROPERTY_REFERENCE, (reference, key) => properties.get(key) ?? reference);
5598
+ return resolved.includes(UNRESOLVED) ? void 0 : resolved;
5599
+ }
5600
+ function elementText(xml, element) {
5601
+ return new RegExp(`<${element}>\\s*([^<]*?)\\s*</${element}>`).exec(xml)?.[1];
5602
+ }
5603
+ // packages/engine/src/risk/dependencies/gradle.ts
5604
+ const CONFIGURATION = String.raw`\b(?:\w*(?:[Ii]mplementation|[Aa]pi|[Cc]ompileOnly|[Rr]untimeOnly|[Aa]nnotationProcessor|[Cc]ompile|[Rr]untime)|kapt\w*|ksp\w*|classpath|coreLibraryDesugaring|detektPlugins|lintChecks)`;
5605
+ const PLATFORM = String.raw`(?:(?:platform|enforcedPlatform)\s*\(\s*)?`;
5606
+ const COORDINATE = String.raw`["']([\w.-]+):([\w.-]+)(?::([^"':@\s]+))?(?::[\w.-]+)?(?:@\w+)?["']`;
5607
+ const COORDINATE_STRING = new RegExp(String.raw`${CONFIGURATION}\s*(?:\(\s*)?${PLATFORM}${COORDINATE}`, "g");
5608
+ const MAP_NOTATION = /\bgroup\s*[:=]\s*["']([\w.-]+)["']\s*,\s*name\s*[:=]\s*["']([\w.-]+)["'](?:\s*,\s*version\s*[:=]\s*["']([^"']+)["'])?/g;
5609
+ const LOCKED_LINE = /^([\w.-]+):([\w.-]+):([^=\s]+)=/;
5610
+ const RICH_VERSION_KEYS = [
5611
+ "strictly",
5612
+ "require",
5613
+ "prefer"
5614
+ ];
5615
+ function parseGradleBuild(text) {
5616
+ return toDeclared(buildCoordinates(text));
5617
+ }
5618
+ function gradleBuildLockfile(text) {
5619
+ return toLocked(buildCoordinates(text));
5620
+ }
5621
+ function parseGradleCatalog(text) {
5622
+ return toDeclared(catalogCoordinates(text));
5623
+ }
5624
+ function gradleCatalogLockfile(text) {
5625
+ return toLocked(catalogCoordinates(text));
5626
+ }
5627
+ function gradleLockfile(text) {
5628
+ return text.split("\n").flatMap((line) => {
5629
+ const [, group, artifact, version] = LOCKED_LINE.exec(line.trim()) ?? [];
5630
+ return group === void 0 || artifact === void 0 || version === void 0 ? [] : [{
5631
+ ecosystem: Ecosystem.Maven,
5632
+ name: `${group}:${artifact}`,
5633
+ version
5634
+ }];
5635
+ });
5636
+ }
5637
+ function buildCoordinates(text) {
5638
+ const fromStrings = [...text.matchAll(COORDINATE_STRING)].map(([, group, artifact, version]) => ({
5639
+ name: `${group}:${artifact}`,
5640
+ version
5641
+ }));
5642
+ const fromMaps = [...text.matchAll(MAP_NOTATION)].map(([, group, artifact, version]) => ({
5643
+ name: `${group}:${artifact}`,
5644
+ version
5645
+ }));
5646
+ return [...fromStrings, ...fromMaps];
5647
+ }
5648
+ function catalogCoordinates(text) {
5649
+ const catalog = parse(text);
5650
+ const versions = recordOrEmpty(field(catalog, "versions"));
5651
+ return Object.values(recordOrEmpty(field(catalog, "libraries"))).flatMap((library) => {
5652
+ if (typeof library === "string") {
5653
+ const [group, artifact, version] = library.split(":");
5654
+ return group === void 0 || artifact === void 0 ? [] : [{
5655
+ name: `${group}:${artifact}`,
5656
+ version
5657
+ }];
5658
+ }
5659
+ const group = stringField(library, "group");
5660
+ const artifact = stringField(library, "name");
5661
+ const name = stringField(library, "module") ?? (group === void 0 || artifact === void 0 ? void 0 : `${group}:${artifact}`);
5662
+ return name === void 0 ? [] : [{
5663
+ name,
5664
+ version: catalogVersion(field(library, "version"), versions)
5665
+ }];
5666
+ });
5667
+ }
5668
+ function catalogVersion(version, versions) {
5669
+ if (typeof version === "string") return version;
5670
+ const reference = stringField(version, "ref");
5671
+ if (reference !== void 0) return catalogVersion(versions[reference], {});
5672
+ if (!isRecord(version)) return void 0;
5673
+ return RICH_VERSION_KEYS.map((key) => stringField(version, key)).find((value) => value !== void 0);
5674
+ }
5675
+ // packages/engine/src/risk/dependencies/packages.ts
4580
5676
  const REQUIREMENTS_FILE = /^requirements.*\.txt$/;
5677
+ const GO_MOD = "go.mod";
5678
+ const POM = "pom.xml";
5679
+ const GRADLE_BUILD = /* @__PURE__ */ new Set(["build.gradle", "build.gradle.kts"]);
5680
+ const GRADLE_CATALOG = /\.versions\.toml$/;
5681
+ const GRADLE_LOCKFILE = "gradle.lockfile";
4581
5682
  const PEP508_REQUIREMENT = /^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*([^;#]*)/;
4582
5683
  const PINNED_VERSION = /^==\s*([^\s,;]+)$/;
4583
5684
  const MANIFESTS = [
@@ -4600,6 +5701,26 @@ const MANIFESTS = [
4600
5701
  ecosystem: Ecosystem.PyPI,
4601
5702
  matches: (name) => REQUIREMENTS_FILE.test(name),
4602
5703
  parse: parseRequirements
5704
+ },
5705
+ {
5706
+ ecosystem: Ecosystem.Go,
5707
+ matches: (name) => name === GO_MOD,
5708
+ parse: parseGoMod
5709
+ },
5710
+ {
5711
+ ecosystem: Ecosystem.Maven,
5712
+ matches: (name) => name === POM,
5713
+ parse: parsePom
5714
+ },
5715
+ {
5716
+ ecosystem: Ecosystem.Maven,
5717
+ matches: (name) => GRADLE_BUILD.has(name),
5718
+ parse: parseGradleBuild
5719
+ },
5720
+ {
5721
+ ecosystem: Ecosystem.Maven,
5722
+ matches: (name) => GRADLE_CATALOG.test(name),
5723
+ parse: parseGradleCatalog
4603
5724
  }
4604
5725
  ];
4605
5726
  const LOCKFILES = [
@@ -4622,6 +5743,31 @@ const LOCKFILES = [
4622
5743
  ecosystem: Ecosystem.PyPI,
4623
5744
  matches: (name) => REQUIREMENTS_FILE.test(name),
4624
5745
  parse: pinnedRequirements
5746
+ },
5747
+ {
5748
+ ecosystem: Ecosystem.Go,
5749
+ matches: (name) => name === GO_MOD,
5750
+ parse: goModLockfile
5751
+ },
5752
+ {
5753
+ ecosystem: Ecosystem.Maven,
5754
+ matches: (name) => name === POM,
5755
+ parse: pomLockfile
5756
+ },
5757
+ {
5758
+ ecosystem: Ecosystem.Maven,
5759
+ matches: (name) => GRADLE_BUILD.has(name),
5760
+ parse: gradleBuildLockfile
5761
+ },
5762
+ {
5763
+ ecosystem: Ecosystem.Maven,
5764
+ matches: (name) => GRADLE_CATALOG.test(name),
5765
+ parse: gradleCatalogLockfile
5766
+ },
5767
+ {
5768
+ ecosystem: Ecosystem.Maven,
5769
+ matches: (name) => name === GRADLE_LOCKFILE,
5770
+ parse: gradleLockfile
4625
5771
  }
4626
5772
  ];
4627
5773
  const UNREAD_LOCKFILES = /* @__PURE__ */ new Set([
@@ -4742,19 +5888,6 @@ function pinnedRequirements(text) {
4742
5888
  function normalizePythonName(name) {
4743
5889
  return name.toLowerCase().replace(/[-_.]+/g, "-");
4744
5890
  }
4745
- function isRecord(value) {
4746
- return typeof value === "object" && value !== null && !Array.isArray(value);
4747
- }
4748
- function field(value, key) {
4749
- return isRecord(value) ? value[key] : void 0;
4750
- }
4751
- function stringField(value, key) {
4752
- const found = field(value, key);
4753
- return typeof found === "string" ? found : void 0;
4754
- }
4755
- function recordOrEmpty(value) {
4756
- return isRecord(value) ? value : {};
4757
- }
4758
5891
  function stringEntries(value) {
4759
5892
  return Object.entries(recordOrEmpty(value)).flatMap(([key, entry]) => typeof entry === "string" ? [[key, entry]] : []);
4760
5893
  }
@@ -5112,6 +6245,62 @@ const POPULAR_PACKAGES = {
5112
6245
  "base64",
5113
6246
  "sha2",
5114
6247
  "rustls"
6248
+ ]),
6249
+ [Ecosystem.Go]: /* @__PURE__ */ new Set([
6250
+ "github.com/gin-gonic/gin",
6251
+ "github.com/stretchr/testify",
6252
+ "github.com/spf13/cobra",
6253
+ "github.com/spf13/viper",
6254
+ "github.com/sirupsen/logrus",
6255
+ "go.uber.org/zap",
6256
+ "github.com/gorilla/mux",
6257
+ "github.com/gorilla/websocket",
6258
+ "google.golang.org/grpc",
6259
+ "google.golang.org/protobuf",
6260
+ "github.com/golang-jwt/jwt/v5",
6261
+ "gorm.io/gorm",
6262
+ "github.com/redis/go-redis/v9",
6263
+ "github.com/jackc/pgx/v5",
6264
+ "github.com/go-sql-driver/mysql",
6265
+ "github.com/lib/pq",
6266
+ "github.com/google/uuid",
6267
+ "github.com/labstack/echo/v4",
6268
+ "github.com/gofiber/fiber/v2",
6269
+ "github.com/go-chi/chi/v5",
6270
+ "github.com/prometheus/client_golang",
6271
+ "golang.org/x/crypto",
6272
+ "golang.org/x/net",
6273
+ "golang.org/x/sync",
6274
+ "gopkg.in/yaml.v3",
6275
+ "github.com/aws/aws-sdk-go-v2",
6276
+ "github.com/boltdb/bolt",
6277
+ "go.etcd.io/bbolt"
6278
+ ]),
6279
+ [Ecosystem.Maven]: /* @__PURE__ */ new Set([
6280
+ "com.fasterxml.jackson.core:jackson-databind",
6281
+ "com.fasterxml.jackson.core:jackson-core",
6282
+ "org.springframework:spring-core",
6283
+ "org.springframework:spring-web",
6284
+ "org.springframework.boot:spring-boot-starter-web",
6285
+ "com.google.guava:guava",
6286
+ "org.apache.commons:commons-lang3",
6287
+ "commons-io:commons-io",
6288
+ "junit:junit",
6289
+ "org.junit.jupiter:junit-jupiter",
6290
+ "org.mockito:mockito-core",
6291
+ "org.slf4j:slf4j-api",
6292
+ "ch.qos.logback:logback-classic",
6293
+ "org.apache.logging.log4j:log4j-core",
6294
+ "com.google.code.gson:gson",
6295
+ "org.projectlombok:lombok",
6296
+ "org.apache.httpcomponents:httpclient",
6297
+ "com.squareup.okhttp3:okhttp",
6298
+ "org.postgresql:postgresql",
6299
+ "mysql:mysql-connector-java",
6300
+ "org.hibernate:hibernate-core",
6301
+ "io.netty:netty-all",
6302
+ "org.jetbrains.kotlin:kotlin-stdlib",
6303
+ "org.yaml:snakeyaml"
5115
6304
  ])
5116
6305
  };
5117
6306
  // packages/engine/src/risk/dependencies/packageTrust.ts
@@ -5129,7 +6318,9 @@ const USER_AGENT$1 = "walkdiff (https://github.com/navasvarela/walkdiff)";
5129
6318
  const REGISTRY_NAMES = {
5130
6319
  [Ecosystem.Npm]: "npm",
5131
6320
  [Ecosystem.PyPI]: "PyPI",
5132
- [Ecosystem.Crates]: "crates.io"
6321
+ [Ecosystem.Crates]: "crates.io",
6322
+ [Ecosystem.Go]: "the Go module proxy",
6323
+ [Ecosystem.Maven]: "Maven Central"
5133
6324
  };
5134
6325
  /**
5135
6326
  * Requirements that don't come from a public registry, so a registry can't say anything about them:
@@ -5273,6 +6464,15 @@ const cratesSchema = z.object({
5273
6464
  crate: z.object({ created_at: z.string() }).loose(),
5274
6465
  versions: z.array(z.object({ license: z.string().nullish() }).loose()).default([])
5275
6466
  }).loose();
6467
+ function singleRequest(service, url, read) {
6468
+ return {
6469
+ service,
6470
+ facts: async (name, getJson) => {
6471
+ const body = await getJson(url(name));
6472
+ return body === void 0 ? void 0 : read(body);
6473
+ }
6474
+ };
6475
+ }
5276
6476
  function npmLicenseText(license) {
5277
6477
  return typeof license === "string" ? license : license?.type;
5278
6478
  }
@@ -5280,45 +6480,83 @@ function npmPathFor(name) {
5280
6480
  return name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
5281
6481
  }
5282
6482
  const REGISTRIES = {
5283
- [Ecosystem.Npm]: {
5284
- url: (name) => `https://registry.npmjs.org/${npmPathFor(name)}`,
5285
- read: (body) => {
5286
- const parsed = npmSchema.parse(body);
5287
- const latest = parsed["dist-tags"]?.latest;
5288
- const latestLicense = latest === void 0 ? void 0 : parsed.versions?.[latest]?.license;
5289
- return {
5290
- firstPublished: new Date(parsed.time.created),
5291
- license: npmLicenseText(latestLicense) ?? npmLicenseText(parsed.license)
5292
- };
5293
- }
5294
- },
5295
- [Ecosystem.PyPI]: {
5296
- url: (name) => `https://pypi.org/pypi/${encodeURIComponent(name)}/json`,
5297
- read: (body) => {
5298
- const { info, releases } = pypiSchema.parse(body);
5299
- const times = Object.values(releases).flat().map((file) => new Date(file.upload_time_iso_8601).getTime());
6483
+ [Ecosystem.Npm]: singleRequest("npm", (name) => `https://registry.npmjs.org/${npmPathFor(name)}`, (body) => {
6484
+ const parsed = npmSchema.parse(body);
6485
+ const latest = parsed["dist-tags"]?.latest;
6486
+ const latestLicense = latest === void 0 ? void 0 : parsed.versions?.[latest]?.license;
6487
+ return {
6488
+ firstPublished: new Date(parsed.time.created),
6489
+ license: npmLicenseText(latestLicense) ?? npmLicenseText(parsed.license)
6490
+ };
6491
+ }),
6492
+ [Ecosystem.PyPI]: singleRequest("PyPI", (name) => `https://pypi.org/pypi/${encodeURIComponent(name)}/json`, (body) => {
6493
+ const { info, releases } = pypiSchema.parse(body);
6494
+ const times = Object.values(releases).flat().map((file) => new Date(file.upload_time_iso_8601).getTime());
6495
+ return {
6496
+ firstPublished: times.length === 0 ? void 0 : new Date(Math.min(...times)),
6497
+ license: pypiLicense(info.license_expression, info.license, info.classifiers)
6498
+ };
6499
+ }),
6500
+ [Ecosystem.Crates]: singleRequest("crates.io", (name) => `https://crates.io/api/v1/crates/${encodeURIComponent(name)}`, (body) => {
6501
+ const parsed = cratesSchema.parse(body);
6502
+ return {
6503
+ firstPublished: new Date(parsed.crate.created_at),
6504
+ license: parsed.versions.at(0)?.license ?? void 0
6505
+ };
6506
+ }),
6507
+ [Ecosystem.Go]: depsDevClient("go"),
6508
+ [Ecosystem.Maven]: depsDevClient("maven")
6509
+ };
6510
+ const DEPS_DEV_SYSTEMS = "https://api.deps.dev/v3/systems";
6511
+ const depsDevPackageSchema = z.object({ versions: z.array(z.object({
6512
+ versionKey: z.object({ version: z.string() }).loose(),
6513
+ publishedAt: z.string().optional(),
6514
+ isDefault: z.boolean().optional()
6515
+ }).loose()).default([]) }).loose();
6516
+ const depsDevVersionSchema = z.object({ licenses: z.array(z.string()).default([]) }).loose();
6517
+ function depsDevClient(system) {
6518
+ return {
6519
+ service: "deps.dev",
6520
+ facts: async (name, getJson) => {
6521
+ const packageUrl = `${DEPS_DEV_SYSTEMS}/${system}/packages/${encodeURIComponent(name)}`;
6522
+ const body = await getJson(packageUrl);
6523
+ if (body === void 0) return void 0;
6524
+ const { versions } = depsDevPackageSchema.parse(body);
6525
+ const times = versions.flatMap((version) => version.publishedAt === void 0 ? [] : [new Date(version.publishedAt).getTime()]);
6526
+ const current = versions.find((version) => version.isDefault === true) ?? versions.at(-1);
6527
+ const license = current === void 0 ? void 0 : depsDevLicense(await getJson(`${packageUrl}/versions/${encodeURIComponent(current.versionKey.version)}`));
5300
6528
  return {
5301
6529
  firstPublished: times.length === 0 ? void 0 : new Date(Math.min(...times)),
5302
- license: pypiLicense(info.license_expression, info.license, info.classifiers)
5303
- };
5304
- }
5305
- },
5306
- [Ecosystem.Crates]: {
5307
- url: (name) => `https://crates.io/api/v1/crates/${encodeURIComponent(name)}`,
5308
- read: (body) => {
5309
- const parsed = cratesSchema.parse(body);
5310
- return {
5311
- firstPublished: new Date(parsed.crate.created_at),
5312
- license: parsed.versions.at(0)?.license ?? void 0
6530
+ license
5313
6531
  };
5314
6532
  }
5315
- }
5316
- };
6533
+ };
6534
+ }
6535
+ function depsDevLicense(body) {
6536
+ if (body === void 0) return void 0;
6537
+ const { licenses } = depsDevVersionSchema.parse(body);
6538
+ if (licenses.length <= 1) return licenses.at(0);
6539
+ return licenses.map((license) => `(${license})`).join(" AND ");
6540
+ }
5317
6541
  async function lookUpOnRegistry(ecosystem, name) {
5318
6542
  const client = REGISTRIES[ecosystem];
6543
+ let facts;
6544
+ try {
6545
+ facts = await client.facts(name, (url) => getJson$1(url, client.service));
6546
+ } catch (error) {
6547
+ if (error instanceof RegistryUnavailableError) throw error;
6548
+ throw new RegistryUnavailableError(`${client.service} sent an unexpected answer: ${error instanceof Error ? error.message : String(error)}`);
6549
+ }
6550
+ return facts?.firstPublished === void 0 ? { status: RegistryStatus.Missing } : {
6551
+ status: RegistryStatus.Published,
6552
+ firstPublished: facts.firstPublished,
6553
+ license: facts.license
6554
+ };
6555
+ }
6556
+ async function getJson$1(url, service) {
5319
6557
  let response;
5320
6558
  try {
5321
- response = await fetch(client.url(name), {
6559
+ response = await fetch(url, {
5322
6560
  headers: {
5323
6561
  "User-Agent": USER_AGENT$1,
5324
6562
  Accept: "application/json"
@@ -5326,20 +6564,11 @@ async function lookUpOnRegistry(ecosystem, name) {
5326
6564
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
5327
6565
  });
5328
6566
  } catch (error) {
5329
- throw new RegistryUnavailableError(`could not reach ${REGISTRY_NAMES[ecosystem]}: ${error instanceof Error ? error.message : String(error)}`);
5330
- }
5331
- if (response.status === 404) return { status: RegistryStatus.Missing };
5332
- if (!response.ok) throw new RegistryUnavailableError(`${REGISTRY_NAMES[ecosystem]} responded ${response.status}`);
5333
- try {
5334
- const { firstPublished, license } = client.read(await response.json());
5335
- return firstPublished === void 0 ? { status: RegistryStatus.Missing } : {
5336
- status: RegistryStatus.Published,
5337
- firstPublished,
5338
- license
5339
- };
5340
- } catch (error) {
5341
- throw new RegistryUnavailableError(`${REGISTRY_NAMES[ecosystem]} sent an unexpected answer: ${error instanceof Error ? error.message : String(error)}`);
6567
+ throw new RegistryUnavailableError(`could not reach ${service}: ${error instanceof Error ? error.message : String(error)}`);
5342
6568
  }
6569
+ if (response.status === 404) return void 0;
6570
+ if (!response.ok) throw new RegistryUnavailableError(`${service} responded ${response.status}`);
6571
+ return response.json();
5343
6572
  }
5344
6573
  const LIVE_TRUST_SOURCES = (now) => ({
5345
6574
  lookUp: lookUpOnRegistry,
@@ -5347,6 +6576,7 @@ const LIVE_TRUST_SOURCES = (now) => ({
5347
6576
  now
5348
6577
  });
5349
6578
  // packages/engine/src/risk/dependencies/scanDependencies.ts
6579
+ const MAVEN_SEPARATOR = ":";
5350
6580
  const OSV_DATABASE_CHECK = {
5351
6581
  name: "OSV database",
5352
6582
  detail: "package versions new to lockfiles"
@@ -5559,16 +6789,26 @@ function vulnerabilityFinding(found, lockfile, text) {
5559
6789
  }, lockfile, lineMentioning$1(text, entry.name), `${entry.name} ${entry.version}`);
5560
6790
  }
5561
6791
  /**
5562
- * First line naming the package, so a finding links to where it is declared or locked:
5563
- * a quoted name (JSON, TOML values) or the name at the start of a line (TOML keys,
5564
- * requirements files), never as part of a longer name.
6792
+ * First line naming the package, so a finding links to where it is declared or locked, never
6793
+ * as part of a longer name:
6794
+ * - a quoted name, in JSON and TOML values, or a quoted Maven coordinate in a Gradle script,
6795
+ * `"group:artifact:1.0"`;
6796
+ * - the name at the start of a line, in TOML keys, requirements files, go.mod's `require`
6797
+ * lines and gradle.lockfile;
6798
+ * - for a Maven `group:artifact`, a pom's `<artifactId>` element.
5565
6799
  */
5566
6800
  function lineMentioning$1(text, name) {
5567
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5568
- const pattern = new RegExp(`"${escaped}"|^\\s*${escaped}(?![\\w.-])`);
6801
+ const escaped = escapeRegExp(name);
6802
+ const alternatives = [`["']${escaped}["':]`, `^\\s*(?:require\\s+)?${escaped}(?![\\w./-])`];
6803
+ const artifact = name.includes(MAVEN_SEPARATOR) ? name.split(MAVEN_SEPARATOR).at(-1) : void 0;
6804
+ if (artifact !== void 0) alternatives.push(`<artifactId>\\s*${escapeRegExp(artifact)}\\s*</artifactId>`);
6805
+ const pattern = new RegExp(alternatives.join("|"));
5569
6806
  const index = text.split("\n").findIndex((line) => pattern.test(line));
5570
6807
  return index === -1 ? null : index + 1;
5571
6808
  }
6809
+ function escapeRegExp(text) {
6810
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6811
+ }
5572
6812
  function previousPathOf$1(diff) {
5573
6813
  return diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied ? diff.previousPath : diff.path;
5574
6814
  }
@@ -5610,6 +6850,46 @@ function isWorseThanLimit(before, after, limit) {
5610
6850
  if (after <= limit) return false;
5611
6851
  return before === void 0 || before <= limit || after >= before * MEANINGFUL_GROWTH;
5612
6852
  }
6853
+ // packages/engine/src/risk/languageCoverage.ts
6854
+ const UNPARSED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
6855
+ ".kt",
6856
+ ".rb",
6857
+ ".php",
6858
+ ".cs",
6859
+ ".swift",
6860
+ ".scala",
6861
+ ".sh"
6862
+ ]);
6863
+ const WITHOUT_PUBLIC_API_RULES = /* @__PURE__ */ new Set([
6864
+ SourceLanguage.Java,
6865
+ SourceLanguage.C,
6866
+ SourceLanguage.Cpp
6867
+ ]);
6868
+ /** The checks that can't read some of the changed files, because of the language they're in. */
6869
+ function languageGaps(paths) {
6870
+ const unparsed = extensionsOf(paths.filter(isUnparsedCode));
6871
+ const withoutApiRules = extensionsOf(paths.filter((path) => isUnparsedCode(path) || hasNoPublicApiRules(path)));
6872
+ const gaps = [];
6873
+ if (unparsed.length > 0) gaps.push({
6874
+ check: `Dangerous-API rules for ${unparsed.join(", ")} files`,
6875
+ reason: "rules exist only for Rust, TypeScript/JavaScript, Python, Go, Java, C and C++"
6876
+ });
6877
+ if (withoutApiRules.length > 0) gaps.push({
6878
+ check: `Public API checks for ${withoutApiRules.join(", ")} files`,
6879
+ reason: "they exist only for Rust, TypeScript/JavaScript, Python and Go"
6880
+ });
6881
+ return gaps;
6882
+ }
6883
+ function isUnparsedCode(path) {
6884
+ return UNPARSED_CODE_EXTENSIONS.has(extname(path));
6885
+ }
6886
+ function hasNoPublicApiRules(path) {
6887
+ const language = languageSpecFor(path)?.language;
6888
+ return language !== void 0 && WITHOUT_PUBLIC_API_RULES.has(language);
6889
+ }
6890
+ function extensionsOf(paths) {
6891
+ return [...new Set(paths.map((path) => extname(path)))];
6892
+ }
5613
6893
  // packages/engine/src/risk/reviewSignals.ts
5614
6894
  const LARGE_CHANGE_LINES = 400;
5615
6895
  const VERY_LARGE_CHANGE_LINES = 1e3;
@@ -7023,22 +8303,6 @@ const SEVERITY_RANK = {
7023
8303
  [RiskSeverity.Medium]: 1,
7024
8304
  [RiskSeverity.Low]: 2
7025
8305
  };
7026
- const UNCOVERED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
7027
- ".go",
7028
- ".java",
7029
- ".kt",
7030
- ".rb",
7031
- ".php",
7032
- ".cs",
7033
- ".c",
7034
- ".cc",
7035
- ".cpp",
7036
- ".h",
7037
- ".hpp",
7038
- ".swift",
7039
- ".scala",
7040
- ".sh"
7041
- ]);
7042
8306
  const BUILT_IN_CHECK = {
7043
8307
  name: "Built-in rules",
7044
8308
  detail: "secrets, risky APIs, sensitive paths and GitLab CI"
@@ -7170,18 +8434,7 @@ function coverageGaps(files, ignoredCount) {
7170
8434
  check: `Risk rules on ${ignoredCount} ${ignoredCount === 1 ? "file" : "files"}`,
7171
8435
  reason: `excluded by "ignore" in ${WALKDIFF_CONFIG_PATH}`
7172
8436
  });
7173
- const uncovered = [...new Set(files.map((file) => extname(file.diff.path)).filter((extension) => UNCOVERED_CODE_EXTENSIONS.has(extension)))];
7174
- if (uncovered.length > 0) {
7175
- gaps.push({
7176
- check: `Dangerous-API rules for ${uncovered.join(", ")} files`,
7177
- reason: "rules exist only for Rust, TypeScript/JavaScript and Python"
7178
- });
7179
- gaps.push({
7180
- check: `Public API checks for ${uncovered.join(", ")} files`,
7181
- reason: "they read syntax, which the engine parses only for Rust, TypeScript/JavaScript and Python"
7182
- });
7183
- }
7184
- return gaps;
8437
+ return [...gaps, ...languageGaps(files.map((file) => file.diff.path))];
7185
8438
  }
7186
8439
  function byImportance(a, b) {
7187
8440
  return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || Number(isSecurityFinding(b)) - Number(isSecurityFinding(a)) || (a.location?.path ?? "").localeCompare(b.location?.path ?? "") || (a.location?.line ?? 0) - (b.location?.line ?? 0);
@@ -7273,8 +8526,8 @@ function compareUnits(files) {
7273
8526
  change: {
7274
8527
  kind: UnitChangeKind.Renamed,
7275
8528
  previousName: from.definition.name,
7276
- before: from.definition.snapshot,
7277
- after: to.definition.snapshot
8529
+ before: from.definition.wholeSnapshot,
8530
+ after: to.definition.wholeSnapshot
7278
8531
  }
7279
8532
  });
7280
8533
  for (const [from, to] of takeMatches(removed, added, isMove)) reportMove(report, from, to, MoveEdits.None);
@@ -7283,14 +8536,14 @@ function compareUnits(files) {
7283
8536
  ...describe(definition),
7284
8537
  change: {
7285
8538
  kind: UnitChangeKind.Added,
7286
- after: definition.snapshot
8539
+ after: definition.wholeSnapshot
7287
8540
  }
7288
8541
  });
7289
8542
  for (const { path, definition } of removed) report(path, {
7290
8543
  ...describe(definition),
7291
8544
  change: {
7292
8545
  kind: UnitChangeKind.Removed,
7293
- before: definition.snapshot
8546
+ before: definition.wholeSnapshot
7294
8547
  }
7295
8548
  });
7296
8549
  for (const units of unitsByPath.values()) units.sort(byPositionInFile);
@@ -7310,7 +8563,7 @@ function reportMove(report, from, to, edits) {
7310
8563
  kind: UnitChangeKind.MovedOut,
7311
8564
  to: locationOf(to),
7312
8565
  edited,
7313
- before: before.snapshot
8566
+ before: before.wholeSnapshot
7314
8567
  }
7315
8568
  });
7316
8569
  report(to.path, {
@@ -7320,8 +8573,8 @@ function reportMove(report, from, to, edits) {
7320
8573
  kind: UnitChangeKind.MovedIn,
7321
8574
  from: locationOf(from),
7322
8575
  edited,
7323
- before: before.snapshot,
7324
- after: after.snapshot
8576
+ before: before.wholeSnapshot,
8577
+ after: after.wholeSnapshot
7325
8578
  }
7326
8579
  });
7327
8580
  }
@@ -7521,9 +8774,18 @@ function previousMetrics(definition, beforeByKey, beforeByBody) {
7521
8774
  const NOT_CALLABLE = /* @__PURE__ */ new Set([
7522
8775
  UnitKind.ModuleScope,
7523
8776
  UnitKind.Impl,
7524
- UnitKind.Module
8777
+ UnitKind.Module,
8778
+ UnitKind.TestSuite,
8779
+ UnitKind.Test,
8780
+ UnitKind.TestHook
8781
+ ]);
8782
+ const CODE_KINDS = /* @__PURE__ */ new Set([
8783
+ UnitKind.Function,
8784
+ UnitKind.Method,
8785
+ UnitKind.TestSuite,
8786
+ UnitKind.Test,
8787
+ UnitKind.TestHook
7525
8788
  ]);
7526
- const FUNCTION_KINDS = /* @__PURE__ */ new Set([UnitKind.Function, UnitKind.Method]);
7527
8789
  const RUST_PATH_SEPARATOR = "::";
7528
8790
  const ReadingGroup = {
7529
8791
  ModuleScope: 0,
@@ -7600,7 +8862,7 @@ function orderUnits(units, calls) {
7600
8862
  function readingGroup(unit) {
7601
8863
  if (unit.kind === UnitKind.ModuleScope) return ReadingGroup.ModuleScope;
7602
8864
  if (!isBehaviourChange(unit.change)) return ReadingGroup.Quiet;
7603
- return FUNCTION_KINDS.has(unit.kind) ? ReadingGroup.Functions : ReadingGroup.Definitions;
8865
+ return CODE_KINDS.has(unit.kind) ? ReadingGroup.Functions : ReadingGroup.Definitions;
7604
8866
  }
7605
8867
  /** `Other::new` is not a call to `Size::new`, though both are named `new`. */
7606
8868
  function pathNamesAnotherType(call, callee) {
@@ -8736,6 +9998,78 @@ async function describeChecks(run = runScannerProcess) {
8736
9998
  function firstExisting(candidates, exists = existsSync) {
8737
9999
  return candidates.find((path) => exists(path)) ?? candidates.at(-1) ?? "";
8738
10000
  }
10001
+ // packages/engine/src/risk/scanners/downloadWithRetries.ts
10002
+ const DOWNLOAD_TIMEOUT_MS = 12e4;
10003
+ const RETRY_DELAYS_MS = [
10004
+ 2e3,
10005
+ 8e3,
10006
+ 2e4
10007
+ ];
10008
+ const TOO_MANY_REQUESTS = 429;
10009
+ const FIRST_SERVER_ERROR = 500;
10010
+ const MS_PER_SECOND = 1e3;
10011
+ const Outcome = {
10012
+ Done: "done",
10013
+ TryAgain: "tryAgain",
10014
+ Failed: "failed"
10015
+ };
10016
+ /**
10017
+ * Downloads `url`, trying again after a server error, a rate limit or a dropped connection.
10018
+ *
10019
+ * # Errors
10020
+ *
10021
+ * Rejects on any other HTTP error, on a timeout, or when the last try also fails.
10022
+ */
10023
+ async function downloadWithRetries(url, deps) {
10024
+ for (const delayMs of RETRY_DELAYS_MS) {
10025
+ const attempt = await downloadOnce(url, deps);
10026
+ if (attempt.outcome !== Outcome.TryAgain) return settled(attempt);
10027
+ deps.log(`Downloading ${url} failed (${attempt.problem}). Trying again in ${delayMs / MS_PER_SECOND} seconds.`);
10028
+ await deps.wait(delayMs);
10029
+ }
10030
+ const last = await downloadOnce(url, deps);
10031
+ if (last.outcome !== Outcome.TryAgain) return settled(last);
10032
+ throw new Error(`${url} failed ${RETRY_DELAYS_MS.length + 1} times, last with: ${last.problem}`);
10033
+ }
10034
+ function settled(attempt) {
10035
+ if (attempt.outcome === Outcome.Failed) throw attempt.error;
10036
+ return attempt.bytes;
10037
+ }
10038
+ async function downloadOnce(url, deps) {
10039
+ try {
10040
+ const response = await deps.fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
10041
+ if (isWorthRetrying(response.status)) return {
10042
+ outcome: Outcome.TryAgain,
10043
+ problem: `responded ${response.status}`
10044
+ };
10045
+ if (!response.ok) return {
10046
+ outcome: Outcome.Failed,
10047
+ error: /* @__PURE__ */ new Error(`${url} responded ${response.status}`)
10048
+ };
10049
+ return {
10050
+ outcome: Outcome.Done,
10051
+ bytes: Buffer.from(await response.arrayBuffer())
10052
+ };
10053
+ } catch (error) {
10054
+ return failedAttempt(error);
10055
+ }
10056
+ }
10057
+ function isWorthRetrying(status) {
10058
+ return status === TOO_MANY_REQUESTS || status >= FIRST_SERVER_ERROR;
10059
+ }
10060
+ function failedAttempt(error) {
10061
+ if (error instanceof TypeError) return {
10062
+ outcome: Outcome.TryAgain,
10063
+ problem: connectionProblem(error)
10064
+ };
10065
+ return {
10066
+ outcome: Outcome.Failed,
10067
+ error: error instanceof Error ? error : new Error(String(error))
10068
+ };
10069
+ }
10070
+ function connectionProblem(error) {
10071
+ return error.cause instanceof Error ? `${error.message}: ${error.cause.message}` : error.message;
10072
+ }
8739
10073
  // packages/engine/src/risk/scanners/installScanners.ts
8740
10074
  const ArchiveKind = {
8741
10075
  TarGz: "tarGz",
@@ -8879,7 +10213,6 @@ const SEMGREP_COMPLETE_MARKER = ".complete";
8879
10213
  const SEMGREP_UNSUPPORTED_PLATFORMS = /* @__PURE__ */ new Set(["win32"]);
8880
10214
  const HAS_SUPPORTED_PYTHON = "import sys; sys.exit(sys.version_info < (3, 10))";
8881
10215
  const NEEDS_PYTHON = "it needs Python 3.10 or later, with the venv module";
8882
- const DOWNLOAD_TIMEOUT_MS = 12e4;
8883
10216
  const COMMAND_TIMEOUT_MS = 6e5;
8884
10217
  const EXECUTABLE_MODE = 493;
8885
10218
  const LOCK_HASH_CHARS = 12;
@@ -9008,11 +10341,6 @@ async function installSemgrep(tools, deps) {
9008
10341
  await writeFile(marker, "");
9009
10342
  return executable;
9010
10343
  }
9011
- async function download(url) {
9012
- const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
9013
- if (!response.ok) throw new Error(`${url} responded ${response.status}`);
9014
- return Buffer.from(await response.arrayBuffer());
9015
- }
9016
10344
  function run(command, args) {
9017
10345
  return new Promise((resolvePromise, reject) => {
9018
10346
  execFile(command, [...args], {
@@ -9026,6 +10354,11 @@ function run(command, args) {
9026
10354
  }
9027
10355
  /** Installs for this machine, into the folder scanners are run from. Quick when they're all there. */
9028
10356
  function installScannersHere(log = console.log) {
10357
+ const download = (url) => downloadWithRetries(url, {
10358
+ fetch,
10359
+ wait: async (ms) => void await setTimeout(ms),
10360
+ log
10361
+ });
9029
10362
  return installScanners(MANAGED_SCANNERS_ROOT, {
9030
10363
  download,
9031
10364
  run,