unknot 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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +203 -0
- package/bin/unknot.mjs +5 -0
- package/dist/allow.js +46 -0
- package/dist/cli.js +189 -0
- package/dist/config.js +36 -0
- package/dist/hook.js +84 -0
- package/dist/init.js +46 -0
- package/dist/model.js +525 -0
- package/dist/projects.js +133 -0
- package/dist/report.js +58 -0
- package/dist/rules/classes.js +124 -0
- package/dist/rules/graph.js +203 -0
- package/dist/rules/index.js +28 -0
- package/dist/rules/react.js +63 -0
- package/dist/rules/shape.js +74 -0
- package/dist/rules/types.js +14 -0
- package/dist/score.js +34 -0
- package/dist/sfc.js +33 -0
- package/package.json +67 -0
package/dist/model.js
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import ts from 'typescript';
|
|
3
|
+
import { isVirtual, realName } from "./sfc.js";
|
|
4
|
+
export function emptyModel(root) {
|
|
5
|
+
return { root, files: new Set(), imports: new Map(), classes: new Map(), fieldUses: new Map(), classRefs: new Map(), forwards: new Map(), lines: new Map(), injections: [], forwardRefs: [], components: new Map() };
|
|
6
|
+
}
|
|
7
|
+
const hasModifier = (node, kind) => !!ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some((m) => m.kind === kind);
|
|
8
|
+
const isHidden = (node) => hasModifier(node, ts.SyntaxKind.PrivateKeyword) || hasModifier(node, ts.SyntaxKind.ProtectedKeyword) || hasModifier(node, ts.SyntaxKind.StaticKeyword) || hasModifier(node, ts.SyntaxKind.ReadonlyKeyword);
|
|
9
|
+
const isCallable = (init) => !!init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init) || ts.isIdentifier(init));
|
|
10
|
+
const lineOf = (node) => node.getSourceFile().getLineAndCharacterOfPosition(node.getStart()).line + 1;
|
|
11
|
+
function memberName(name) {
|
|
12
|
+
if (!name)
|
|
13
|
+
return null;
|
|
14
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name))
|
|
15
|
+
return name.text;
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
function classOf(node) {
|
|
19
|
+
for (let n = node.parent; n; n = n.parent)
|
|
20
|
+
if (ts.isClassDeclaration(n) || ts.isClassExpression(n))
|
|
21
|
+
return n;
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
function fieldClass(decl) {
|
|
25
|
+
if (ts.isPropertyDeclaration(decl) && (ts.isClassDeclaration(decl.parent) || ts.isClassExpression(decl.parent)))
|
|
26
|
+
return decl.parent;
|
|
27
|
+
if (ts.isParameter(decl) && ts.isConstructorDeclaration(decl.parent) && ts.isParameterPropertyDeclaration(decl, decl.parent))
|
|
28
|
+
return decl.parent.parent;
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function topLevelName(decl) {
|
|
32
|
+
if ((ts.isFunctionDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isEnumDeclaration(decl)) && ts.isSourceFile(decl.parent))
|
|
33
|
+
return decl.name?.text ?? null;
|
|
34
|
+
if (ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name) && ts.isVariableDeclarationList(decl.parent) && ts.isVariableStatement(decl.parent.parent) && ts.isSourceFile(decl.parent.parent.parent))
|
|
35
|
+
return decl.name.text;
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
function isDeclarationName(node) {
|
|
39
|
+
const p = node.parent;
|
|
40
|
+
return !!p && p.name === node && !ts.isPropertyAccessExpression(p) && !ts.isMetaProperty(p) && !ts.isShorthandPropertyAssignment(p);
|
|
41
|
+
}
|
|
42
|
+
function forwardTarget(fn) {
|
|
43
|
+
if (!fn.body || fn.parameters.length === 0)
|
|
44
|
+
return null;
|
|
45
|
+
if (ts.canHaveDecorators(fn) && ts.getDecorators(fn)?.length)
|
|
46
|
+
return null;
|
|
47
|
+
let expr;
|
|
48
|
+
if (ts.isBlock(fn.body)) {
|
|
49
|
+
if (fn.body.statements.length !== 1)
|
|
50
|
+
return null;
|
|
51
|
+
const st = fn.body.statements[0];
|
|
52
|
+
expr = ts.isReturnStatement(st) ? st.expression : ts.isExpressionStatement(st) ? st.expression : undefined;
|
|
53
|
+
}
|
|
54
|
+
else
|
|
55
|
+
expr = fn.body;
|
|
56
|
+
while (expr && (ts.isAwaitExpression(expr) || ts.isParenthesizedExpression(expr)))
|
|
57
|
+
expr = expr.expression;
|
|
58
|
+
if (!expr || !ts.isCallExpression(expr) || expr.arguments.length !== fn.parameters.length)
|
|
59
|
+
return null;
|
|
60
|
+
const same = fn.parameters.every((p, i) => {
|
|
61
|
+
const a = expr.arguments[i];
|
|
62
|
+
return ts.isIdentifier(p.name) && !p.dotDotDotToken && ts.isIdentifier(a) && a.text === p.name.text;
|
|
63
|
+
});
|
|
64
|
+
if (!same)
|
|
65
|
+
return null;
|
|
66
|
+
const callee = expr.expression;
|
|
67
|
+
if (ts.isPropertyAccessExpression(callee) && callee.expression.kind === ts.SyntaxKind.SuperKeyword)
|
|
68
|
+
return null;
|
|
69
|
+
return callee;
|
|
70
|
+
}
|
|
71
|
+
function isData(st) {
|
|
72
|
+
if (!ts.isVariableStatement(st))
|
|
73
|
+
return false;
|
|
74
|
+
const plain = (init) => {
|
|
75
|
+
while (init && (ts.isAsExpression(init) || ts.isSatisfiesExpression(init) || ts.isParenthesizedExpression(init)))
|
|
76
|
+
init = init.expression;
|
|
77
|
+
if (!init)
|
|
78
|
+
return false;
|
|
79
|
+
if (ts.isNewExpression(init) || ts.isCallExpression(init))
|
|
80
|
+
return !!init.arguments?.length && init.arguments.every(plain);
|
|
81
|
+
if (ts.isStringLiteralLike(init) || ts.isTemplateExpression(init))
|
|
82
|
+
return true;
|
|
83
|
+
if (!ts.isObjectLiteralExpression(init) && !ts.isArrayLiteralExpression(init))
|
|
84
|
+
return false;
|
|
85
|
+
let code = false;
|
|
86
|
+
each(init, (node) => {
|
|
87
|
+
if (ts.isFunctionLike(node) || ts.isClassExpression(node))
|
|
88
|
+
code = true;
|
|
89
|
+
return !code;
|
|
90
|
+
});
|
|
91
|
+
return !code;
|
|
92
|
+
};
|
|
93
|
+
return st.declarationList.declarations.every((d) => plain(d.initializer));
|
|
94
|
+
}
|
|
95
|
+
function each(root, fn) {
|
|
96
|
+
const stack = [root];
|
|
97
|
+
while (stack.length) {
|
|
98
|
+
const node = stack.pop();
|
|
99
|
+
if (fn(node) === false)
|
|
100
|
+
continue;
|
|
101
|
+
const at = stack.length;
|
|
102
|
+
ts.forEachChild(node, (child) => {
|
|
103
|
+
stack.push(child);
|
|
104
|
+
});
|
|
105
|
+
for (let i = at, j = stack.length - 1; i < j; i++, j--)
|
|
106
|
+
[stack[i], stack[j]] = [stack[j], stack[i]];
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'add', 'delete', 'clear']);
|
|
110
|
+
const COLLECTIONS = new Set(['Array', 'Map', 'Set', 'WeakMap', 'WeakSet']);
|
|
111
|
+
const HANDLER_SLOT = /^on[A-Z_a-z]/;
|
|
112
|
+
function insideFunction(node) {
|
|
113
|
+
for (let p = node.parent; p; p = p.parent)
|
|
114
|
+
if (ts.isFunctionLike(p))
|
|
115
|
+
return true;
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
function rootOf(expr) {
|
|
119
|
+
let cur = expr;
|
|
120
|
+
while (ts.isPropertyAccessExpression(cur))
|
|
121
|
+
cur = cur.expression;
|
|
122
|
+
return cur;
|
|
123
|
+
}
|
|
124
|
+
function unwrapped(expr) {
|
|
125
|
+
let cur = expr;
|
|
126
|
+
while ((ts.isNonNullExpression(cur.parent) || ts.isAsExpression(cur.parent) || ts.isParenthesizedExpression(cur.parent) || ts.isSatisfiesExpression(cur.parent)) && cur.parent.expression === cur)
|
|
127
|
+
cur = cur.parent;
|
|
128
|
+
return cur;
|
|
129
|
+
}
|
|
130
|
+
function assigned(target) {
|
|
131
|
+
const holder = target.parent;
|
|
132
|
+
if (ts.isBinaryExpression(holder))
|
|
133
|
+
return holder.left === target && holder.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && holder.operatorToken.kind <= ts.SyntaxKind.LastAssignment;
|
|
134
|
+
if (ts.isPrefixUnaryExpression(holder) || ts.isPostfixUnaryExpression(holder))
|
|
135
|
+
return holder.operator === ts.SyntaxKind.PlusPlusToken || holder.operator === ts.SyntaxKind.MinusMinusToken;
|
|
136
|
+
return ts.isDeleteExpression(holder);
|
|
137
|
+
}
|
|
138
|
+
function isMutation(name, checker) {
|
|
139
|
+
const access = name.parent;
|
|
140
|
+
if (!ts.isPropertyAccessExpression(access) || access.name !== name || access.expression.kind === ts.SyntaxKind.ThisKeyword)
|
|
141
|
+
return false;
|
|
142
|
+
const whole = unwrapped(access);
|
|
143
|
+
if (assigned(whole))
|
|
144
|
+
return !(HANDLER_SLOT.test(name.text) && checker.getNonNullableType(checker.getTypeAtLocation(access)).getCallSignatures().length > 0);
|
|
145
|
+
const outer = whole.parent;
|
|
146
|
+
if (ts.isElementAccessExpression(outer) && outer.expression === whole)
|
|
147
|
+
return assigned(unwrapped(outer));
|
|
148
|
+
if (!ts.isPropertyAccessExpression(outer) || outer.expression !== whole)
|
|
149
|
+
return false;
|
|
150
|
+
if (assigned(unwrapped(outer)))
|
|
151
|
+
return true;
|
|
152
|
+
if (!MUTATORS.has(outer.name.text) || !ts.isCallExpression(outer.parent) || outer.parent.expression !== outer)
|
|
153
|
+
return false;
|
|
154
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(access));
|
|
155
|
+
return checker.isArrayType(type) || COLLECTIONS.has(type.getSymbol()?.name ?? '');
|
|
156
|
+
}
|
|
157
|
+
function heritage(node, token) {
|
|
158
|
+
return (node.heritageClauses ?? []).filter((h) => h.token === token).flatMap((h) => [...h.types]);
|
|
159
|
+
}
|
|
160
|
+
function decorated(node) {
|
|
161
|
+
return ts.canHaveDecorators(node) && !!ts.getDecorators(node)?.length;
|
|
162
|
+
}
|
|
163
|
+
function metadataSite(type) {
|
|
164
|
+
const holder = type.parent;
|
|
165
|
+
if (ts.isParameter(holder) && holder.type === type) {
|
|
166
|
+
const fn = holder.parent;
|
|
167
|
+
if (ts.isConstructorDeclaration(fn))
|
|
168
|
+
return decorated(fn.parent) || fn.parameters.some(decorated);
|
|
169
|
+
return ts.isMethodDeclaration(fn) && (decorated(fn) || fn.parameters.some(decorated));
|
|
170
|
+
}
|
|
171
|
+
if (ts.isPropertyDeclaration(holder) && holder.type === type)
|
|
172
|
+
return decorated(holder);
|
|
173
|
+
return ts.isMethodDeclaration(holder) && holder.type === type && decorated(holder);
|
|
174
|
+
}
|
|
175
|
+
function typeSite(node) {
|
|
176
|
+
for (let p = node.parent; p; p = p.parent) {
|
|
177
|
+
if (ts.isExpressionWithTypeArguments(p))
|
|
178
|
+
return !ts.isHeritageClause(p.parent) || p.parent.token === ts.SyntaxKind.ImplementsKeyword || ts.isInterfaceDeclaration(p.parent.parent);
|
|
179
|
+
if (ts.isTypeNode(p))
|
|
180
|
+
return ts.isTypeReferenceNode(p) && p.typeName === node ? p : true;
|
|
181
|
+
if (ts.isInterfaceDeclaration(p) || ts.isTypeAliasDeclaration(p))
|
|
182
|
+
return true;
|
|
183
|
+
if (ts.isFunctionLike(p) || ts.isClassLike(p) || ts.isBlock(p) || ts.isSourceFile(p))
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
const DI_PACKAGES = new Set(['@nestjs/common', '@angular/core', 'tsyringe', 'inversify']);
|
|
189
|
+
function unwrapComponent(init) {
|
|
190
|
+
let e = init;
|
|
191
|
+
for (let i = 0; e && i < 4; i++) {
|
|
192
|
+
if (ts.isArrowFunction(e) || ts.isFunctionExpression(e))
|
|
193
|
+
return e;
|
|
194
|
+
if (ts.isCallExpression(e))
|
|
195
|
+
e = e.arguments[0];
|
|
196
|
+
else if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
|
|
197
|
+
e = e.expression;
|
|
198
|
+
else
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
function typeOnlyImport(node) {
|
|
204
|
+
if (ts.isExportDeclaration(node))
|
|
205
|
+
return node.isTypeOnly || (!!node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements.length > 0 && node.exportClause.elements.every((e) => e.isTypeOnly));
|
|
206
|
+
const clause = node.importClause;
|
|
207
|
+
if (!clause)
|
|
208
|
+
return false;
|
|
209
|
+
if (clause.isTypeOnly)
|
|
210
|
+
return true;
|
|
211
|
+
if (clause.name)
|
|
212
|
+
return false;
|
|
213
|
+
const named = clause.namedBindings;
|
|
214
|
+
return !!named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((e) => e.isTypeOnly);
|
|
215
|
+
}
|
|
216
|
+
export function collect(model, program, accept) {
|
|
217
|
+
const checker = program.getTypeChecker();
|
|
218
|
+
const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
|
|
219
|
+
const rel = (file) => path.relative(model.root, realName(file)).split(path.sep).join('/');
|
|
220
|
+
const sources = program.getSourceFiles().filter((sf) => accept(sf.fileName));
|
|
221
|
+
const inScope = new Set(sources.map((sf) => sf.fileName));
|
|
222
|
+
for (const sf of sources)
|
|
223
|
+
model.files.add(rel(sf.fileName));
|
|
224
|
+
const bump = (map, key, make) => {
|
|
225
|
+
let v = map.get(key);
|
|
226
|
+
if (!v)
|
|
227
|
+
map.set(key, (v = make()));
|
|
228
|
+
return v;
|
|
229
|
+
};
|
|
230
|
+
const classKey = (c) => `${rel(c.getSourceFile().fileName)}#${c.name?.text ?? 'anonymous'}`;
|
|
231
|
+
for (const sf of sources) {
|
|
232
|
+
const file = rel(sf.fileName);
|
|
233
|
+
const forwardOf = (fn, name) => {
|
|
234
|
+
const callee = forwardTarget(fn);
|
|
235
|
+
if (!callee)
|
|
236
|
+
return null;
|
|
237
|
+
const root = rootOf(callee);
|
|
238
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(root)) {
|
|
239
|
+
const holder = checker.getSymbolAtLocation(root);
|
|
240
|
+
if (holder && !(holder.flags & ts.SymbolFlags.Alias) && holder.declarations?.some((d) => d.getSourceFile() === sf))
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
let sym = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(callee) ? callee.name : callee);
|
|
244
|
+
if (sym && sym.flags & ts.SymbolFlags.Alias)
|
|
245
|
+
sym = checker.getAliasedSymbol(sym);
|
|
246
|
+
const home = (sym?.valueDeclaration ?? sym?.declarations?.[0])?.getSourceFile().fileName;
|
|
247
|
+
if (!home || !inScope.has(home) || home === sf.fileName)
|
|
248
|
+
return null;
|
|
249
|
+
return { name, line: lineOf(fn), target: `${callee.getText()} (${rel(home)})` };
|
|
250
|
+
};
|
|
251
|
+
const forward = (fn, name) => {
|
|
252
|
+
const found = forwardOf(fn, name);
|
|
253
|
+
if (!found)
|
|
254
|
+
return;
|
|
255
|
+
const list = bump(model.forwards, file, () => []);
|
|
256
|
+
if (!list.some((f) => f.name === name))
|
|
257
|
+
list.push(found);
|
|
258
|
+
};
|
|
259
|
+
for (const st of sf.statements) {
|
|
260
|
+
if (ts.isFunctionDeclaration(st) && st.name)
|
|
261
|
+
forward(st, st.name.text);
|
|
262
|
+
if (ts.isVariableStatement(st))
|
|
263
|
+
for (const d of st.declarationList.declarations)
|
|
264
|
+
if (ts.isIdentifier(d.name) && d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer)))
|
|
265
|
+
forward(d.initializer, d.name.text);
|
|
266
|
+
if (ts.isClassDeclaration(st) && st.name) {
|
|
267
|
+
const abstract = (p) => !!p.declarations?.some((d) => hasModifier(d, ts.SyntaxKind.AbstractKeyword));
|
|
268
|
+
const promised = new Set([
|
|
269
|
+
...heritage(st, ts.SyntaxKind.ImplementsKeyword).flatMap((t) => checker.getTypeAtLocation(t).getProperties()),
|
|
270
|
+
...heritage(st, ts.SyntaxKind.ExtendsKeyword).flatMap((t) => checker.getTypeAtLocation(t).getProperties().filter(abstract)),
|
|
271
|
+
].map((p) => p.name));
|
|
272
|
+
const parents = [...heritage(st, ts.SyntaxKind.ImplementsKeyword), ...heritage(st, ts.SyntaxKind.ExtendsKeyword)];
|
|
273
|
+
if (parents.some((t) => checker.getTypeAtLocation(t).flags & ts.TypeFlags.Any))
|
|
274
|
+
continue;
|
|
275
|
+
const open = st.members.filter((m) => ts.isMethodDeclaration(m) && ts.isIdentifier(m.name) && !isHidden(m));
|
|
276
|
+
const passing = open.filter((m) => !promised.has(m.name.text) && forwardOf(m, st.name.text));
|
|
277
|
+
if (passing.length * 2 >= open.length)
|
|
278
|
+
for (const m of passing)
|
|
279
|
+
forward(m, `${st.name.text}.${m.name.text}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const lineAt = (pos) => sf.getLineAndCharacterOfPosition(pos).line;
|
|
283
|
+
const coded = new Set();
|
|
284
|
+
for (const st of sf.statements) {
|
|
285
|
+
if (isData(st))
|
|
286
|
+
continue;
|
|
287
|
+
const from = st.getStart(sf);
|
|
288
|
+
scanner.setText(sf.text, from, st.end - from);
|
|
289
|
+
while (scanner.scan() !== ts.SyntaxKind.EndOfFileToken)
|
|
290
|
+
for (let line = lineAt(scanner.getTokenStart()), last = lineAt(scanner.getTokenEnd()); line <= last; line++)
|
|
291
|
+
coded.add(line);
|
|
292
|
+
}
|
|
293
|
+
model.lines.set(file, coded.size);
|
|
294
|
+
const diForwardRef = sf.statements.some((st) => ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && DI_PACKAGES.has(st.moduleSpecifier.text) && /\bforwardRef\b/.test(st.importClause?.getText() ?? ''));
|
|
295
|
+
const componentKeyOf = (tag) => {
|
|
296
|
+
if (!ts.isIdentifier(tag) || !/^[A-Z]/.test(tag.text))
|
|
297
|
+
return undefined;
|
|
298
|
+
let sym = checker.getSymbolAtLocation(tag);
|
|
299
|
+
if (sym && sym.flags & ts.SymbolFlags.Alias)
|
|
300
|
+
sym = checker.getAliasedSymbol(sym);
|
|
301
|
+
const decl = sym?.valueDeclaration ?? sym?.declarations?.[0];
|
|
302
|
+
if (!decl || !inScope.has(decl.getSourceFile().fileName))
|
|
303
|
+
return undefined;
|
|
304
|
+
const name = topLevelName(decl);
|
|
305
|
+
return name ? `${rel(decl.getSourceFile().fileName)}#${name}` : undefined;
|
|
306
|
+
};
|
|
307
|
+
const component = (name, fn) => {
|
|
308
|
+
const first = fn.parameters[0];
|
|
309
|
+
if (!first || !fn.body)
|
|
310
|
+
return;
|
|
311
|
+
const locals = new Map();
|
|
312
|
+
let bag;
|
|
313
|
+
if (ts.isObjectBindingPattern(first.name)) {
|
|
314
|
+
for (const el of first.name.elements) {
|
|
315
|
+
if (el.dotDotDotToken)
|
|
316
|
+
return;
|
|
317
|
+
if (!ts.isIdentifier(el.name))
|
|
318
|
+
continue;
|
|
319
|
+
const sym = checker.getSymbolAtLocation(el.name);
|
|
320
|
+
if (sym)
|
|
321
|
+
locals.set(sym, el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : el.name.text);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
else if (ts.isIdentifier(first.name))
|
|
325
|
+
bag = checker.getSymbolAtLocation(first.name);
|
|
326
|
+
else
|
|
327
|
+
return;
|
|
328
|
+
const props = new Map();
|
|
329
|
+
let jsx = false;
|
|
330
|
+
let opaque = false;
|
|
331
|
+
const note = (prop, value) => {
|
|
332
|
+
const use = bump(props, prop, () => ({ line: lineOf(value), used: false, passes: [] }));
|
|
333
|
+
const holder = value.parent;
|
|
334
|
+
if (ts.isJsxExpression(holder) && ts.isJsxAttribute(holder.parent) && ts.isIdentifier(holder.parent.name)) {
|
|
335
|
+
const child = componentKeyOf(holder.parent.parent.parent.tagName);
|
|
336
|
+
if (child) {
|
|
337
|
+
use.passes.push({ child, attr: holder.parent.name.text, line: lineOf(value) });
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
use.used = true;
|
|
342
|
+
};
|
|
343
|
+
const walk = (node) => {
|
|
344
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
|
|
345
|
+
jsx = true;
|
|
346
|
+
if (ts.isIdentifier(node) && !isDeclarationName(node)) {
|
|
347
|
+
const sym = ts.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
348
|
+
const prop = sym && locals.get(sym);
|
|
349
|
+
if (prop)
|
|
350
|
+
note(prop, node);
|
|
351
|
+
else if (sym && sym === bag) {
|
|
352
|
+
if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)
|
|
353
|
+
note(node.parent.name.text, node.parent);
|
|
354
|
+
else
|
|
355
|
+
opaque = true;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
each(fn.body, walk);
|
|
360
|
+
if (jsx && !opaque)
|
|
361
|
+
model.components.set(`${file}#${name}`, { key: `${file}#${name}`, name, file, line: lineOf(fn), props });
|
|
362
|
+
};
|
|
363
|
+
if (sf.languageVariant === ts.LanguageVariant.JSX) {
|
|
364
|
+
for (const st of sf.statements) {
|
|
365
|
+
if (ts.isFunctionDeclaration(st) && st.name && /^[A-Z]/.test(st.name.text))
|
|
366
|
+
component(st.name.text, st);
|
|
367
|
+
if (ts.isVariableStatement(st))
|
|
368
|
+
for (const d of st.declarationList.declarations) {
|
|
369
|
+
const fn = ts.isIdentifier(d.name) && /^[A-Z]/.test(d.name.text) ? unwrapComponent(d.initializer) : null;
|
|
370
|
+
if (fn)
|
|
371
|
+
component(d.name.text, fn);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const valueUsed = new Set();
|
|
376
|
+
const pending = [];
|
|
377
|
+
const options = program.getCompilerOptions();
|
|
378
|
+
const keepsImports = !!options.verbatimModuleSyntax || isVirtual(sf.fileName) || /\.[cm]?jsx?$/.test(sf.fileName);
|
|
379
|
+
const metadata = !!options.emitDecoratorMetadata || sf.statements.some((st) => ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && st.moduleSpecifier.text === '@angular/core');
|
|
380
|
+
const keepsConstEnums = !!options.isolatedModules || !!options.preserveConstEnums || keepsImports;
|
|
381
|
+
const target = (node) => {
|
|
382
|
+
const sym = ts.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
383
|
+
return { local: sym, real: sym && sym.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym) : sym };
|
|
384
|
+
};
|
|
385
|
+
const erased = (node) => {
|
|
386
|
+
const site = typeSite(node);
|
|
387
|
+
const { real } = target(node);
|
|
388
|
+
if (site === false)
|
|
389
|
+
return !!real && !!(real.flags & ts.SymbolFlags.ConstEnum) && !keepsConstEnums;
|
|
390
|
+
return !(site !== true && metadata && metadataSite(site) && !!real && !!(real.flags & ts.SymbolFlags.Class));
|
|
391
|
+
};
|
|
392
|
+
const edge = (target) => {
|
|
393
|
+
if (target && inScope.has(target) && target !== sf.fileName)
|
|
394
|
+
bump(model.imports, file, () => new Set()).add(rel(target));
|
|
395
|
+
};
|
|
396
|
+
const collaborator = (p, injected) => {
|
|
397
|
+
if (!p.type)
|
|
398
|
+
return injected && decorated(p);
|
|
399
|
+
const type = checker.getTypeAtLocation(p.type);
|
|
400
|
+
const sym = type.getSymbol();
|
|
401
|
+
if (!sym)
|
|
402
|
+
return injected && ts.isTypeReferenceNode(p.type) && !!(type.flags & ts.TypeFlags.Any);
|
|
403
|
+
const decl = sym.declarations?.[0];
|
|
404
|
+
if (!decl || program.isSourceFileDefaultLibrary(decl.getSourceFile()))
|
|
405
|
+
return false;
|
|
406
|
+
return !!(sym.flags & ts.SymbolFlags.Class) || (injected && !!(sym.flags & ts.SymbolFlags.Interface));
|
|
407
|
+
};
|
|
408
|
+
const visit = (node) => {
|
|
409
|
+
if (diForwardRef && ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'forwardRef' && node.arguments[0]) {
|
|
410
|
+
const arg = node.arguments[0];
|
|
411
|
+
const named = (ts.isArrowFunction(arg) && !ts.isBlock(arg.body) ? arg.body : arg).getText();
|
|
412
|
+
const owner = classOf(node)?.name?.text ?? path.posix.basename(file);
|
|
413
|
+
const body = ts.isArrowFunction(arg) && ts.isIdentifier(arg.body) ? checker.getSymbolAtLocation(arg.body) : undefined;
|
|
414
|
+
const home = (body && body.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(body) : body)?.declarations?.[0]?.getSourceFile();
|
|
415
|
+
if (named !== owner && home !== sf)
|
|
416
|
+
model.forwardRefs.push({ file, line: lineOf(node), owner, target: named });
|
|
417
|
+
}
|
|
418
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0]) && !insideFunction(node)) {
|
|
419
|
+
edge(ts.resolveModuleName(node.arguments[0].text, sf.fileName, options, ts.sys).resolvedModule?.resolvedFileName);
|
|
420
|
+
}
|
|
421
|
+
if (ts.isExportSpecifier(node) && !node.isTypeOnly && !node.parent.parent.moduleSpecifier && !node.parent.parent.isTypeOnly) {
|
|
422
|
+
const local = checker.getExportSpecifierLocalTargetSymbol(node);
|
|
423
|
+
if (local)
|
|
424
|
+
valueUsed.add(local);
|
|
425
|
+
}
|
|
426
|
+
if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) && !node.isTypeOnly) {
|
|
427
|
+
const from = checker.getSymbolAtLocation(node.moduleReference.expression)?.declarations?.[0]?.getSourceFile().fileName;
|
|
428
|
+
const binding = checker.getSymbolAtLocation(node.name);
|
|
429
|
+
if (from)
|
|
430
|
+
pending.push({ target: from, bindings: binding ? [binding] : [], always: keepsImports || !binding });
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) {
|
|
434
|
+
const target = checker.getSymbolAtLocation(node.moduleSpecifier)?.declarations?.[0]?.getSourceFile().fileName;
|
|
435
|
+
if (target && !typeOnlyImport(node)) {
|
|
436
|
+
const clause = ts.isImportDeclaration(node) ? node.importClause : undefined;
|
|
437
|
+
const names = clause ? [clause.name, clause.namedBindings && ts.isNamespaceImport(clause.namedBindings) ? clause.namedBindings.name : undefined, ...(clause.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements.filter((e) => !e.isTypeOnly).map((e) => e.name) : [])] : [];
|
|
438
|
+
const bindings = names.map((n) => n && checker.getSymbolAtLocation(n)).filter((b) => !!b);
|
|
439
|
+
pending.push({ target, bindings, always: !clause || keepsImports });
|
|
440
|
+
}
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
if (ts.isClassDeclaration(node) && node.name) {
|
|
444
|
+
const info = { key: classKey(node), name: node.name.text, file, line: lineOf(node), fields: new Map(), methods: 0 };
|
|
445
|
+
const contract = new Set();
|
|
446
|
+
for (const h of node.heritageClauses ?? [])
|
|
447
|
+
for (const t of h.types)
|
|
448
|
+
for (const p of checker.getTypeAtLocation(t).getProperties())
|
|
449
|
+
contract.add(p.name);
|
|
450
|
+
for (const m of node.members) {
|
|
451
|
+
if (ts.isPropertyDeclaration(m) && isCallable(m.initializer))
|
|
452
|
+
info.methods++;
|
|
453
|
+
else if (ts.isPropertyDeclaration(m) && !isHidden(m) && !ts.isPrivateIdentifier(m.name)) {
|
|
454
|
+
const n = memberName(m.name);
|
|
455
|
+
if (n && !contract.has(n))
|
|
456
|
+
info.fields.set(n, lineOf(m));
|
|
457
|
+
}
|
|
458
|
+
else if (ts.isMethodDeclaration(m) || ts.isGetAccessorDeclaration(m) || ts.isSetAccessorDeclaration(m))
|
|
459
|
+
info.methods++;
|
|
460
|
+
else if (ts.isConstructorDeclaration(m)) {
|
|
461
|
+
for (const p of m.parameters)
|
|
462
|
+
if (ts.isParameterPropertyDeclaration(p, m) && !isHidden(p)) {
|
|
463
|
+
const n = memberName(p.name);
|
|
464
|
+
if (n && !contract.has(n))
|
|
465
|
+
info.fields.set(n, lineOf(p));
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
model.classes.set(info.key, info);
|
|
470
|
+
const ctor = node.members.find(ts.isConstructorDeclaration);
|
|
471
|
+
const injected = decorated(node) || !!ctor?.parameters.some(decorated);
|
|
472
|
+
const deps = [
|
|
473
|
+
...(ctor ? ctor.parameters.filter((p) => collaborator(p, injected)).map((p) => p.type?.getText() ?? p.name.getText()) : []),
|
|
474
|
+
...node.members.filter((m) => ts.isPropertyDeclaration(m) && !!m.initializer && ts.isCallExpression(m.initializer) && ts.isIdentifier(m.initializer.expression) && m.initializer.expression.text === 'inject').map((m) => m.initializer.getText()),
|
|
475
|
+
];
|
|
476
|
+
if (deps.length)
|
|
477
|
+
model.injections.push({ key: info.key, name: info.name, file, line: lineOf(ctor ?? node), deps });
|
|
478
|
+
}
|
|
479
|
+
if (ts.isIdentifier(node) && !isDeclarationName(node)) {
|
|
480
|
+
const typed = erased(node);
|
|
481
|
+
if (!typed) {
|
|
482
|
+
const { local } = target(node);
|
|
483
|
+
if (local)
|
|
484
|
+
valueUsed.add(local);
|
|
485
|
+
}
|
|
486
|
+
use(node, typed);
|
|
487
|
+
}
|
|
488
|
+
return true;
|
|
489
|
+
};
|
|
490
|
+
const use = (node, typed) => {
|
|
491
|
+
let sym = checker.getSymbolAtLocation(node);
|
|
492
|
+
if (!sym)
|
|
493
|
+
return;
|
|
494
|
+
if (sym.flags & ts.SymbolFlags.Alias)
|
|
495
|
+
sym = checker.getAliasedSymbol(sym);
|
|
496
|
+
const decl = sym.valueDeclaration ?? sym.declarations?.[0];
|
|
497
|
+
if (!decl)
|
|
498
|
+
return;
|
|
499
|
+
const declFile = decl.getSourceFile().fileName;
|
|
500
|
+
if (!inScope.has(declFile) || declFile === sf.fileName)
|
|
501
|
+
return;
|
|
502
|
+
const owner = fieldClass(decl);
|
|
503
|
+
if (owner && owner.name && isMutation(node, checker)) {
|
|
504
|
+
const field = memberName(decl.name);
|
|
505
|
+
if (field) {
|
|
506
|
+
const byField = bump(model.fieldUses, classKey(owner), () => new Map());
|
|
507
|
+
const byFile = bump(byField, field, () => new Map());
|
|
508
|
+
if (!byFile.has(file))
|
|
509
|
+
byFile.set(file, lineOf(node));
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const from = classOf(node);
|
|
513
|
+
const to = ts.isClassDeclaration(decl) ? decl : classOf(decl);
|
|
514
|
+
if (!typed && from?.name && to?.name && from !== to) {
|
|
515
|
+
const refs = bump(model.classRefs, classKey(from), () => new Map());
|
|
516
|
+
if (!refs.has(classKey(to)))
|
|
517
|
+
refs.set(classKey(to), { file, line: lineOf(node) });
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
each(sf, visit);
|
|
521
|
+
for (const imp of pending)
|
|
522
|
+
if (imp.always || imp.bindings.some((b) => valueUsed.has(b)))
|
|
523
|
+
edge(imp.target);
|
|
524
|
+
}
|
|
525
|
+
}
|
package/dist/projects.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { isSfc, isVirtual, realName, scriptOf } from "./sfc.js";
|
|
5
|
+
const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', '.git', '.next', '.nuxt', '.output', '.svelte-kit', '.astro', 'coverage', 'out', '.turbo', 'vendor']);
|
|
6
|
+
const TEST_FILE = /(\.|\/)(spec|test|e2e|stories|bench|vitest|cy|test-d|spec-d)\.[cm]?[jt]sx?$|\/(__tests__|__mocks__|test|tests|testing|fixtures|e2e)\//;
|
|
7
|
+
export function findTsconfigs(root) {
|
|
8
|
+
const found = [];
|
|
9
|
+
const walk = (dir) => {
|
|
10
|
+
const own = path.join(dir, 'tsconfig.json');
|
|
11
|
+
if (fs.existsSync(own))
|
|
12
|
+
found.push(own);
|
|
13
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
14
|
+
if (entry.isDirectory() && !SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.'))
|
|
15
|
+
walk(path.join(dir, entry.name));
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
walk(root);
|
|
19
|
+
return found;
|
|
20
|
+
}
|
|
21
|
+
const SOURCE = /\.[cm]?[jt]sx?$/;
|
|
22
|
+
export function looseProject(root) {
|
|
23
|
+
const files = [];
|
|
24
|
+
const components = [];
|
|
25
|
+
const walk = (at) => {
|
|
26
|
+
for (const entry of fs.readdirSync(at, { withFileTypes: true })) {
|
|
27
|
+
const full = path.join(at, entry.name);
|
|
28
|
+
if (entry.isDirectory()) {
|
|
29
|
+
if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.'))
|
|
30
|
+
walk(full);
|
|
31
|
+
}
|
|
32
|
+
else if (isSfc(entry.name))
|
|
33
|
+
components.push(full);
|
|
34
|
+
else if (SOURCE.test(entry.name) && !entry.name.endsWith('.d.ts'))
|
|
35
|
+
files.push(full);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
walk(root);
|
|
39
|
+
if (!files.length && !components.length)
|
|
40
|
+
return null;
|
|
41
|
+
const options = { allowJs: true, jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, noEmit: true, skipLibCheck: true };
|
|
42
|
+
return { parsed: { options, fileNames: files, errors: [] }, components };
|
|
43
|
+
}
|
|
44
|
+
function findSfc(dir) {
|
|
45
|
+
const out = [];
|
|
46
|
+
const walk = (at) => {
|
|
47
|
+
for (const entry of fs.readdirSync(at, { withFileTypes: true })) {
|
|
48
|
+
if (entry.isDirectory()) {
|
|
49
|
+
if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.'))
|
|
50
|
+
walk(path.join(at, entry.name));
|
|
51
|
+
}
|
|
52
|
+
else if (isSfc(entry.name))
|
|
53
|
+
out.push(path.join(at, entry.name));
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(dir);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
export function expandProject(configPath, seen = new Set()) {
|
|
60
|
+
const abs = path.resolve(configPath);
|
|
61
|
+
if (seen.has(abs))
|
|
62
|
+
return [];
|
|
63
|
+
seen.add(abs);
|
|
64
|
+
const parsed = ts.getParsedCommandLineOfConfigFile(abs, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => undefined });
|
|
65
|
+
if (!parsed)
|
|
66
|
+
return [];
|
|
67
|
+
const includesAll = !parsed.raw?.files || parsed.raw.files.length > 0 || parsed.raw.include;
|
|
68
|
+
const components = includesAll ? findSfc(path.dirname(abs)) : [];
|
|
69
|
+
const out = parsed.fileNames.length || components.length ? [{ parsed, components }] : [];
|
|
70
|
+
for (const ref of parsed.projectReferences ?? []) {
|
|
71
|
+
const stat = fs.statSync(ref.path, { throwIfNoEntry: false });
|
|
72
|
+
if (stat)
|
|
73
|
+
out.push(...expandProject(stat.isDirectory() ? path.join(ref.path, 'tsconfig.json') : ref.path, seen));
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
export function createProgram({ parsed, components }) {
|
|
78
|
+
const options = { ...parsed.options, noEmit: true };
|
|
79
|
+
const host = ts.createCompilerHost(options, true);
|
|
80
|
+
const scripts = new Map();
|
|
81
|
+
const script = (real) => {
|
|
82
|
+
if (!scripts.has(real)) {
|
|
83
|
+
const text = ts.sys.readFile(real);
|
|
84
|
+
if (text === undefined)
|
|
85
|
+
scripts.set(real, null);
|
|
86
|
+
else {
|
|
87
|
+
const { code, tsx } = scriptOf(real, text);
|
|
88
|
+
scripts.set(real, { name: real + (tsx ? '.tsx' : '.ts'), code });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return scripts.get(real);
|
|
92
|
+
};
|
|
93
|
+
const virtual = (name) => {
|
|
94
|
+
if (!isVirtual(name))
|
|
95
|
+
return null;
|
|
96
|
+
const found = script(realName(name));
|
|
97
|
+
return found && found.name === name ? found : null;
|
|
98
|
+
};
|
|
99
|
+
const fileExists = host.fileExists.bind(host);
|
|
100
|
+
const readFile = host.readFile.bind(host);
|
|
101
|
+
const getSourceFile = host.getSourceFile.bind(host);
|
|
102
|
+
host.fileExists = (name) => !!virtual(name) || fileExists(name);
|
|
103
|
+
host.readFile = (name) => virtual(name)?.code ?? readFile(name);
|
|
104
|
+
host.getSourceFile = (name, version, onError, fresh) => {
|
|
105
|
+
const found = virtual(name);
|
|
106
|
+
return found ? ts.createSourceFile(name, found.code, version, true, name.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS) : getSourceFile(name, version, onError, fresh);
|
|
107
|
+
};
|
|
108
|
+
if (components.length) {
|
|
109
|
+
const cache = ts.createModuleResolutionCache(host.getCurrentDirectory(), host.getCanonicalFileName, options);
|
|
110
|
+
const loose = { ...options, moduleResolution: ts.ModuleResolutionKind.Bundler, module: ts.ModuleKind.ESNext };
|
|
111
|
+
host.resolveModuleNameLiterals = (literals, containing, redirected, _options, sourceFile) => literals.map((literal) => {
|
|
112
|
+
const strict = ts.resolveModuleName(literal.text, containing, options, host, cache, redirected, ts.getModeForUsageLocation(sourceFile, literal, options));
|
|
113
|
+
return strict.resolvedModule || !isSfc(literal.text) ? strict : ts.resolveModuleName(literal.text, containing, loose, host);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const roots = [...parsed.fileNames, ...components.map((c) => script(c)?.name).filter((n) => !!n)];
|
|
117
|
+
return ts.createProgram({ rootNames: roots, options, projectReferences: parsed.projectReferences, host });
|
|
118
|
+
}
|
|
119
|
+
export function isSource(file, root, ignore) {
|
|
120
|
+
const real = realName(file);
|
|
121
|
+
const rel = path.relative(root, real).split(path.sep).join('/');
|
|
122
|
+
if (rel.startsWith('..') || real.endsWith('.d.ts') || real.endsWith('.json') || /node_modules/.test(real))
|
|
123
|
+
return false;
|
|
124
|
+
if (TEST_FILE.test('/' + rel) || /\.min\.[cm]?js$/.test(rel))
|
|
125
|
+
return false;
|
|
126
|
+
if (/\.[cm]?jsx?$/.test(rel) && rel.split('/').slice(0, -1).some((part) => SKIP_DIRS.has(part)))
|
|
127
|
+
return false;
|
|
128
|
+
return !ignore.some((re) => re.test(rel));
|
|
129
|
+
}
|
|
130
|
+
export function globToRegExp(glob) {
|
|
131
|
+
const re = glob.replace(/\*\*\/|\*\*|\*|\?|[.+^${}()|[\]\\]/g, (m) => (m === '**/' ? '(?:.*/)?' : m === '**' ? '.*' : m === '*' ? '[^/]*' : m === '?' ? '[^/]' : `\\${m}`));
|
|
132
|
+
return new RegExp(`^${re}$`);
|
|
133
|
+
}
|