codefactory-cli 0.20.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,483 @@
1
+ // TypeScript / JavaScript analyzer, run by codefactory/analyzers/typescript.py with Node:
2
+ // node ts_helper.js <root> <typescript module path> <ignore JSON>
3
+ // Prints the graph as JSON on stdout (the same shape as the Python analyzer's). Uses the analyzed repo's own
4
+ // TypeScript and tsconfig, so path aliases ("@/...") resolve, and the type checker resolves what each call runs:
5
+ // imported functions, methods on typed objects, functions handed out by hooks, and JSX components.
6
+ "use strict";
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+
10
+ const [root, tsPath, ignoreJson] = process.argv.slice(2);
11
+ const ts = require(tsPath);
12
+ const ignore = new Set(JSON.parse(ignoreJson || "[]"));
13
+ const EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
14
+ const rel = (f) => path.relative(root, f).split(path.sep).join("/");
15
+ const skipped = (f) => {
16
+ const parts = rel(f).split("/");
17
+ return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..");
18
+ };
19
+
20
+ function walkDir(dir, out) {
21
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
22
+ if (e.isDirectory()) { if (!ignore.has(e.name)) walkDir(path.join(dir, e.name), out); }
23
+ else if (EXT.test(e.name)) out.push(path.join(dir, e.name));
24
+ }
25
+ return out;
26
+ }
27
+
28
+ // Program: the repo's tsconfig when there is one (its paths and settings), plus any other source files found.
29
+ // codefactory: ignore module_state — a one-shot script: one run, one program, no importers
30
+ let options = { allowJs: true, jsx: ts.JsxEmit.Preserve, noEmit: true, skipLibCheck: true, esModuleInterop: true };
31
+ let fileNames = []; // codefactory: ignore module_state — the same one run
32
+ const cfgPath = ts.findConfigFile(root, ts.sys.fileExists, "tsconfig.json");
33
+ // (TypeScript reports paths with "/", Node on Windows with "\\": compare both resolved.)
34
+ if (cfgPath && path.resolve(path.dirname(cfgPath)) === path.resolve(root)) {
35
+ const cfg = ts.readConfigFile(cfgPath, ts.sys.readFile);
36
+ if (!cfg.error) {
37
+ const parsed = ts.parseJsonConfigFileContent(cfg.config, ts.sys, path.dirname(cfgPath));
38
+ options = { ...parsed.options, allowJs: true, noEmit: true, skipLibCheck: true };
39
+ fileNames = parsed.fileNames;
40
+ }
41
+ }
42
+ const all = new Set([...fileNames, ...walkDir(root, [])].map((f) => path.resolve(f)).filter((f) => !skipped(f)));
43
+ const program = ts.createProgram([...all], options);
44
+ const checker = program.getTypeChecker();
45
+ const sources = program.getSourceFiles().filter((sf) => all.has(path.resolve(sf.fileName)));
46
+
47
+ const files = [], functions = [], fnByNode = new Map(), calls = new Map(), refs = new Map(), imports = new Set();
48
+ const sites = [], ioOf = new Map();
49
+ const unresolvedProps = new Set();
50
+ const bump = (m, k) => m.set(k, (m.get(k) || 0) + 1);
51
+ const isFnLike = (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) ||
52
+ ts.isFunctionExpression(n) || ts.isConstructorDeclaration(n) || ts.isGetAccessor(n) || ts.isSetAccessor(n);
53
+ const lineOf = (sf, pos) => sf.getLineAndCharacterOfPosition(pos).line + 1;
54
+
55
+ function hash(s) { // FNV-1a, 2 x 32 bits
56
+ let a = 0x811c9dc5, b = 0x01000193;
57
+ for (let i = 0; i < s.length; i++) { a = Math.imul(a ^ s.charCodeAt(i), 16777619) >>> 0; b = Math.imul(b ^ s.charCodeAt(i), 2654435761) >>> 0; }
58
+ return a.toString(16).padStart(8, "0") + b.toString(16).padStart(8, "0");
59
+ }
60
+
61
+ // The name a function is known by: its own, the variable or property it's assigned to, or null (anonymous callback).
62
+ function nameOf(n) {
63
+ if (ts.isConstructorDeclaration(n)) return "constructor";
64
+ if (n.name && (ts.isIdentifier(n.name) || ts.isStringLiteral(n.name) || ts.isPrivateIdentifier(n.name))) return n.name.text;
65
+ const p = n.parent;
66
+ if (p && ts.isVariableDeclaration(p) && ts.isIdentifier(p.name)) return p.name.text;
67
+ if (p && ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))) return p.name.text;
68
+ if (p && ts.isPropertyDeclaration(p) && ts.isIdentifier(p.name)) return p.name.text;
69
+ if (p && ts.isExportAssignment(p)) return "default";
70
+ // const Row = memo(() => …), forwardRef(…), useCallback(…): the wrapped function is the variable. (Other calls,
71
+ // like useSyncExternalStore(cb) or usePicker(cb), return something else: their callbacks stay anonymous.)
72
+ if (p && ts.isCallExpression(p) && p.parent && ts.isVariableDeclaration(p.parent) && ts.isIdentifier(p.parent.name)) {
73
+ const callee = ts.isPropertyAccessExpression(p.expression) ? p.expression.name.text : ts.isIdentifier(p.expression) ? p.expression.text : "";
74
+ if (WRAPPERS.has(callee)) return p.parent.name.text;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ const WRAPPERS = new Set(["memo", "forwardRef", "useCallback", "useEvent", "useEffectEvent", "observer", "styled"]);
80
+
81
+ function isDefaultExport(n) {
82
+ const mods = ts.canHaveModifiers(n) ? ts.getModifiers(n) || [] : [];
83
+ if (mods.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) return true;
84
+ return !!(n.parent && ts.isExportAssignment(n.parent));
85
+ }
86
+
87
+ function isExported(n) {
88
+ const has = (x) => ts.canHaveModifiers(x) && (ts.getModifiers(x) || []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
89
+ if (has(n) || isDefaultExport(n)) return true;
90
+ const decl = n.parent && ts.isVariableDeclaration(n.parent) ? n.parent : null; // export const f = () => …
91
+ return !!(decl && decl.parent && decl.parent.parent && has(decl.parent.parent));
92
+ }
93
+
94
+ function shapeOf(n, sf) {
95
+ const body = n.body;
96
+ if (!body) return "";
97
+ const parts = [];
98
+ let count = 0;
99
+ const visit = (x) => {
100
+ count++;
101
+ parts.push(x.kind);
102
+ if (ts.isPropertyAccessExpression(x)) parts.push(x.name.text);
103
+ else if (ts.isIdentifier(x) && !(x.parent && ts.isPropertyAccessExpression(x.parent) && x.parent.name === x)) {
104
+ const sym = checker.getSymbolAtLocation(x);
105
+ const d = sym && sym.declarations && sym.declarations[0];
106
+ const local = d && d.getSourceFile() === sf && d.pos >= n.pos && d.end <= n.end;
107
+ if (!local) parts.push(x.text);
108
+ } else if (ts.isBinaryExpression(x)) parts.push(x.operatorToken.kind);
109
+ // a string's words count: two functions differing only in their SQL or messages aren't copies
110
+ else if (ts.isStringLiteral(x) || ts.isNoSubstitutionTemplateLiteral(x) || ts.isTemplateHead(x) ||
111
+ ts.isTemplateMiddle(x) || ts.isTemplateTail(x)) parts.push(...x.text.split(/\s+/).filter(Boolean).slice(0, 24).map((w) => "S:" + w));
112
+ else if (ts.isNumericLiteral(x)) parts.push("N:" + x.text);
113
+ ts.forEachChild(x, visit);
114
+ };
115
+ visit(body);
116
+ if (count < 15) return { shape: "", tokens: "" };
117
+ const tokens = parts.join(" ");
118
+ return { shape: hash(tokens), tokens };
119
+ }
120
+
121
+ // Efficiency: where a call or await sits relative to loops, and which calls leave the process.
122
+ const ITER = new Set(["map", "forEach", "filter", "reduce", "reduceRight", "some", "every", "flatMap", "find", "findIndex",
123
+ "findLast", "findLastIndex", "sort", "toSorted"]);
124
+ const SCAN = new Set(["find", "filter", "includes", "indexOf", "lastIndexOf", "some", "every", "findIndex", "findLast", "findLastIndex"]);
125
+ const IO_FN = /^(getAll|getFirst|getEach|run|exec|prepare|execute|withTransaction|withExclusiveTransaction)(Async|Sync)$|^(fetch|readAsStringAsync|writeAsStringAsync|downloadAsync|downloadFileAsync|uploadAsync|getItemAsync|setItemAsync|deleteItemAsync|readFile|writeFile|readFileSync|writeFileSync|appendFile|appendFileSync|readdir|readdirSync|stat|statSync)$/;
126
+ const IO_RECEIVER = /^(axios|AsyncStorage|prisma|knex|pool|client|db|sql|supabase|firestore|redis|mongoose)$/i;
127
+ const IO_VIA_RECEIVER = /^(query|execute|get|set|post|put|patch|delete|findMany|findUnique|findFirst|create|update|upsert|select|insert|from|getItem|setItem|removeItem|multiGet|multiSet)$/;
128
+
129
+ // { loop, stmt }: runs once per iteration of a loop (for/while, or an array callback like .map); stmt = a for/while
130
+ // statement around it in the same function body (an await there waits on each round in turn).
131
+ // A list whose length is fixed in the code: an array or object literal, a const holding one (also imported, and
132
+ // through Object.keys/values/entries, .map, .filter…), an enum, or anything cut to a small .slice(0, N).
133
+ const SMALL = 50;
134
+ function constIterable(e, depth = 0) {
135
+ if (!e || depth > 5) return false;
136
+ while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isNonNullExpression(e) ||
137
+ (ts.isSatisfiesExpression && ts.isSatisfiesExpression(e))) e = e.expression;
138
+ if (ts.isArrayLiteralExpression(e) || ts.isObjectLiteralExpression(e)) return true;
139
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression)) {
140
+ const name = e.expression.name.text, recv = e.expression.expression;
141
+ if (name === "slice" && e.arguments.length === 2 && ts.isNumericLiteral(e.arguments[1]) && Number(e.arguments[1].text) <= SMALL) return true;
142
+ if (ts.isIdentifier(recv) && recv.text === "Object" && ["keys", "values", "entries"].includes(name)) return constIterable(e.arguments[0], depth + 1);
143
+ if (["map", "filter", "flatMap", "slice", "concat", "toSorted", "toReversed"].includes(name)) return constIterable(recv, depth + 1);
144
+ }
145
+ if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e)) {
146
+ let sym = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(e) ? e.name : e);
147
+ if (sym && sym.flags & ts.SymbolFlags.Alias) { try { sym = checker.getAliasedSymbol(sym); } catch { return false; } }
148
+ const d = sym && sym.declarations && sym.declarations[0];
149
+ if (!d) return false;
150
+ if (ts.isEnumDeclaration(d)) return true;
151
+ if (ts.isVariableDeclaration(d) && d.initializer && (ts.getCombinedNodeFlags(d) & ts.NodeFlags.Const)) return constIterable(d.initializer, depth + 1);
152
+ if (ts.isPropertyAssignment(d)) return constIterable(d.initializer, depth + 1);
153
+ // const { tables } = PARTS[part]: a piece of a constant object is as fixed as the object
154
+ if (ts.isBindingElement(d) && ts.isVariableDeclaration(d.parent.parent)) return constRoot(d.parent.parent.initializer, depth + 1);
155
+ }
156
+ if (ts.isElementAccessExpression(e)) return constRoot(e, depth + 1);
157
+ return false;
158
+ }
159
+ // PARTS[part].tables, CONFIG.items: the object at the root of the access is a constant literal.
160
+ function constRoot(e, depth) {
161
+ while (e && (ts.isElementAccessExpression(e) || ts.isPropertyAccessExpression(e) || ts.isParenthesizedExpression(e) ||
162
+ ts.isAsExpression(e) || ts.isNonNullExpression(e))) e = e.expression;
163
+ return !!e && ts.isIdentifier(e) && constIterable(e, depth);
164
+ }
165
+ function boundedLoop(p) {
166
+ if (ts.isForOfStatement(p) || ts.isForInStatement(p)) return constIterable(p.expression);
167
+ if (ts.isForStatement(p) && p.condition && ts.isBinaryExpression(p.condition)) {
168
+ const r = p.condition.right;
169
+ return (ts.isNumericLiteral(r) && Number(r.text) <= SMALL) ||
170
+ (ts.isPropertyAccessExpression(r) && r.name.text === "length" && constIterable(r.expression));
171
+ }
172
+ return false; // while / do: can't tell
173
+ }
174
+
175
+ // Decision points in a function's own body (if, loops, case, catch, ?:, && || ??): how hard it is to follow, which
176
+ // length alone doesn't say (a 700-line table of options is long and simple).
177
+ function branchesOf(fnNode) {
178
+ let count = 0;
179
+ const visit = (x) => {
180
+ if (x !== fnNode && fnByNode.has(x)) return;
181
+ if (ts.isIfStatement(x) || ts.isForStatement(x) || ts.isForOfStatement(x) || ts.isForInStatement(x) || ts.isWhileStatement(x) ||
182
+ ts.isDoStatement(x) || ts.isCaseClause(x) || ts.isCatchClause(x) || ts.isConditionalExpression(x)) count++;
183
+ if (ts.isBinaryExpression(x) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
184
+ ts.SyntaxKind.QuestionQuestionToken].includes(x.operatorToken.kind)) count++;
185
+ ts.forEachChild(x, visit);
186
+ };
187
+ visit(fnNode);
188
+ return count;
189
+ }
190
+
191
+ // A write inside a callback handed to transaction()/withTransactionAsync()/atomic(): batched into one transaction.
192
+ const TX = /transaction|atomic|batch|writeTxn|serializ/i;
193
+ function inTransaction(n) {
194
+ for (let p = n.parent; p; p = p.parent) {
195
+ if (ts.isSourceFile(p)) return false;
196
+ if (isFnLike(p)) {
197
+ const call = p.parent;
198
+ if (call && ts.isCallExpression(call) && call.arguments.includes(p) && TX.test(lastName(call.expression) || "")) return true;
199
+ if (fnByNode.has(p)) return false;
200
+ }
201
+ }
202
+ return false;
203
+ }
204
+
205
+ // { loop, stmt, bounded }: runs once per iteration of a loop (for/while, or an array callback like .map); stmt = a
206
+ // for/while statement around it in the same function body (an await there waits on each round in turn); bounded =
207
+ // every loop around it goes over a list fixed in the code, so the number of rounds can't grow with the data.
208
+ function loopState(n) {
209
+ let loop = false, stmt = false, crossed = false, bounded = true;
210
+ for (let c = n, p = n.parent; p; c = p, p = p.parent) {
211
+ if (fnByNode.has(p) || ts.isSourceFile(p)) break;
212
+ const statementLoop = ((ts.isForOfStatement(p) || ts.isForInStatement(p)) && c === p.statement) ||
213
+ (ts.isForStatement(p) && c !== p.initializer) || ts.isWhileStatement(p) || ts.isDoStatement(p);
214
+ if (statementLoop) { loop = true; if (!crossed) stmt = true; bounded = bounded && boundedLoop(p); }
215
+ if (isFnLike(p)) {
216
+ const call = p.parent;
217
+ const iterating = call && ts.isCallExpression(call) && call.arguments.includes(p) && ts.isPropertyAccessExpression(call.expression) &&
218
+ ITER.has(call.expression.name.text);
219
+ // any other callback (onPress={() => …}, setTimeout, .then) runs later, not once per iteration of loops around it
220
+ if (!iterating) break;
221
+ loop = true;
222
+ crossed = true;
223
+ bounded = bounded && constIterable(call.expression.expression);
224
+ }
225
+ }
226
+ return { loop, stmt, bounded: loop && bounded };
227
+ }
228
+ function lastName(expr) {
229
+ while (expr && (ts.isPropertyAccessExpression(expr) || ts.isCallExpression(expr) || ts.isNonNullExpression(expr))) {
230
+ if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
231
+ expr = expr.expression;
232
+ }
233
+ return expr && ts.isIdentifier(expr) ? expr.text : expr && expr.kind === ts.SyntaxKind.ThisKeyword ? "this" : "";
234
+ }
235
+ function headName(expr) {
236
+ while (expr && (ts.isPropertyAccessExpression(expr) || ts.isCallExpression(expr) || ts.isNonNullExpression(expr))) expr = expr.expression;
237
+ return expr && ts.isIdentifier(expr) ? expr.text : "";
238
+ }
239
+ function ioCall(call) {
240
+ const e = call.expression;
241
+ if (ts.isIdentifier(e)) return IO_FN.test(e.text) ? e.text : null;
242
+ if (!ts.isPropertyAccessExpression(e)) return null;
243
+ const name = e.name.text, recv = lastName(e.expression), head = headName(e.expression);
244
+ if (IO_FN.test(name) || IO_RECEIVER.test(head) && (IO_VIA_RECEIVER.test(name) || /^axios$/i.test(head))) return recv ? `${recv}.${name}` : name;
245
+ return null;
246
+ }
247
+ function arrayish(expr) {
248
+ try {
249
+ const t = checker.getTypeAtLocation(expr);
250
+ if (typeof checker.isArrayType === "function" && checker.isArrayType(t)) return true;
251
+ return /\[\]$|^(readonly )?(Readonly)?Array</.test(checker.typeToString(t));
252
+ } catch { return false; }
253
+ }
254
+
255
+ // 1. Files and functions. Nested named functions (a hook's handlers, a component's callbacks) are their own
256
+ // functions, qualified by what holds them ("useRun.logSet"); anonymous callbacks belong to the function around them.
257
+ for (const sf of sources) {
258
+ const id = rel(sf.fileName);
259
+ files.push({ id, module: id.replace(EXT, ""), loc: sf.getLineAndCharacterOfPosition(sf.end).line + 1 });
260
+ const top = { id: `${id}::<module>`, file: id, name: "<module>", qualname: "<module>", line: 1, end: 1, loc: 0,
261
+ kind: "module", decorated: false, exported: false, shape: "", tokens: "", dynamic: false, public: false, io: [] };
262
+ functions.push(top);
263
+ fnByNode.set(sf, top);
264
+ const seen = new Map();
265
+ const visit = (n, owner, cls) => {
266
+ let next = owner, nextCls = cls;
267
+ if (ts.isClassDeclaration(n) || ts.isClassExpression(n)) nextCls = n.name ? n.name.text : cls;
268
+ if (isFnLike(n)) {
269
+ // A function written inline as an object property or JSX prop inside another function ({ onPress: () => … },
270
+ // headerRight: () => …) is a callback handed to something else: part of the function around it.
271
+ const inline = owner && owner.kind !== "module" && n.parent &&
272
+ (ts.isPropertyAssignment(n.parent) || ts.isJsxExpression(n.parent) || (ts.isMethodDeclaration(n) && ts.isObjectLiteralExpression(n.parent)));
273
+ const name = inline ? null : nameOf(n);
274
+ if (name) {
275
+ const prefix = cls && (ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n) || ts.isGetAccessor(n) ||
276
+ ts.isSetAccessor(n) || (n.parent && ts.isPropertyDeclaration(n.parent))) ? cls : owner && owner.kind !== "module" ? owner.qualname : null;
277
+ let qual = prefix ? `${prefix}.${name}` : name;
278
+ const line = lineOf(sf, n.getStart(sf)), end = lineOf(sf, n.end);
279
+ const fid = seen.has(qual) ? `${id}::${qual}@${line}` : `${id}::${qual}`;
280
+ seen.set(qual, true);
281
+ // A function stored in a module-level object ({ label, onPress: () => … }) is handed around as data and
282
+ // called by whatever receives it: never reported as unused.
283
+ const asData = n.parent && (ts.isPropertyAssignment(n.parent) || (ts.isMethodDeclaration(n) && ts.isObjectLiteralExpression(n.parent)));
284
+ const fn = { id: fid, file: id, name, qualname: qual, line, end, loc: end - line + 1,
285
+ kind: prefix && prefix === cls ? "method" : "function", decorated: !!(ts.canHaveDecorators(n) && ts.getDecorators(n)?.length),
286
+ exported: !!asData || isDefaultExport(n) || (n.parent && ts.isVariableDeclaration(n.parent) && isDefaultExport(n.parent.parent.parent)),
287
+ ...shapeOf(n, sf), dynamic: false, public: isExported(n), io: [], branches: branchesOf(n) };
288
+ functions.push(fn);
289
+ fnByNode.set(n, fn);
290
+ next = fn;
291
+ if (prefix === cls) nextCls = null; // inside a method, nested functions are qualified by the method
292
+ }
293
+ }
294
+ ts.forEachChild(n, (c) => visit(c, next, nextCls));
295
+ };
296
+ ts.forEachChild(sf, (c) => visit(c, top, null));
297
+ }
298
+
299
+ // 2. Edges.
300
+ function fnForDeclaration(d) {
301
+ if (!d) return null;
302
+ if (fnByNode.has(d)) return fnByNode.get(d);
303
+ if (ts.isVariableDeclaration(d) && d.initializer) {
304
+ let init = d.initializer;
305
+ while (init && (ts.isParenthesizedExpression(init) || ts.isAsExpression(init) || ts.isCallExpression(init))) {
306
+ if (ts.isCallExpression(init)) { // memo(() => …): the wrapped function; any other call returns something else
307
+ const callee = ts.isPropertyAccessExpression(init.expression) ? init.expression.name.text : ts.isIdentifier(init.expression) ? init.expression.text : "";
308
+ init = WRAPPERS.has(callee) ? init.arguments.find((a) => isFnLike(a)) : null;
309
+ } else init = init.expression;
310
+ }
311
+ if (init && fnByNode.has(init)) return fnByNode.get(init);
312
+ }
313
+ if ((ts.isPropertyAssignment(d) || ts.isPropertyDeclaration(d)) && d.initializer && fnByNode.has(d.initializer)) return fnByNode.get(d.initializer);
314
+ if (ts.isShorthandPropertyAssignment(d)) {
315
+ const v = checker.getShorthandAssignmentValueSymbol(d);
316
+ return v ? fnForSymbol(v) : null;
317
+ }
318
+ return null;
319
+ }
320
+ function fnForSymbol(sym) {
321
+ if (!sym) return null;
322
+ if (sym.flags & ts.SymbolFlags.Alias) { try { sym = checker.getAliasedSymbol(sym); } catch { return null; } }
323
+ for (const d of sym.declarations || []) { const f = fnForDeclaration(d); if (f) return f; }
324
+ if (sym.flags & ts.SymbolFlags.Class) { // new Foo() / <Foo />: its constructor
325
+ for (const d of sym.declarations || []) for (const m of d.members || []) if (ts.isConstructorDeclaration(m) && fnByNode.has(m)) return fnByNode.get(m);
326
+ }
327
+ return null;
328
+ }
329
+ // Code loaded on demand: const { fn } = require("./x") (also cast with `as`), const m = require("./x"); m.fn(),
330
+ // require("./x").fn(), await import("./x"). The type checker can't see through these; the module's exports can.
331
+ // codefactory: ignore module_state — filled once per run, read by the passes after it
332
+ let exportsByFile = null;
333
+ function exportsOf(fileId) {
334
+ if (!exportsByFile) {
335
+ exportsByFile = new Map();
336
+ for (const f of functions) {
337
+ if (f.kind === "module" || f.qualname.includes(".")) continue;
338
+ if (!exportsByFile.has(f.file)) exportsByFile.set(f.file, new Map());
339
+ exportsByFile.get(f.file).set(f.name, f);
340
+ }
341
+ }
342
+ return exportsByFile.get(fileId);
343
+ }
344
+ function requiredFile(init) {
345
+ while (init && (ts.isParenthesizedExpression(init) || ts.isAsExpression(init) || ts.isAwaitExpression(init) ||
346
+ ts.isNonNullExpression(init) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(init)))) init = init.expression;
347
+ if (!init || !ts.isCallExpression(init) || !init.arguments[0] || !ts.isStringLiteral(init.arguments[0])) return null;
348
+ const isRequire = ts.isIdentifier(init.expression) && init.expression.text === "require";
349
+ if (!isRequire && init.expression.kind !== ts.SyntaxKind.ImportKeyword) return null;
350
+ return resolveModule(init.arguments[0].text, init.getSourceFile());
351
+ }
352
+ function fnViaRequire(sym, prop) {
353
+ for (const d of (sym && sym.declarations) || []) {
354
+ if (ts.isBindingElement(d) && ts.isObjectBindingPattern(d.parent) && ts.isVariableDeclaration(d.parent.parent)) {
355
+ const file = requiredFile(d.parent.parent.initializer);
356
+ const name = d.propertyName && ts.isIdentifier(d.propertyName) ? d.propertyName.text : ts.isIdentifier(d.name) ? d.name.text : "";
357
+ if (file) return (exportsOf(file) || new Map()).get(name) || null;
358
+ }
359
+ if (prop && ts.isVariableDeclaration(d) && ts.isIdentifier(d.name)) {
360
+ const file = requiredFile(d.initializer);
361
+ if (file) return (exportsOf(file) || new Map()).get(prop) || null;
362
+ }
363
+ }
364
+ return null;
365
+ }
366
+
367
+ function calleeOf(node) {
368
+ try {
369
+ const sig = checker.getResolvedSignature(node);
370
+ const f = sig && sig.declaration && fnForDeclaration(sig.declaration);
371
+ if (f) return f;
372
+ } catch { /* fall back to the symbol */ }
373
+ const target = ts.isCallExpression(node) || ts.isNewExpression(node) ? node.expression : node.tagName;
374
+ const f = fnForSymbol(checker.getSymbolAtLocation(ts.isPropertyAccessExpression(target) ? target.name : target));
375
+ if (f) return f;
376
+ if (ts.isIdentifier(target)) return fnViaRequire(checker.getSymbolAtLocation(target), null);
377
+ if (ts.isPropertyAccessExpression(target)) {
378
+ if (ts.isIdentifier(target.expression)) {
379
+ const viaVar = fnViaRequire(checker.getSymbolAtLocation(target.expression), target.name.text);
380
+ if (viaVar) return viaVar;
381
+ }
382
+ const file = requiredFile(target.expression);
383
+ if (file) return (exportsOf(file) || new Map()).get(target.name.text) || null;
384
+ }
385
+ return null;
386
+ }
387
+ // TABLE[key](…): one of the table's functions runs (the type checker picks just one); link to all of them.
388
+ function linkTable(n, src) {
389
+ let root = n.expression;
390
+ while (ts.isElementAccessExpression(root) || ts.isPropertyAccessExpression(root)) root = root.expression;
391
+ let sym = ts.isIdentifier(root) ? checker.getSymbolAtLocation(root) : null;
392
+ if (sym && sym.flags & ts.SymbolFlags.Alias) { try { sym = checker.getAliasedSymbol(sym); } catch { sym = null; } }
393
+ const decl = sym && sym.declarations && sym.declarations[0];
394
+ if (!decl || !ts.isVariableDeclaration(decl) || !decl.initializer) return;
395
+ const link = (f) => { if (f && f !== src) bump(refs, `${src.id}\u0000${f.id}`); };
396
+ const walk = (x) => {
397
+ if (isFnLike(x) && fnByNode.has(x)) return link(fnByNode.get(x)); // an inline function in the table
398
+ if (ts.isIdentifier(x) || ts.isPropertyAccessExpression(x)) {
399
+ link(fnForSymbol(checker.getSymbolAtLocation(ts.isPropertyAccessExpression(x) ? x.name : x)));
400
+ if (ts.isIdentifier(x)) return;
401
+ }
402
+ ts.forEachChild(x, walk);
403
+ };
404
+ walk(decl.initializer);
405
+ }
406
+ function ownerOf(n) {
407
+ for (let p = n.parent; p; p = p.parent) if (fnByNode.has(p)) return fnByNode.get(p);
408
+ return null;
409
+ }
410
+ function resolveModule(spec, sf) {
411
+ const r = ts.resolveModuleName(spec, sf.fileName, options, ts.sys).resolvedModule;
412
+ if (!r || r.isExternalLibraryImport) return null;
413
+ const f = path.resolve(r.resolvedFileName);
414
+ return all.has(f) ? rel(f) : null;
415
+ }
416
+ const typeOnly = (d) => d.importClause && (d.importClause.isTypeOnly ||
417
+ (!d.importClause.name && d.importClause.namedBindings && ts.isNamedImports(d.importClause.namedBindings) &&
418
+ d.importClause.namedBindings.elements.length > 0 && d.importClause.namedBindings.elements.every((e) => e.isTypeOnly)));
419
+
420
+ for (const sf of sources) {
421
+ const fileId = rel(sf.fileName);
422
+ const visit = (n) => {
423
+ if ((ts.isImportDeclaration(n) || ts.isExportDeclaration(n)) && n.moduleSpecifier && ts.isStringLiteral(n.moduleSpecifier)
424
+ && !(ts.isImportDeclaration(n) && typeOnly(n)) && !(ts.isExportDeclaration(n) && n.isTypeOnly)) {
425
+ const dst = resolveModule(n.moduleSpecifier.text, sf);
426
+ if (dst && dst !== fileId) imports.add(`${fileId}\u0000${dst}`);
427
+ }
428
+ const isCall = ts.isCallExpression(n) || ts.isNewExpression(n) || ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n);
429
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === "require" && n.arguments[0] && ts.isStringLiteral(n.arguments[0])) {
430
+ // only a top-level require runs when the file loads; one inside a function is loaded on demand (no loop)
431
+ const dst = resolveModule(n.arguments[0].text, sf);
432
+ const owner = ownerOf(n);
433
+ if (dst && dst !== fileId && (!owner || owner.kind === "module")) imports.add(`${fileId}\u0000${dst}`);
434
+ } else if (isCall) {
435
+ const src = ownerOf(n), dst = calleeOf(n);
436
+ if (src && ts.isCallExpression(n) && ts.isElementAccessExpression(n.expression)) linkTable(n, src);
437
+ const where = src && (ts.isCallExpression(n) || ts.isNewExpression(n)) ? loopState(n) : { loop: false };
438
+ const line = lineOf(sf, n.getStart(sf));
439
+ if (src && dst && dst !== src) {
440
+ bump(calls, `${src.id}\u0000${dst.id}`);
441
+ if (where.loop) sites.push({ fn: src.id, kind: "loop_call", line, target: dst.id, detail: "", bounded: where.bounded, tx: inTransaction(n) });
442
+ else if (inTransaction(n)) sites.push({ fn: src.id, kind: "tx_call", line, target: dst.id, detail: "", bounded: false, tx: true });
443
+ } else if (!dst && ts.isCallExpression(n)) {
444
+ if (ts.isPropertyAccessExpression(n.expression)) unresolvedProps.add(n.expression.name.text);
445
+ const io = src && ioCall(n);
446
+ if (io) {
447
+ (ioOf.get(src) || ioOf.set(src, new Set()).get(src)).add(io);
448
+ if (where.loop) sites.push({ fn: src.id, kind: "loop_io", line, target: "", detail: io, bounded: where.bounded, tx: inTransaction(n) });
449
+ } else if (src && where.loop && ts.isPropertyAccessExpression(n.expression) && SCAN.has(n.expression.name.text) &&
450
+ arrayish(n.expression.expression) && !constIterable(n.expression.expression)) { // [a, b].includes(x) is O(1)
451
+ sites.push({ fn: src.id, kind: "loop_scan", line, target: "", detail: `${lastName(n.expression.expression) || "array"}.${n.expression.name.text}`, bounded: where.bounded });
452
+ }
453
+ }
454
+ } else if (ts.isAwaitExpression(n)) {
455
+ const src = ownerOf(n);
456
+ const ls = src && loopState(n);
457
+ if (ls && ls.stmt) sites.push({ fn: src.id, kind: "loop_await", line: lineOf(sf, n.getStart(sf)), target: "", detail: "", bounded: ls.bounded });
458
+ } else if (ts.isIdentifier(n)) {
459
+ const p = n.parent;
460
+ const callee = p && (ts.isCallExpression(p) || ts.isNewExpression(p)) && p.expression === n;
461
+ const tag = p && (ts.isJsxOpeningElement(p) || ts.isJsxSelfClosingElement(p) || ts.isJsxClosingElement(p)) && p.tagName === n;
462
+ const declName = p && (p.name === n) && (isFnLike(p) || ts.isVariableDeclaration(p) || ts.isPropertyAssignment(p) ||
463
+ ts.isPropertyDeclaration(p) || ts.isClassDeclaration(p) || ts.isMethodDeclaration(p));
464
+ const memberCallee = p && ts.isPropertyAccessExpression(p) && p.name === n && p.parent && ts.isCallExpression(p.parent) && p.parent.expression === p;
465
+ if (!callee && !tag && !declName && !memberCallee) {
466
+ const sym = p && ts.isShorthandPropertyAssignment(p) ? checker.getShorthandAssignmentValueSymbol(p) : checker.getSymbolAtLocation(n);
467
+ const dst = fnForSymbol(sym) || fnViaRequire(sym, null);
468
+ const src = ownerOf(n);
469
+ if (src && dst && dst !== src) bump(refs, `${src.id}\u0000${dst.id}`);
470
+ }
471
+ }
472
+ ts.forEachChild(n, visit);
473
+ };
474
+ ts.forEachChild(sf, visit);
475
+ }
476
+ for (const f of functions) if (f.kind === "method" && unresolvedProps.has(f.name)) f.dynamic = true;
477
+
478
+ const edges = [];
479
+ for (const [k, count] of calls) { const [src, dst] = k.split("\u0000"); edges.push({ src, dst, kind: "call", count }); }
480
+ for (const [k, count] of refs) if (!calls.has(k)) { const [src, dst] = k.split("\u0000"); edges.push({ src, dst, kind: "ref", count }); }
481
+ for (const k of imports) { const [src, dst] = k.split("\u0000"); edges.push({ src, dst, kind: "import", count: 1 }); }
482
+ for (const [fn, set] of ioOf) fn.io = [...set].sort();
483
+ process.stdout.write(JSON.stringify({ files, functions, edges, sites }));
@@ -0,0 +1,118 @@
1
+ """TypeScript / JavaScript analyzer. The parsing and call resolution run in Node (ts_helper.js) with the TypeScript
2
+ compiler, because only the type checker can tell what `obj.method()` or a function from a React hook really is.
3
+
4
+ Needs Node on PATH and the `typescript` package: the analyzed repo's own (node_modules/typescript) is used first,
5
+ then a global install (npm install -g typescript), or CODEFACTORY_TYPESCRIPT pointing at one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from importlib.resources import files as pkg_files
17
+ from pathlib import Path
18
+
19
+ from ..graph import Edge, File, Function, Graph, Site
20
+
21
+ EXTENSIONS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
22
+
23
+
24
+ class TypeScriptUnavailable(RuntimeError):
25
+ pass
26
+
27
+
28
+ def sources_stamp(root: Path, ignore: list[str]) -> str:
29
+ """A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none)."""
30
+ skip = set(ignore)
31
+ h = hashlib.sha1()
32
+ found = False
33
+ for dirpath, dirnames, filenames in os.walk(root):
34
+ dirnames[:] = sorted(d for d in dirnames if d not in skip)
35
+ for f in sorted(filenames):
36
+ if (f.endswith(EXTENSIONS) and not f.endswith(".d.ts")) or f.startswith(("tsconfig", "jsconfig", "package.json")):
37
+ found = found or f.endswith(EXTENSIONS)
38
+ try:
39
+ st = os.stat(os.path.join(dirpath, f))
40
+ except OSError:
41
+ continue
42
+ h.update(
43
+ f"{os.path.relpath(os.path.join(dirpath, f), root)}|{st.st_size}|{st.st_mtime_ns}\n".encode(
44
+ "utf-8", "surrogatepass"
45
+ )
46
+ )
47
+ return h.hexdigest() if found else ""
48
+
49
+
50
+ def find_typescript(root: Path, node: str) -> str:
51
+ env = os.environ.get("CODEFACTORY_TYPESCRIPT")
52
+ if env:
53
+ return env
54
+ local = root / "node_modules" / "typescript"
55
+ if (local / "package.json").is_file():
56
+ return str(local)
57
+ try:
58
+ npm_root = subprocess.run(
59
+ ["npm", "root", "-g"], capture_output=True, text=True, timeout=30, shell=sys.platform == "win32"
60
+ ).stdout.strip()
61
+ if npm_root and (Path(npm_root) / "typescript" / "package.json").is_file():
62
+ return str(Path(npm_root) / "typescript")
63
+ except (OSError, subprocess.SubprocessError):
64
+ pass
65
+ raise TypeScriptUnavailable(
66
+ "TypeScript files found, but the typescript package isn't installed. Run `npm install` in the repo, "
67
+ "or `npm install -g typescript`, or set CODEFACTORY_TYPESCRIPT to its folder."
68
+ )
69
+
70
+
71
+ def analyze_typescript(root: Path, ignore: list[str], cache: bool = True) -> Graph:
72
+ g = Graph(root=str(root), language="typescript")
73
+ stamp = sources_stamp(root, ignore)
74
+ if not stamp:
75
+ return g
76
+ from .parallel import _tool_hash
77
+
78
+ stamp = f"{stamp}|{_tool_hash()}"
79
+ saved = root / ".codefactory" / "typescript.json"
80
+ data = None
81
+ if cache:
82
+ try:
83
+ got = json.loads(saved.read_text(encoding="utf-8"))
84
+ data = got["data"] if got.get("stamp") == stamp else None
85
+ except (OSError, ValueError, KeyError):
86
+ data = None
87
+ if data is None:
88
+ data = _run_helper(root, ignore)
89
+ if cache:
90
+ try:
91
+ saved.parent.mkdir(exist_ok=True)
92
+ saved.write_text(json.dumps({"stamp": stamp, "data": data}), encoding="utf-8")
93
+ except OSError:
94
+ pass
95
+ g.files = [File(**f) for f in data["files"]]
96
+ g.functions = [Function(**f) for f in data["functions"]]
97
+ g.edges = [Edge(**e) for e in data["edges"]]
98
+ g.sites = [Site(**s) for s in data.get("sites", [])]
99
+ return g
100
+
101
+
102
+ def _run_helper(root: Path, ignore: list[str]) -> dict:
103
+ """Runs ts_helper.js in Node over the whole project (the type checker needs all of it at once)."""
104
+ node = shutil.which("node")
105
+ if not node:
106
+ raise TypeScriptUnavailable("TypeScript files found, but Node.js isn't installed (https://nodejs.org).")
107
+ ts_path = find_typescript(root, node)
108
+ helper = pkg_files(__package__) / "ts_helper.js"
109
+ proc = subprocess.run(
110
+ [node, "--max-old-space-size=4096", str(helper), str(root), ts_path, json.dumps(ignore)],
111
+ capture_output=True,
112
+ text=True,
113
+ encoding="utf-8",
114
+ timeout=1800,
115
+ )
116
+ if proc.returncode != 0:
117
+ raise RuntimeError(f"The TypeScript analyzer failed:\n{proc.stderr.strip()[-2000:]}")
118
+ return json.loads(proc.stdout)