weavatrix 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +146 -0
- package/bin/weavatrix-mcp.mjs +6 -0
- package/package.json +50 -0
- package/skill/SKILL.md +56 -0
- package/src/analysis/coverage-reports.js +232 -0
- package/src/analysis/dead-check.js +136 -0
- package/src/analysis/dep-check.js +310 -0
- package/src/analysis/dep-rules.js +221 -0
- package/src/analysis/duplicates-worker.js +11 -0
- package/src/analysis/duplicates.compute.js +215 -0
- package/src/analysis/duplicates.js +15 -0
- package/src/analysis/duplicates.run.js +51 -0
- package/src/analysis/duplicates.tokenize.js +182 -0
- package/src/analysis/endpoints.js +156 -0
- package/src/analysis/findings.js +52 -0
- package/src/analysis/graph-analysis.aggregate.js +280 -0
- package/src/analysis/graph-analysis.js +7 -0
- package/src/analysis/graph-analysis.refs.js +146 -0
- package/src/analysis/graph-analysis.summaries.js +62 -0
- package/src/analysis/internal-audit.collect.js +117 -0
- package/src/analysis/internal-audit.js +9 -0
- package/src/analysis/internal-audit.reach.js +47 -0
- package/src/analysis/internal-audit.run.js +189 -0
- package/src/analysis/manifests.js +169 -0
- package/src/analysis/source-complexity.ast.js +97 -0
- package/src/analysis/source-complexity.constants.js +55 -0
- package/src/analysis/source-complexity.js +14 -0
- package/src/analysis/source-complexity.report.js +76 -0
- package/src/analysis/source-complexity.walk.js +174 -0
- package/src/build-graph.js +102 -0
- package/src/config.js +5 -0
- package/src/graph/build-worker.js +30 -0
- package/src/graph/builder/lang-csharp.js +40 -0
- package/src/graph/builder/lang-css.js +29 -0
- package/src/graph/builder/lang-go.js +53 -0
- package/src/graph/builder/lang-html.js +29 -0
- package/src/graph/builder/lang-java.js +29 -0
- package/src/graph/builder/lang-js.js +168 -0
- package/src/graph/builder/lang-python.js +78 -0
- package/src/graph/builder/lang-rust.js +45 -0
- package/src/graph/builder/spec-pkg.js +87 -0
- package/src/graph/graph-filter.js +44 -0
- package/src/graph/internal-builder.build.js +217 -0
- package/src/graph/internal-builder.js +12 -0
- package/src/graph/internal-builder.langs.js +86 -0
- package/src/graph/internal-builder.resolvers.js +116 -0
- package/src/graph/layout.js +35 -0
- package/src/infra/infra-items.js +255 -0
- package/src/infra/infra-registry.js +184 -0
- package/src/infra/infra.detect.js +119 -0
- package/src/infra/infra.js +38 -0
- package/src/infra/infra.match.js +102 -0
- package/src/infra/infra.scan.js +93 -0
- package/src/mcp/catalog.mjs +68 -0
- package/src/mcp/graph-context.mjs +276 -0
- package/src/mcp/tools-actions.mjs +132 -0
- package/src/mcp/tools-graph.mjs +274 -0
- package/src/mcp/tools-health.mjs +209 -0
- package/src/mcp/tools-impact.mjs +189 -0
- package/src/mcp-rg.mjs +51 -0
- package/src/mcp-server.mjs +171 -0
- package/src/mcp-source-tools.mjs +139 -0
- package/src/process.js +77 -0
- package/src/scan/discover.inventory.js +78 -0
- package/src/scan/discover.js +5 -0
- package/src/scan/discover.list.js +79 -0
- package/src/scan/discover.stack.js +227 -0
- package/src/scan/search.core.js +24 -0
- package/src/scan/search.git.js +102 -0
- package/src/scan/search.js +9 -0
- package/src/scan/search.node.js +83 -0
- package/src/scan/search.preview.js +49 -0
- package/src/scan/search.rg.js +145 -0
- package/src/security/advisory-store.js +177 -0
- package/src/security/installed.js +247 -0
- package/src/security/malware-file-heuristics.js +121 -0
- package/src/security/malware-heuristics.exclusions.js +134 -0
- package/src/security/malware-heuristics.js +15 -0
- package/src/security/malware-heuristics.roots.js +142 -0
- package/src/security/malware-heuristics.scan.js +87 -0
- package/src/security/malware-heuristics.sweep.js +122 -0
- package/src/security/malware-scoring.js +84 -0
- package/src/security/match.js +85 -0
- package/src/security/registry-sig.classify.js +136 -0
- package/src/security/registry-sig.js +18 -0
- package/src/security/registry-sig.rules.js +188 -0
- package/src/security/typosquat.js +72 -0
- package/src/util.js +27 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// duplicates.compute.js — fragment extraction, inverted-index pairing, and the computeDuplicates
|
|
2
|
+
// pipeline (split from duplicates.js; see the facade there for the full algorithm overview).
|
|
3
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
4
|
+
import { join, extname } from "node:path";
|
|
5
|
+
import { isTestPath } from "../graph/graph-filter.js";
|
|
6
|
+
import { stripNonCode, bodyEndLineCount, tokenize, fingerprints, extractLargeStrings } from "./duplicates.tokenize.js";
|
|
7
|
+
|
|
8
|
+
const FLOOR_TOKENS = 30; // fragments below this never enter the index (UI slider min)
|
|
9
|
+
const FLOOR_SIM = 0.5; // pairs below this are not reported (UI slider min)
|
|
10
|
+
const MAX_BODY_LINES = 400;
|
|
11
|
+
// File types with no code SYMBOLS to fragment (stylesheets, markup, docs, single-file components). The
|
|
12
|
+
// user still wants them clone-checked ("check the frontend / md too"), so each is sliced into fixed line
|
|
13
|
+
// WINDOWS and each window is fingerprinted like a function body — a duplicated CSS rule block / HTML
|
|
14
|
+
// section / doc passage then clones the same way.
|
|
15
|
+
const WINDOW_EXTS = /\.(css|scss|sass|less|styl|html?|md|markdown|mdx|vue|svelte|astro)$/i;
|
|
16
|
+
const WINDOW_LINES = 24; // non-overlapping block size for windowed files
|
|
17
|
+
// Asset files are DEDUP-ONLY — they are NOT put in the code graph (that would score md/css as fake
|
|
18
|
+
// "methods" in Health and clutter the GUI board), so the clone scanner finds them by walking the repo.
|
|
19
|
+
const WALK_SKIP = new Set(["node_modules", ".git", "dist", "build", "coverage", "vendor", "weavatrix-graphs", ".next", "out", "__pycache__", ".venv", "venv", "site-packages"]);
|
|
20
|
+
const MAX_ASSET_FILES = 4000;
|
|
21
|
+
function walkAssets(root, dir, acc, depth) {
|
|
22
|
+
if (depth > 40 || acc.length >= MAX_ASSET_FILES) return acc;
|
|
23
|
+
let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return acc; }
|
|
24
|
+
for (const e of entries) {
|
|
25
|
+
if (acc.length >= MAX_ASSET_FILES) break;
|
|
26
|
+
if (e.name.startsWith(".") || WALK_SKIP.has(e.name)) continue;
|
|
27
|
+
const full = join(dir, e.name);
|
|
28
|
+
if (e.isDirectory()) walkAssets(root, full, acc, depth + 1);
|
|
29
|
+
else if (WINDOW_EXTS.test(e.name)) acc.push(full.slice(root.length + 1).replace(/\\/g, "/"));
|
|
30
|
+
}
|
|
31
|
+
return acc;
|
|
32
|
+
}
|
|
33
|
+
// Fingerprints shared by MORE than this many fragments are ubiquitous boilerplate and are excluded
|
|
34
|
+
// from BOTH the shared count AND the union (so jaccard stays honest — see pairsForMode). Set well
|
|
35
|
+
// above realistic clone multiplicity: N byte-identical copies each put all their fingerprints in
|
|
36
|
+
// buckets of size N, so the cap must exceed N or the whole clone family is invisible. 120 covers all
|
|
37
|
+
// but pathological mass-duplication; the O(n²) pair work per bucket stays bounded by it.
|
|
38
|
+
const BUCKET_CAP = 120;
|
|
39
|
+
// A clone must share at least this many DISTINCT (non-ubiquitous) fingerprints. Winnowing collapses a
|
|
40
|
+
// UNIFORM repetitive body (a constant table where every line is `KEY: 'VALUE',` → renamed `I: <str>`) to a
|
|
41
|
+
// handful of fingerprints, so two UNRELATED such tables hit 100% renamed Jaccard on ~3-6 shared fingerprints
|
|
42
|
+
// — "same shape, zero shared content". Requiring real shared evidence drops those false positives while a
|
|
43
|
+
// genuine clone (which shares dozens of fingerprints) is untouched.
|
|
44
|
+
const MIN_SHARED_FP = 8;
|
|
45
|
+
|
|
46
|
+
// Same-name symbols across DIFFERENT files — the semantic complement to token clones. A token clone
|
|
47
|
+
// says "same body"; a name twin with LOW similarity says "same name, different behavior" — the
|
|
48
|
+
// drift-hazard class of duplicate (three divergent uniqueStrings() implementations) that jaccard
|
|
49
|
+
// ranks too low to surface. OOP-generic lifecycle names are stoplisted; interface implementations
|
|
50
|
+
// still appear, so the caller's report keeps neutral wording.
|
|
51
|
+
const TWIN_STOP = new Set(["constructor", "tostring", "valueof", "dispose", "close", "render", "setup", "teardown", "initialize", "destroy", "connect", "disconnect", "update", "reset", "clear", "create", "handle", "execute", "invoke", "main", "start", "stop", "build", "parse", "value", "index"]);
|
|
52
|
+
function computeNameTwins(frags) {
|
|
53
|
+
const byName = new Map();
|
|
54
|
+
frags.forEach((f, i) => {
|
|
55
|
+
if (f.kind === "string") return;
|
|
56
|
+
const name = String(f.label || "").trim().replace(/\(\)$/, "");
|
|
57
|
+
if (name.length < 5 || !/^[A-Za-z_$][\w$]*$/.test(name) || TWIN_STOP.has(name.toLowerCase())) return;
|
|
58
|
+
const key = name.toLowerCase();
|
|
59
|
+
let a = byName.get(key); if (!a) byName.set(key, (a = []));
|
|
60
|
+
a.push(i);
|
|
61
|
+
});
|
|
62
|
+
const jac = (A, B) => { let inter = 0; for (const h of A) if (B.has(h)) inter++; const u = A.size + B.size - inter; return u ? inter / u : 0; };
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const idxs of byName.values()) {
|
|
65
|
+
const files = new Set(idxs.map((i) => frags[i].file));
|
|
66
|
+
if (files.size < 2 || idxs.length > 12) continue; // single-file overloads / framework-name explosions
|
|
67
|
+
let simMin = 1, simMax = 0;
|
|
68
|
+
for (let a = 0; a < idxs.length; a++) for (let b = a + 1; b < idxs.length; b++) {
|
|
69
|
+
if (frags[idxs[a]].file === frags[idxs[b]].file) continue;
|
|
70
|
+
const s = jac(frags[idxs[a]].fp.renamed, frags[idxs[b]].fp.renamed);
|
|
71
|
+
if (s < simMin) simMin = s;
|
|
72
|
+
if (s > simMax) simMax = s;
|
|
73
|
+
}
|
|
74
|
+
out.push({
|
|
75
|
+
label: String(frags[idxs[0]].label || "").replace(/\(\)$/, ""), members: idxs, files: files.size,
|
|
76
|
+
simMin: Math.round(simMin * 100), simMax: Math.round(simMax * 100),
|
|
77
|
+
tokens: idxs.reduce((n, i) => n + frags[i].n, 0),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return out.sort((x, y) => y.tokens - x.tokens).slice(0, 200);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function pairsForMode(frags, mode) {
|
|
84
|
+
const index = new Map();
|
|
85
|
+
frags.forEach((f, i) => { for (const h of f.fp[mode]) { let a = index.get(h); if (!a) index.set(h, (a = [])); a.push(i); } });
|
|
86
|
+
// eff[i] = count of i's fingerprints that sit in NON-ubiquitous buckets. Jaccard's numerator (shared)
|
|
87
|
+
// and denominator (union) are BOTH computed over this same restricted set, so excluding a boilerplate
|
|
88
|
+
// fingerprint never deflates similarity — two real clones sharing a widely-repeated preamble still
|
|
89
|
+
// pair at 100% on their unique bodies, and the sim is a true jaccard, not an under-count.
|
|
90
|
+
const eff = new Array(frags.length).fill(0);
|
|
91
|
+
const shared = new Map();
|
|
92
|
+
for (const arr of index.values()) {
|
|
93
|
+
if (arr.length > BUCKET_CAP) continue; // ubiquitous k-gram → excluded from count AND size (both sides)
|
|
94
|
+
for (const idx of arr) eff[idx]++;
|
|
95
|
+
for (let a = 0; a < arr.length; a++) for (let b = a + 1; b < arr.length; b++) {
|
|
96
|
+
const key = arr[a] * 1000000 + arr[b]; // frag count is bounded way below 1e6
|
|
97
|
+
shared.set(key, (shared.get(key) || 0) + 1);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const pairs = [];
|
|
101
|
+
for (const [key, count] of shared) {
|
|
102
|
+
const i = Math.floor(key / 1000000), j = key % 1000000;
|
|
103
|
+
const union = eff[i] + eff[j] - count;
|
|
104
|
+
const sim = union > 0 ? count / union : 0;
|
|
105
|
+
if (sim >= FLOOR_SIM && count >= MIN_SHARED_FP) pairs.push([i, j, Math.round(sim * 100)]);
|
|
106
|
+
}
|
|
107
|
+
return pairs;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Parse "L<line>" graph symbol locations into per-file ordered symbol lists.
|
|
111
|
+
function symbolRanges(graph) {
|
|
112
|
+
const byFile = new Map();
|
|
113
|
+
for (const n of graph.nodes || []) {
|
|
114
|
+
if (!n.source_file || !String(n.id || "").includes("#")) continue;
|
|
115
|
+
const line = Number((String(n.source_location || "").match(/L(\d+)/) || [])[1] || 0);
|
|
116
|
+
if (!line) continue;
|
|
117
|
+
let arr = byFile.get(n.source_file);
|
|
118
|
+
if (!arr) byFile.set(n.source_file, (arr = []));
|
|
119
|
+
arr.push({ id: n.id, label: n.label || n.id, line });
|
|
120
|
+
}
|
|
121
|
+
for (const arr of byFile.values()) arr.sort((a, b) => a.line - b.line);
|
|
122
|
+
return byFile;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function computeDuplicates(repoPath, graphJsonPath, opts = {}) {
|
|
126
|
+
const includeStrings = !!opts.includeStrings;
|
|
127
|
+
const graph = JSON.parse(readFileSync(graphJsonPath, "utf8"));
|
|
128
|
+
const byFile = symbolRanges(graph);
|
|
129
|
+
// total symbol nodes in the graph — 0 means a file-only graph (built by an older builder before
|
|
130
|
+
// symbol extraction, or a stale graph): clone detection has nothing to work with, and the UI must
|
|
131
|
+
// say "rebuild the graph" instead of the misleading "no clones at these thresholds".
|
|
132
|
+
let graphSymbols = 0;
|
|
133
|
+
for (const arr of byFile.values()) graphSymbols += arr.length;
|
|
134
|
+
const frags = [];
|
|
135
|
+
for (const [file, syms] of byFile) {
|
|
136
|
+
const full = join(repoPath, file);
|
|
137
|
+
let lines;
|
|
138
|
+
try { lines = readFileSync(full, "utf8").split(/\r?\n/); } catch { continue; }
|
|
139
|
+
const py = /\.py$/i.test(file);
|
|
140
|
+
for (let i = 0; i < syms.length; i++) {
|
|
141
|
+
const start = syms[i].line;
|
|
142
|
+
// hard cap first (next symbol, or EOF, whichever comes first, ≤ MAX_BODY_LINES) …
|
|
143
|
+
const hardEnd = Math.min(i + 1 < syms.length ? syms[i + 1].line - 1 : lines.length, start + MAX_BODY_LINES);
|
|
144
|
+
if (hardEnd - start < 2) continue; // one-liners can't be meaningful clones
|
|
145
|
+
// … then shrink to where the construct actually closes, so the last symbol doesn't absorb
|
|
146
|
+
// trailing module-level code (module.exports tables, main() calls) up to EOF.
|
|
147
|
+
const bodyLines = lines.slice(start - 1, hardEnd);
|
|
148
|
+
const body = bodyLines.slice(0, bodyEndLineCount(bodyLines, py));
|
|
149
|
+
const end = start + body.length - 1;
|
|
150
|
+
if (end - start < 2) continue;
|
|
151
|
+
const toks = tokenize(stripNonCode(body.join("\n"), py));
|
|
152
|
+
if (toks.strict.length < FLOOR_TOKENS) continue;
|
|
153
|
+
frags.push({
|
|
154
|
+
id: syms[i].id, label: syms[i].label, file, start, end,
|
|
155
|
+
n: toks.strict.length,
|
|
156
|
+
test: isTestPath(file),
|
|
157
|
+
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
// ---- opt-in: large multi-line string literals as their own fragments. The code pass above strips
|
|
161
|
+
// string bodies (correctly — content isn't code), which makes embedded DSL templates (inline
|
|
162
|
+
// C#/SQL/PowerShell) invisible to clone detection. Tokenized RAW: the content IS the payload.
|
|
163
|
+
if (includeStrings) {
|
|
164
|
+
const base = file.split("/").pop();
|
|
165
|
+
const pushStr = (startLine, endLine, content) => {
|
|
166
|
+
const toks = tokenize(content);
|
|
167
|
+
if (toks.strict.length < FLOOR_TOKENS) return;
|
|
168
|
+
frags.push({
|
|
169
|
+
id: `${file}#str@${startLine}`, label: `${base}:${startLine} ~${endLine - startLine + 1}-line string`,
|
|
170
|
+
file, start: startLine, end: endLine, n: toks.strict.length, test: isTestPath(file), kind: "string",
|
|
171
|
+
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
for (const str of extractLargeStrings(lines.join("\n"), { py, cs: /\.cs$/i.test(file) })) {
|
|
175
|
+
const strLines = str.content.split(/\r?\n/).slice(0, MAX_BODY_LINES);
|
|
176
|
+
// A SECTION shared between two big templates dilutes below the similarity floor when the whole
|
|
177
|
+
// literals are compared (70 shared lines inside 220- and 107-line strings ≈ 27% jaccard). Big
|
|
178
|
+
// literals therefore get the same WINDOW treatment as CSS/HTML files; small ones stay whole.
|
|
179
|
+
if (strLines.length <= WINDOW_LINES * 2) {
|
|
180
|
+
pushStr(str.start, str.start + strLines.length - 1, strLines.join("\n"));
|
|
181
|
+
} else {
|
|
182
|
+
for (let off = 0; off < strLines.length; off += WINDOW_LINES) {
|
|
183
|
+
const chunk = strLines.slice(off, off + WINDOW_LINES);
|
|
184
|
+
if (chunk.length < 3) break;
|
|
185
|
+
pushStr(str.start + off, str.start + off + chunk.length - 1, chunk.join("\n"));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// ---- windowed fragments for symbol-less file types (CSS/HTML/MD/…), found by walking the repo (NOT the
|
|
192
|
+
// graph — assets are dedup-only). Each file is sliced into WINDOW_LINES blocks and fingerprinted.
|
|
193
|
+
const symFiles = new Set(byFile.keys());
|
|
194
|
+
for (const file of walkAssets(repoPath, repoPath, [], 0)) {
|
|
195
|
+
if (symFiles.has(file)) continue;
|
|
196
|
+
let lines;
|
|
197
|
+
try { lines = readFileSync(join(repoPath, file), "utf8").split(/\r?\n/); } catch { continue; }
|
|
198
|
+
for (let start = 1; start <= lines.length; start += WINDOW_LINES) {
|
|
199
|
+
const end = Math.min(start + WINDOW_LINES - 1, lines.length);
|
|
200
|
+
if (end - start < 2) continue;
|
|
201
|
+
const toks = tokenize(stripNonCode(lines.slice(start - 1, end).join("\n"), false));
|
|
202
|
+
if (toks.strict.length < FLOOR_TOKENS) continue;
|
|
203
|
+
frags.push({
|
|
204
|
+
id: `${file}#win@${start}`, label: `${file.split("/").pop()}:${start}-${end}`, file, start, end,
|
|
205
|
+
n: toks.strict.length, test: isTestPath(file),
|
|
206
|
+
fp: { strict: fingerprints(toks.strict), renamed: fingerprints(toks.renamed) },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const modes = { strict: pairsForMode(frags, "strict"), renamed: pairsForMode(frags, "renamed") };
|
|
211
|
+
const nameTwins = opts.nameTwins ? computeNameTwins(frags) : null;
|
|
212
|
+
// fp sets are worker-internal — strip them from the payload that crosses the thread boundary
|
|
213
|
+
const slim = frags.map(({ fp, ...rest }) => rest);
|
|
214
|
+
return { ok: true, frags: slim, modes, ...(nameTwins ? { nameTwins } : {}), graphSymbols, floors: { tokens: FLOOR_TOKENS, sim: FLOOR_SIM * 100 } };
|
|
215
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// duplicates.js — content-based clone detection over the repo's OWN graph.json symbols (the Health
|
|
2
|
+
// tab's engine). MOSS-style pipeline: symbol bodies (line ranges from the graph) → strip comments &
|
|
3
|
+
// string bodies → tokenize → k-gram rolling hashes → winnowing fingerprints → inverted index (no
|
|
4
|
+
// O(n²) all-pairs) → jaccard similarity. BOTH normalization modes are computed in one pass so every
|
|
5
|
+
// UI knob (similarity %, min size, strict/renamed) filters instantly on the renderer side:
|
|
6
|
+
// strict — identifiers kept: only literal copy-paste (Type-1 clones)
|
|
7
|
+
// renamed — identifiers canonicalized to "I": catches copy-paste-then-rename (Type-2 clones)
|
|
8
|
+
// Pairs are reported down to the FLOOR values; the renderer slices from there upward.
|
|
9
|
+
//
|
|
10
|
+
// Facade: the implementation lives in the sibling modules —
|
|
11
|
+
// duplicates.tokenize.js — stripping, body-end detection, tokenization, winnowing fingerprints
|
|
12
|
+
// duplicates.compute.js — fragment extraction, inverted-index pairing, computeDuplicates
|
|
13
|
+
// duplicates.run.js — worker offload + mtime cache (runDuplicates entry)
|
|
14
|
+
export { computeDuplicates } from "./duplicates.compute.js";
|
|
15
|
+
export { runDuplicates } from "./duplicates.run.js";
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// duplicates.run.js — the repos:duplicates entry point (split from duplicates.js): worker-thread
|
|
2
|
+
// offload with in-process fallback, cached per (repo, graph.json mtime).
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Worker } from "node:worker_threads";
|
|
6
|
+
import { graphOutDirForRepo } from "../graph/layout.js";
|
|
7
|
+
import { computeDuplicates } from "./duplicates.compute.js";
|
|
8
|
+
|
|
9
|
+
function computeInWorker(repoPath, graphJsonPath) {
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
let worker;
|
|
12
|
+
try {
|
|
13
|
+
worker = new Worker(new URL("./duplicates-worker.js", import.meta.url), { workerData: { repoPath, graphJsonPath } });
|
|
14
|
+
} catch (e) {
|
|
15
|
+
reject(Object.assign(e, { workerStartFailed: true }));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
let settled = false;
|
|
19
|
+
const done = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
20
|
+
worker.once("message", (msg) => done(resolve, msg));
|
|
21
|
+
worker.once("error", (e) => done(reject, Object.assign(e, { workerStartFailed: true })));
|
|
22
|
+
worker.once("exit", (code) => { if (code !== 0) done(reject, Object.assign(new Error(`duplicates worker exited with code ${code}`), { workerStartFailed: true })); });
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// repos:duplicates entry — cached per (repo, graph.json mtime): re-running with an unchanged graph is
|
|
27
|
+
// free. `force` (the UI's ↻ rescan) bypasses the cache: fragment BODIES are read from live source, so a
|
|
28
|
+
// source edit that didn't rebuild the graph (same mtime) must still be re-scanned on demand.
|
|
29
|
+
const _cache = new Map();
|
|
30
|
+
export async function runDuplicates(repoPath, force = false) {
|
|
31
|
+
const repo = String(repoPath || "");
|
|
32
|
+
if (!repo || !existsSync(repo)) return { ok: false, error: "Repo path not found" };
|
|
33
|
+
const graphJsonPath = join(graphOutDirForRepo(repo), "graph.json");
|
|
34
|
+
if (!existsSync(graphJsonPath)) {
|
|
35
|
+
return { ok: false, needsGraph: true, error: "No graph yet — build the Relations graph first (↻ on the Relations tab)" };
|
|
36
|
+
}
|
|
37
|
+
let mtime = 0;
|
|
38
|
+
try { mtime = statSync(graphJsonPath).mtimeMs; } catch { /* treat as uncached */ }
|
|
39
|
+
const cached = _cache.get(repo);
|
|
40
|
+
if (!force && cached && cached.mtime === mtime) return cached.result;
|
|
41
|
+
let result;
|
|
42
|
+
try {
|
|
43
|
+
result = await computeInWorker(repo, graphJsonPath);
|
|
44
|
+
} catch (e) {
|
|
45
|
+
if (!e || !e.workerStartFailed) return { ok: false, error: e.message || String(e) };
|
|
46
|
+
try { result = computeDuplicates(repo, graphJsonPath); } // in-process fallback (exotic packaging)
|
|
47
|
+
catch (e2) { return { ok: false, error: e2.message || String(e2) }; }
|
|
48
|
+
}
|
|
49
|
+
if (result && result.ok) _cache.set(repo, { mtime, result });
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// duplicates.tokenize.js — lexical layer of the clone detector (split from duplicates.js): comment &
|
|
2
|
+
// string stripping, body-end detection, strict/renamed tokenization, and winnowing fingerprints.
|
|
3
|
+
|
|
4
|
+
const K = 8; // k-gram length (tokens)
|
|
5
|
+
const W = 4; // winnowing window → guaranteed detection of matches ≥ K+W-1 tokens
|
|
6
|
+
const STRLIT = String.fromCharCode(0); // opaque-literal sentinel for every string/regex body: a NUL
|
|
7
|
+
// its own class (never an identifier "I" nor a number "N"), so a literal can
|
|
8
|
+
// never masquerade as code in either mode
|
|
9
|
+
|
|
10
|
+
const KEYWORDS = new Set(("if else for while do switch case break continue return function const let var new class extends async await try catch finally throw import from export default typeof instanceof in of delete void yield static get set this super null undefined true false def elif except lambda pass raise with as is not and or None True False func go defer chan map range struct interface type package nil err string int bool byte float64 public private protected final void long double boolean").split(" "));
|
|
11
|
+
|
|
12
|
+
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
13
|
+
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
14
|
+
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
15
|
+
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
16
|
+
// regex and ate the rest of the line.
|
|
17
|
+
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
18
|
+
|
|
19
|
+
// Replace comments with nothing and string/regex BODIES with the sentinel, so their contents never
|
|
20
|
+
// count as code. Handles Python triple-quoted docstrings (embedded quotes no longer desync the scan)
|
|
21
|
+
// and JS regex literals (a quote inside /['"]/ no longer opens a phantom string).
|
|
22
|
+
export function stripNonCode(text, py) {
|
|
23
|
+
let out = "", i = 0, prevSig = "";
|
|
24
|
+
const s = String(text || "");
|
|
25
|
+
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
26
|
+
while (i < s.length) {
|
|
27
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
28
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
29
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
30
|
+
i += 3;
|
|
31
|
+
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
32
|
+
i += 3; push(` ${STRLIT} `); continue;
|
|
33
|
+
}
|
|
34
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
35
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
36
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
37
|
+
i++; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
38
|
+
while (i < s.length && s[i] !== "\n") {
|
|
39
|
+
const c = s[i];
|
|
40
|
+
if (c === "\\") { i += 2; continue; }
|
|
41
|
+
if (c === "[") inClass = true;
|
|
42
|
+
else if (c === "]") inClass = false;
|
|
43
|
+
else if (c === "/" && !inClass) { i++; break; }
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
47
|
+
push(` ${STRLIT} `); continue;
|
|
48
|
+
}
|
|
49
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
50
|
+
const q = ch; i++;
|
|
51
|
+
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
52
|
+
i++; push(` ${STRLIT} `); continue;
|
|
53
|
+
}
|
|
54
|
+
push(ch); i++;
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
60
|
+
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
61
|
+
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
62
|
+
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
63
|
+
// when the construct never closes, so the caller's cap stands).
|
|
64
|
+
export function bodyEndLineCount(bodyLines, py) {
|
|
65
|
+
if (py) {
|
|
66
|
+
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
67
|
+
let last = 1;
|
|
68
|
+
for (let k = 1; k < bodyLines.length; k++) {
|
|
69
|
+
const ln = bodyLines[k];
|
|
70
|
+
if (!ln.trim()) continue; // blank lines never end a block
|
|
71
|
+
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
72
|
+
last = k + 1;
|
|
73
|
+
}
|
|
74
|
+
return bodyLines.length;
|
|
75
|
+
}
|
|
76
|
+
const text = bodyLines.join("\n");
|
|
77
|
+
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
78
|
+
while (i < text.length) {
|
|
79
|
+
const ch = text[i], two = text.slice(i, i + 2);
|
|
80
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
81
|
+
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
82
|
+
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
83
|
+
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
84
|
+
i++; let inClass = false;
|
|
85
|
+
while (i < text.length && text[i] !== "\n") { const c = text[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
86
|
+
prevSig = "/"; continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '"' || ch === "'" || ch === "`") { const q = ch; i++; while (i < text.length && text[i] !== q) { if (text[i] === "\\") i++; else if (text[i] === "\n") line++; i++; } i++; prevSig = q; continue; }
|
|
89
|
+
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
90
|
+
// depth 0 must not be read as the construct closing on line 1
|
|
91
|
+
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
92
|
+
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
93
|
+
if (ch.trim()) prevSig = ch;
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
return bodyLines.length;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
100
|
+
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
101
|
+
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
102
|
+
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
103
|
+
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
104
|
+
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
105
|
+
const s = String(text || "");
|
|
106
|
+
const out = [];
|
|
107
|
+
let i = 0, line = 1, prevSig = "";
|
|
108
|
+
const capture = (from, to, startLine) => {
|
|
109
|
+
const content = s.slice(from, to);
|
|
110
|
+
const nl = (content.match(/\n/g) || []).length;
|
|
111
|
+
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
112
|
+
};
|
|
113
|
+
while (i < s.length) {
|
|
114
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
115
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
116
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
117
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
118
|
+
const startLine = line; i += 3; const from = i;
|
|
119
|
+
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
120
|
+
capture(from, i, startLine); i += 3; continue;
|
|
121
|
+
}
|
|
122
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
123
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
124
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
125
|
+
i++; let inClass = false;
|
|
126
|
+
while (i < s.length && s[i] !== "\n") { const c = s[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
127
|
+
prevSig = "/"; continue;
|
|
128
|
+
}
|
|
129
|
+
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
130
|
+
const startLine = line; i += 2; const from = i;
|
|
131
|
+
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
132
|
+
capture(from, i, startLine); i++; continue;
|
|
133
|
+
}
|
|
134
|
+
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
135
|
+
const startLine = line; i++; const from = i;
|
|
136
|
+
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
137
|
+
capture(from, i, startLine); i++; continue;
|
|
138
|
+
}
|
|
139
|
+
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
140
|
+
const q = ch; i++;
|
|
141
|
+
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
142
|
+
if (s[i] === q) i++; continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch.trim()) prevSig = ch;
|
|
145
|
+
i++;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
151
|
+
export function tokenize(text) {
|
|
152
|
+
const raw = text.match(/[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s\w]/g) || [];
|
|
153
|
+
const strict = [];
|
|
154
|
+
const renamed = [];
|
|
155
|
+
for (const t of raw) {
|
|
156
|
+
if (/^\d/.test(t)) { strict.push("N"); renamed.push("N"); continue; }
|
|
157
|
+
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
158
|
+
strict.push(t); renamed.push(t);
|
|
159
|
+
}
|
|
160
|
+
return { strict, renamed };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function fingerprints(toks) {
|
|
164
|
+
if (toks.length < K + W - 1) return new Set();
|
|
165
|
+
const hashes = [];
|
|
166
|
+
for (let i = 0; i + K <= toks.length; i++) {
|
|
167
|
+
let h = 0;
|
|
168
|
+
for (let j = i; j < i + K; j++) {
|
|
169
|
+
const s = toks[j];
|
|
170
|
+
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
171
|
+
h = (h * 131) | 0;
|
|
172
|
+
}
|
|
173
|
+
hashes.push(h >>> 0);
|
|
174
|
+
}
|
|
175
|
+
const fp = new Set();
|
|
176
|
+
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
177
|
+
let min = Infinity;
|
|
178
|
+
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
179
|
+
fp.add(min);
|
|
180
|
+
}
|
|
181
|
+
return fp;
|
|
182
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// endpoints.js — detect the repo's OWN HTTP API surface (routes it EXPOSES), so the Health tab can
|
|
2
|
+
// surface endpoints the way infra towers surface the services a repo TALKS TO. Each endpoint carries a
|
|
3
|
+
// best-effort handler NAME so the UI can join it to that method's health (O(n) complexity, criticality,
|
|
4
|
+
// coverage). Covers the common shapes across JS/TS, Python and Go:
|
|
5
|
+
// • object routes (Bun.serve / custom): "/path": { GET: handler, POST: fn } | "/path": handler
|
|
6
|
+
// • method-call routes (Express/Fastify/Koa/Hono/gin/echo): app.get("/path", handler)
|
|
7
|
+
// • decorators (FastAPI/Flask/NestJS): @app.get("/path") / @Get("/path")
|
|
8
|
+
// • Go net/http: mux.HandleFunc("/path", handler)
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { safeRead } from "../util.js";
|
|
11
|
+
|
|
12
|
+
const MAX_FILES = 3000;
|
|
13
|
+
const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ALL", "ANY"]);
|
|
14
|
+
// UNAMBIGUOUS HTTP CLIENTS (make requests) vs servers (define routes) — reject `axios.get("/x")`-style client
|
|
15
|
+
// calls in frontend code. Ambiguous names (api/client/service — could be a server router) are NOT listed;
|
|
16
|
+
// they're filtered by the handler requirement instead (a client call has no handler / a config object arg).
|
|
17
|
+
const HTTP_CLIENT_CALLER = /^(axios|https?|fetch|ky|got|superagent|needle|undici|xhr|\$http|http[Cc]lient|api[Cc]lient|rest[Cc]lient)$/;
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
// 1-based line of a string index
|
|
21
|
+
function lineAt(text, index) {
|
|
22
|
+
let line = 1;
|
|
23
|
+
for (let i = 0; i < index && i < text.length; i++) if (text[i] === "\n") line++;
|
|
24
|
+
return line;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// best-effort bare handler name from a value expression: the LAST identifier, unwrapping wrappers like
|
|
28
|
+
// executionRoute(queryHandlers.executeQuery) → executeQuery, asyncHandler(fn) → fn, a.b.c → c.
|
|
29
|
+
// An INLINE handler (arrow / function literal) has no named method to join to, so it returns "" (the
|
|
30
|
+
// UI then shows "inline") — grabbing an identifier out of an arrow body only invents garbage names.
|
|
31
|
+
function handlerName(expr) {
|
|
32
|
+
const s = String(expr || "").trim();
|
|
33
|
+
if (!s) return "";
|
|
34
|
+
if (/=>/.test(s) || /^\s*(async\s+)?function\b/.test(s)) return "";
|
|
35
|
+
const ids = s.match(/[A-Za-z_$][\w$]*/g);
|
|
36
|
+
if (!ids) return "";
|
|
37
|
+
const SKIP = new Set(["async", "function", "await", "req", "res", "ctx", "request", "response", "next", "return"]);
|
|
38
|
+
for (let i = ids.length - 1; i >= 0; i--) if (!SKIP.has(ids[i])) return ids[i];
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// An OpenAPI / Swagger spec object (e.g. `*.openapi.js` `paths`) documents routes rather than serving
|
|
43
|
+
// them — its "handlers" are operation()/spec objects, so treating it as a route table produced fake
|
|
44
|
+
// endpoints (handler "operation", {id} params). These keys never appear in a real route/handler table.
|
|
45
|
+
const OPENAPI_BLOCK = /\boperationId\b|\bresponses\s*:|\brequestBody\b|\bschemaRef\b|\boperation\s*\(|\bsummary\s*:/;
|
|
46
|
+
|
|
47
|
+
const looksLikePath = (p) => typeof p === "string" && /^\/[\w\-./:{}*$]*$/.test(p) && !p.includes("://");
|
|
48
|
+
const cleanPath = (p) => String(p || "").replace(/\/+$/, "") || "/";
|
|
49
|
+
|
|
50
|
+
export function extractEndpointsFromText(text, file) {
|
|
51
|
+
const out = [];
|
|
52
|
+
const py = /\.py$/i.test(file);
|
|
53
|
+
const add = (method, path, expr, idx) => {
|
|
54
|
+
const p = cleanPath(path);
|
|
55
|
+
if (!looksLikePath(p)) return;
|
|
56
|
+
const m = String(method || "ANY").toUpperCase();
|
|
57
|
+
if (!HTTP_METHODS.has(m)) return;
|
|
58
|
+
out.push({ method: m, path: p, handler: handlerName(expr), file, line: lineAt(text, idx) });
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// ---- object routes: "/path": { GET: fn, POST: fn2 } or "/path": handler --------------------
|
|
62
|
+
// find each "…": { or "…": expr, where the key looks like a path
|
|
63
|
+
const objKeyRe = /(["'`])(\/[^"'`]*)\1\s*:\s*(\{)?/g;
|
|
64
|
+
let m;
|
|
65
|
+
while ((m = objKeyRe.exec(text))) {
|
|
66
|
+
const path = m[2], keyIdx = m.index;
|
|
67
|
+
if (m[3]) {
|
|
68
|
+
// object of METHOD: handler — scan to the matching close brace (routes objects are shallow)
|
|
69
|
+
let i = objKeyRe.lastIndex, depth = 1;
|
|
70
|
+
const start = i;
|
|
71
|
+
while (i < text.length && depth > 0) { const c = text[i]; if (c === "{") depth++; else if (c === "}") depth--; i++; }
|
|
72
|
+
const body = text.slice(start, i - 1);
|
|
73
|
+
objKeyRe.lastIndex = i;
|
|
74
|
+
if (OPENAPI_BLOCK.test(body)) continue; // documentation, not a route table
|
|
75
|
+
const methodRe = /\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b\s*:\s*([^,\n}]+)/gi;
|
|
76
|
+
let mm;
|
|
77
|
+
while ((mm = methodRe.exec(body))) add(mm[1], path, mm[2], keyIdx);
|
|
78
|
+
} else {
|
|
79
|
+
// "/path": handlerExpr — a direct handler (any method); grab up to the next , or }
|
|
80
|
+
const tail = text.slice(objKeyRe.lastIndex, objKeyRe.lastIndex + 200);
|
|
81
|
+
const em = /^([^,\n}]+)/.exec(tail);
|
|
82
|
+
if (em && !/^\s*\{/.test(em[1])) add("ANY", path, em[1], keyIdx);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---- method-call routes: app.get("/path", handler) / router.post(...) / r.GET(...) ------------
|
|
87
|
+
// (?<!@) so a DECORATOR like @router.get("/x") isn't also caught here (handler-less); decorators are
|
|
88
|
+
// handled separately below where the handler is the following def. The CALLER is captured so we can reject
|
|
89
|
+
// CLIENT HTTP calls (axios.get("/api/users"), http.get(url), apiClient.post(...)) — those are requests in
|
|
90
|
+
// FRONTEND code, not server routes. A server route also REQUIRES a handler arg (an identifier/function),
|
|
91
|
+
// so a bare `client.get("/x")` or one whose 2nd arg is a config object literal `{…}` is skipped.
|
|
92
|
+
const callRe = /(?<!@)\b([\w$]+)\s*\.\s*(get|post|put|patch|delete|head|options|all)\s*\(\s*(["'`])(\/[^"'`]*)\3\s*(?:,\s*([\s\S]{0,160}?))?\)/gi;
|
|
93
|
+
while ((m = callRe.exec(text))) {
|
|
94
|
+
const caller = m[1], arg2 = String(m[5] || "").trim();
|
|
95
|
+
if (HTTP_CLIENT_CALLER.test(caller)) continue; // axios/http/fetch/apiClient… → a client request
|
|
96
|
+
if (!arg2 || arg2[0] === "{") continue; // no handler, or a config object → not a route def
|
|
97
|
+
add(m[2], m[4], m[5] || "", m.index);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---- Go net/http: mux.HandleFunc("/path", handler) / http.Handle("/path", h) ------------------
|
|
101
|
+
const goRe = /\.\s*(?:HandleFunc|Handle)\s*\(\s*(["'`])(\/[^"'`]*)\1\s*,\s*([\s\S]{0,120}?)\)/g;
|
|
102
|
+
while ((m = goRe.exec(text))) add("ANY", m[2], m[3], m.index);
|
|
103
|
+
|
|
104
|
+
// ---- decorators: @app.get("/path") / @router.post("/path") / @Get("/path") -------------------
|
|
105
|
+
if (py || /\.(ts|js|tsx|jsx|cjs|mjs)$/i.test(file)) {
|
|
106
|
+
const decoRe = /@[\w$]*\.?\s*(get|post|put|patch|delete|head|options)\s*\(\s*(["'`])(\/[^"'`]*)\2/gi;
|
|
107
|
+
while ((m = decoRe.exec(text))) {
|
|
108
|
+
// the handler is the def/function on a following line — best-effort: next def name
|
|
109
|
+
const after = text.slice(decoRe.lastIndex, decoRe.lastIndex + 200);
|
|
110
|
+
const fn = /\b(?:def|async\s+def|function|const|export\s+function)\s+([A-Za-z_$][\w$]*)/.exec(after);
|
|
111
|
+
add(m[1], m[3], fn ? fn[1] : "", m.index);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// `{id}` (OpenAPI) and `:id` (JS routers) are the SAME route — normalize for dedup so a real handler
|
|
119
|
+
// route isn't listed twice alongside its doc counterpart.
|
|
120
|
+
const normParamKey = (p) => String(p).replace(/\{([^/}]+)\}/g, ":$1");
|
|
121
|
+
|
|
122
|
+
// Detect endpoints across the repo's code files (from the graph's file nodes, or a caller-supplied list
|
|
123
|
+
// of {path, full}). Deduped by method+normalized-path; on a collision the entry with a resolvable
|
|
124
|
+
// handler (and `:param` display) wins. Capped. Returns [{method, path, handler, file, line}].
|
|
125
|
+
export function detectEndpoints(repoPath, codeFiles) {
|
|
126
|
+
const files = (codeFiles || []).slice(0, MAX_FILES);
|
|
127
|
+
const byKey = new Map();
|
|
128
|
+
for (const f of files) {
|
|
129
|
+
const rel = f.path || f;
|
|
130
|
+
const full = f.full || join(repoPath, rel);
|
|
131
|
+
if (!/\.(js|ts|tsx|jsx|cjs|mjs|py|go)$/i.test(rel)) continue;
|
|
132
|
+
const text = safeRead(full);
|
|
133
|
+
if (!text || !/["'`]\/|\.(get|post|put|patch|delete)\s*\(|HandleFunc|@\w*\.?(get|post|put|patch|delete)/i.test(text)) continue;
|
|
134
|
+
for (const e of extractEndpointsFromText(text, rel.replace(/\\/g, "/"))) {
|
|
135
|
+
const key = `${e.method} ${normParamKey(e.path)}`;
|
|
136
|
+
const prev = byKey.get(key);
|
|
137
|
+
if (!prev) { byKey.set(key, e); }
|
|
138
|
+
else if (preferEndpoint(e, prev)) { byKey.set(key, e); }
|
|
139
|
+
if (byKey.size >= 500) return [...byKey.values()].sort(sortEndpoints);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return [...byKey.values()].sort(sortEndpoints);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// true when candidate `a` is a better representative of a route than the already-kept `b`:
|
|
146
|
+
// a resolvable handler beats none; failing that, a `:param` path beats a `{param}` one.
|
|
147
|
+
function preferEndpoint(a, b) {
|
|
148
|
+
const ha = a.handler ? 1 : 0, hb = b.handler ? 1 : 0;
|
|
149
|
+
if (ha !== hb) return ha > hb;
|
|
150
|
+
const ca = a.path.includes("{") ? 1 : 0, cb = b.path.includes("{") ? 1 : 0;
|
|
151
|
+
return ca < cb;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function sortEndpoints(a, b) {
|
|
155
|
+
return a.path.localeCompare(b.path) || a.method.localeCompare(b.method);
|
|
156
|
+
}
|