mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
chore(server): db-call-graph --unawaited lists calls to async methods whose result is used without await
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Fixture for `db-call-graph.mjs --unawaited --root scripts/__fixtures__`. Not part of the
|
||||
* server build or its typecheck — it exists only so the detector has something small and
|
||||
* known-good/known-bad to run against. Three GOOD call shapes should produce no findings;
|
||||
* five BAD ones should each produce exactly one, with a distinct reason tag.
|
||||
*/
|
||||
|
||||
class Dep {
|
||||
async fetchValue(): Promise<number> {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
export class Sample {
|
||||
private dep: Dep = new Dep();
|
||||
|
||||
async loadOne(): Promise<number> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- GOOD (3): correctly consumed, nothing to report ----
|
||||
|
||||
async good1() {
|
||||
return await this.loadOne(); // awaited
|
||||
}
|
||||
|
||||
async good2() {
|
||||
return this.loadOne(); // returned directly — propagates the promise to the caller
|
||||
}
|
||||
|
||||
async good3() {
|
||||
await Promise.all([this.loadOne(), this.dep.fetchValue()]); // Promise.all combinator
|
||||
}
|
||||
|
||||
// ---- BAD (5): used without await, one per reason tag ----
|
||||
|
||||
async bad1() {
|
||||
const x = this.loadOne(); // stored-then-used
|
||||
return { x };
|
||||
}
|
||||
|
||||
async bad2() {
|
||||
console.log(this.dep.fetchValue()); // argument
|
||||
}
|
||||
|
||||
async bad3() {
|
||||
return { value: this.loadOne() }; // property
|
||||
}
|
||||
|
||||
async bad4() {
|
||||
if (this.loadOne()) {
|
||||
return 1;
|
||||
}
|
||||
return 0; // condition
|
||||
}
|
||||
|
||||
async bad5() {
|
||||
this.loadOne(); // statement — result discarded
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,33 @@
|
||||
* --tx every real `….transaction(` call site (the AST sees calls, so the six
|
||||
* prose mentions inside doc comments that `grep` finds are not here).
|
||||
* These are the sites R2 routes through `UnitOfWork.transactional`.
|
||||
* --unawaited every call expression of the form `this.<dep>.<m>(…)`,
|
||||
* `this.<m>(…)`, or `<importedFn>(…)` (imported from a relative path
|
||||
* resolving under `src/`) whose target resolves to an `async`
|
||||
* method/function, where the call's result is used without `await`
|
||||
* in a way that compiles under `strict: false` but is a live bug —
|
||||
* stored in a variable then read, passed as a plain argument, used
|
||||
* as an object-literal property value, tested in a condition or
|
||||
* comparison, or member-accessed. Each finding carries a reason tag
|
||||
* (`stored-then-used` / `argument` / `property` / `condition` /
|
||||
* `compared` / `member` / `statement` / `other`). It does NOT flag
|
||||
* `await x()`, `return x()` (any function), `void x()`, an argument
|
||||
* of `Promise.all/allSettled/race/any`, the concise body of an arrow
|
||||
* passed to `.map(` (the `Promise.all(arr.map(…))` pattern — but it
|
||||
* DOES flag that shape for `.filter/.find/.some/.every/.sort/.forEach`),
|
||||
* or a `.then(`/`.catch(`/`.finally(` chain (which also covers the
|
||||
* fire-and-forget-with-`.catch(` case). It is a lint-shaped finder
|
||||
* for shapes the type-aware ESLint rules (`no-floating-promises`,
|
||||
* `no-misused-promises`) cannot see under `strict: false` — see the
|
||||
* recipe for why those rules alone aren't enough during Phase 1.
|
||||
*
|
||||
* It exits 1 as soon as either list is non-empty, so a task can gate on it:
|
||||
* IT DOES NOT RESOLVE: calls through a `.bind` alias, a call reached
|
||||
* via a local variable holding a method/function reference, a call
|
||||
* on a dependency typed as an interface/token/union (same limit as
|
||||
* `--sync`), or a call to a `export default`-exported function. Those
|
||||
* stay the manual-grep's job — see the recipe.
|
||||
*
|
||||
* It exits 1 as soon as any requested list is non-empty, so a task can gate on it:
|
||||
* `node scripts/db-call-graph.mjs --sync --tx --domains nest/days,nest/budget`
|
||||
*
|
||||
* R0 EXCEPTIONS (never listed, by either flag): `DatabaseService` itself,
|
||||
@@ -42,18 +67,23 @@ const REPO = path.resolve(SERVER, '..');
|
||||
const require_ = createRequire(path.join(REPO, 'package.json'));
|
||||
const ts = require_('typescript');
|
||||
|
||||
const SRC = path.join(SERVER, 'src');
|
||||
let SRC = path.join(SERVER, 'src');
|
||||
|
||||
// ---------------------------------------------------------------- CLI
|
||||
function parseArgs(argv) {
|
||||
const opts = { sync: false, tx: false, domains: null, json: false };
|
||||
const opts = { sync: false, tx: false, unawaited: false, domains: null, json: false, root: null };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === '--sync') opts.sync = true;
|
||||
else if (a === '--tx') opts.tx = true;
|
||||
else if (a === '--unawaited') opts.unawaited = true;
|
||||
else if (a === '--json') opts.json = true;
|
||||
else if (a === '--domains') opts.domains = splitDomains(argv[++i]);
|
||||
else if (a.startsWith('--domains=')) opts.domains = splitDomains(a.slice('--domains='.length));
|
||||
// --root is intentionally undocumented: it exists so the __fixtures__ suite can point
|
||||
// the whole analysis at a tiny sample tree instead of server/src.
|
||||
else if (a === '--root') opts.root = argv[++i];
|
||||
else if (a.startsWith('--root=')) opts.root = a.slice('--root='.length);
|
||||
else if (a === '--help' || a === '-h') opts.help = true;
|
||||
else {
|
||||
process.stderr.write(`db-call-graph: unknown argument ${a}\n`);
|
||||
@@ -61,8 +91,9 @@ function parseArgs(argv) {
|
||||
opts.bad = true;
|
||||
}
|
||||
}
|
||||
// No selector: report both, which is what a task's gate wants.
|
||||
if (!opts.sync && !opts.tx) {
|
||||
// No selector: report both --sync and --tx, which is what a task's gate wants.
|
||||
// --unawaited is never implied — it's opt-in only.
|
||||
if (!opts.sync && !opts.tx && !opts.unawaited) {
|
||||
opts.sync = true;
|
||||
opts.tx = true;
|
||||
}
|
||||
@@ -76,13 +107,14 @@ function splitDomains(value) {
|
||||
.filter(Boolean);
|
||||
return list.length ? list : null;
|
||||
}
|
||||
const USAGE = `Usage: node scripts/db-call-graph.mjs [--sync] [--tx] [--domains a,b,…] [--json]
|
||||
const USAGE = `Usage: node scripts/db-call-graph.mjs [--sync] [--tx] [--unawaited] [--domains a,b,…] [--json]
|
||||
|
||||
--sync list synchronous DB-touching methods (direct + transitive)
|
||||
--tx list real transaction call sites
|
||||
--unawaited list calls to async methods/functions whose result is used without await
|
||||
--domains a,b restrict to these inventory domain names (nest/days, systemNotices, …)
|
||||
--json machine-readable output
|
||||
(no --sync/--tx) both lists
|
||||
(no --sync/--tx/--unawaited) --sync and --tx together
|
||||
|
||||
Exits 1 when a requested list is non-empty. R0 exceptions (DatabaseService,
|
||||
src/db/**, src/demo/**, plugins/host/plugin-data.service.ts) are never listed.
|
||||
@@ -93,6 +125,9 @@ if (opts.help) {
|
||||
process.stdout.write(USAGE);
|
||||
process.exit(opts.bad ? 2 : 0);
|
||||
}
|
||||
if (opts.root) {
|
||||
SRC = path.resolve(process.cwd(), opts.root);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- file walk
|
||||
function walk(dir, acc = []) {
|
||||
@@ -270,6 +305,7 @@ for (const file of files) {
|
||||
kind: 'method',
|
||||
body: m.body,
|
||||
async: !!mods?.some((x) => x.kind === ts.SyntaxKind.AsyncKeyword),
|
||||
generator: !!m.asteriskToken, // async *foo() — consumed via `for await`/`yield*`, not `await`; see --unawaited
|
||||
line: lineOf(sf, m),
|
||||
});
|
||||
} else if (
|
||||
@@ -390,6 +426,7 @@ for (const file of files) {
|
||||
kind: m.kind,
|
||||
line: m.line,
|
||||
async: m.async,
|
||||
generator: !!m.generator,
|
||||
dbCalls,
|
||||
dbCallCount: dbCalls.length,
|
||||
calls,
|
||||
@@ -483,6 +520,386 @@ syncMethods.sort(byDomainClass);
|
||||
restructureSites.sort(byDomainClass);
|
||||
txSelected.sort(byDomainClass);
|
||||
|
||||
// ------------------------------------------------- --unawaited
|
||||
/**
|
||||
* Everything below is purely syntactic (same posture as the rest of the file):
|
||||
* it classifies a call expression's *immediate* AST context, and resolves its
|
||||
* target through the `classes`/`deps` maps the main pass already built (for
|
||||
* `this.<m>` / `this.<dep>.<m>`) or a fresh per-file import map (for a plain
|
||||
* `<importedFn>(…)` call). See the header comment for exactly what it does and
|
||||
* does not see.
|
||||
*/
|
||||
/** Walk up through no-op-at-runtime wrappers (parens, `as`/`satisfies`, postfix `!`) and through
|
||||
* a ternary branch (`cond ? call() : x` propagates `call()`'s result exactly like `call()` would
|
||||
* on its own) to the expression a caller actually treats as "the call's result". */
|
||||
function effectiveNode(node) {
|
||||
let n = node;
|
||||
for (;;) {
|
||||
const p = n.parent;
|
||||
if (!p) return n;
|
||||
if (ts.isParenthesizedExpression(p) || ts.isAsExpression(p) || ts.isNonNullExpression(p) || ts.isSatisfiesExpression?.(p)) {
|
||||
n = p;
|
||||
continue;
|
||||
}
|
||||
if (ts.isConditionalExpression(p) && (p.whenTrue === n || p.whenFalse === n)) {
|
||||
n = p;
|
||||
continue;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
const COMPARE_OPS = new Set([
|
||||
ts.SyntaxKind.EqualsEqualsToken,
|
||||
ts.SyntaxKind.EqualsEqualsEqualsToken,
|
||||
ts.SyntaxKind.ExclamationEqualsToken,
|
||||
ts.SyntaxKind.ExclamationEqualsEqualsToken,
|
||||
ts.SyntaxKind.LessThanToken,
|
||||
ts.SyntaxKind.GreaterThanToken,
|
||||
ts.SyntaxKind.LessThanEqualsToken,
|
||||
ts.SyntaxKind.GreaterThanEqualsToken,
|
||||
]);
|
||||
const LOGICAL_OPS = new Set([ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken]);
|
||||
const ARROW_ALWAYS_REPORT = new Set(['filter', 'find', 'some', 'every', 'sort', 'forEach']);
|
||||
|
||||
/** The property/method name of a call `X.<name>(arrow)` when `arrow` is one of its arguments, else null. */
|
||||
function arrowCallContext(arrow) {
|
||||
const call = arrow.parent;
|
||||
if (!call || !ts.isCallExpression(call) || !call.arguments.includes(arrow)) return null;
|
||||
const callee = call.expression;
|
||||
if (!ts.isPropertyAccessExpression(callee)) return null;
|
||||
return callee.name.text;
|
||||
}
|
||||
/** `eff` is (via an optional spread) a direct element of an array passed to Promise.all/allSettled/race/any. */
|
||||
function isPromiseCombinatorArrayElement(eff) {
|
||||
let n = eff;
|
||||
let p = n.parent;
|
||||
if (p && ts.isSpreadElement(p)) {
|
||||
n = p;
|
||||
p = n.parent;
|
||||
}
|
||||
if (!p || !ts.isArrayLiteralExpression(p)) return false;
|
||||
const call = p.parent;
|
||||
if (!call || !ts.isCallExpression(call) || !call.arguments.includes(p)) return false;
|
||||
const callee = call.expression;
|
||||
return (
|
||||
ts.isPropertyAccessExpression(callee) &&
|
||||
ts.isIdentifier(callee.expression) &&
|
||||
callee.expression.text === 'Promise' &&
|
||||
['all', 'allSettled', 'race', 'any'].includes(callee.name.text)
|
||||
);
|
||||
}
|
||||
/** True when `node`'s result is used in a way this recipe treats as already-safe. */
|
||||
function isUnawaitedSkip(node) {
|
||||
const eff = effectiveNode(node);
|
||||
const parent = eff.parent;
|
||||
if (!parent) return false;
|
||||
if (ts.isAwaitExpression(parent) && parent.expression === eff) return true;
|
||||
if (ts.isReturnStatement(parent) && parent.expression === eff) return true;
|
||||
if (ts.isVoidExpression(parent) && parent.expression === eff) return true;
|
||||
// A `.then(`/`.catch(`/`.finally(` chain — including the fire-and-forget-with-.catch( shape.
|
||||
if (
|
||||
ts.isPropertyAccessExpression(parent) &&
|
||||
parent.expression === eff &&
|
||||
['then', 'catch', 'finally'].includes(parent.name.text) &&
|
||||
parent.parent &&
|
||||
ts.isCallExpression(parent.parent) &&
|
||||
parent.parent.expression === parent
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (isPromiseCombinatorArrayElement(eff)) return true;
|
||||
if (ts.isArrowFunction(parent) && parent.body === eff) {
|
||||
const mc = arrowCallContext(parent);
|
||||
return !(mc && ARROW_ALWAYS_REPORT.has(mc)); // default: implicit-return-like (the `.map(` pattern) — skip
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** `async *foo()` returns an AsyncGenerator, not a Promise — `await` doesn't consume it (and isn't
|
||||
* expected to); only `for await (… of call())` or a delegating `yield* call()` does. */
|
||||
function isGeneratorConsumedSafely(node) {
|
||||
const eff = effectiveNode(node);
|
||||
const parent = eff.parent;
|
||||
if (!parent) return false;
|
||||
if (ts.isForOfStatement(parent) && parent.expression === eff && parent.awaitModifier) return true;
|
||||
if (ts.isYieldExpression(parent) && parent.expression === eff && parent.asteriskToken) return true;
|
||||
return false;
|
||||
}
|
||||
/** Reason tag for a call whose result is used without await (only called when NOT skipped). */
|
||||
function classifyUnawaitedShape(node) {
|
||||
const eff = effectiveNode(node);
|
||||
const parent = eff.parent;
|
||||
if (!parent) return 'other';
|
||||
if (ts.isVariableDeclaration(parent) && parent.initializer === eff) return 'stored-then-used';
|
||||
if (ts.isPropertyAssignment(parent) && parent.initializer === eff) return 'property';
|
||||
if (ts.isBinaryExpression(parent)) {
|
||||
const op = parent.operatorToken.kind;
|
||||
if (COMPARE_OPS.has(op) && (parent.left === eff || parent.right === eff)) return 'compared';
|
||||
if (LOGICAL_OPS.has(op) && (parent.left === eff || parent.right === eff)) return 'condition';
|
||||
}
|
||||
if (ts.isIfStatement(parent) && parent.expression === eff) return 'condition';
|
||||
if (ts.isConditionalExpression(parent) && parent.condition === eff) return 'condition';
|
||||
if (ts.isWhileStatement(parent) && parent.expression === eff) return 'condition';
|
||||
if (ts.isDoStatement(parent) && parent.expression === eff) return 'condition';
|
||||
if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === eff) {
|
||||
return 'member';
|
||||
}
|
||||
if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && parent.arguments?.includes(eff)) return 'argument';
|
||||
if (ts.isExpressionStatement(parent)) return 'statement';
|
||||
if (ts.isArrowFunction(parent) && parent.body === eff) {
|
||||
const mc = arrowCallContext(parent);
|
||||
if (mc && ['filter', 'find', 'some', 'every'].includes(mc)) return 'condition'; // predicate result discarded
|
||||
if (mc === 'forEach') return 'statement'; // return value discarded, same as an expression statement
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function collectExportedFnAsyncness(sf) {
|
||||
const out = new Map(); // name -> { async, generator }
|
||||
for (const st of sf.statements) {
|
||||
if (ts.isFunctionDeclaration(st) && st.name && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
||||
out.set(st.name.text, {
|
||||
async: !!st.modifiers.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword),
|
||||
generator: !!st.asteriskToken,
|
||||
});
|
||||
} else if (ts.isVariableStatement(st) && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
||||
for (const d of st.declarationList.declarations) {
|
||||
if (
|
||||
d.initializer &&
|
||||
(ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer)) &&
|
||||
ts.isIdentifier(d.name)
|
||||
) {
|
||||
out.set(d.name.text, {
|
||||
async: !!d.initializer.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword),
|
||||
// Arrow functions can't be generators; a function expression can (`async function* () {}`).
|
||||
generator: ts.isFunctionExpression(d.initializer) ? !!d.initializer.asteriskToken : false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/** Resolve a relative import specifier to a `.ts` file (or its `index.ts`) under the tree, else null. */
|
||||
function resolveModuleFile(fromFile, specifier) {
|
||||
if (!specifier.startsWith('.')) return null; // node_modules / path-mapped — not "a file under src/"
|
||||
const base = path.resolve(path.dirname(fromFile), specifier);
|
||||
for (const cand of [`${base}.ts`, path.join(base, 'index.ts')]) {
|
||||
if (fs.existsSync(cand) && fs.statSync(cand).isFile()) return cand;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Nearest enclosing function-like body of `node`, or null (e.g. a class-field initializer). */
|
||||
function findEnclosingFunctionBody(node) {
|
||||
let n = node.parent;
|
||||
while (n) {
|
||||
if (
|
||||
ts.isFunctionDeclaration(n) ||
|
||||
ts.isFunctionExpression(n) ||
|
||||
ts.isArrowFunction(n) ||
|
||||
ts.isMethodDeclaration(n) ||
|
||||
ts.isGetAccessorDeclaration(n) ||
|
||||
ts.isSetAccessorDeclaration(n) ||
|
||||
ts.isConstructorDeclaration(n)
|
||||
) {
|
||||
return n.body ?? null;
|
||||
}
|
||||
n = n.parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* `const x = this.asyncMethod()` is only safe when *every* later read of `x` in its
|
||||
* declaring function is itself one of the safe shapes `isUnawaitedSkip` recognizes
|
||||
* (`await x`, `return x`, `Promise.all([x, …])`, …) — the in-flight/memoized-promise
|
||||
* pattern (`this.inFlight.set(url, task); … return await task;`). Matches by name
|
||||
* within the enclosing function body only (no real scope/shadowing analysis — see
|
||||
* the header's limits); a variable this can't find a later read for is reported,
|
||||
* same as the declaration-only heuristic would.
|
||||
*/
|
||||
function isVariableUsedSafely(declNode, varName) {
|
||||
const scopeBody = findEnclosingFunctionBody(declNode);
|
||||
if (!scopeBody) return false;
|
||||
let sawReference = false;
|
||||
let allSafe = true;
|
||||
const visit = (node) => {
|
||||
if (ts.isIdentifier(node) && node.text === varName && node !== declNode.name) {
|
||||
const p = node.parent;
|
||||
const isBindingOrPropertyName =
|
||||
(ts.isVariableDeclaration(p) && p.name === node) ||
|
||||
(ts.isParameter(p) && p.name === node) ||
|
||||
(ts.isBindingElement(p) && p.name === node) ||
|
||||
(ts.isPropertyAccessExpression(p) && p.name === node);
|
||||
if (!isBindingOrPropertyName) {
|
||||
sawReference = true;
|
||||
if (!isUnawaitedSkip(node)) allSafe = false;
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(scopeBody);
|
||||
return sawReference && allSafe;
|
||||
}
|
||||
|
||||
function classMemberBodies(classNode, sf) {
|
||||
const out = [];
|
||||
for (const m of classNode.members) {
|
||||
if (ts.isMethodDeclaration(m) && m.name && m.body) {
|
||||
out.push({ name: m.name.getText(sf), body: m.body });
|
||||
} else if (
|
||||
ts.isPropertyDeclaration(m) &&
|
||||
m.initializer &&
|
||||
(ts.isArrowFunction(m.initializer) || ts.isFunctionExpression(m.initializer)) &&
|
||||
m.name
|
||||
) {
|
||||
out.push({ name: m.name.getText(sf), body: m.initializer.body });
|
||||
} else if (ts.isConstructorDeclaration(m) && m.body) {
|
||||
out.push({ name: 'constructor', body: m.body });
|
||||
} else if (ts.isGetAccessorDeclaration(m) && m.body && m.name) {
|
||||
out.push({ name: m.name.getText(sf), body: m.body });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let unawaitedFindings = [];
|
||||
if (opts.unawaited) {
|
||||
const exportedFnsByFile = new Map();
|
||||
const parsed = new Map(); // file -> {sf, text}
|
||||
for (const file of files) {
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ESNext, true, ts.ScriptKind.TS);
|
||||
parsed.set(file, sf);
|
||||
exportedFnsByFile.set(file, collectExportedFnAsyncness(sf));
|
||||
}
|
||||
|
||||
function resolveCallTarget(node, classRec, selfAsyncByName, importMap) {
|
||||
const callee = node.expression;
|
||||
if (ts.isPropertyAccessExpression(callee)) {
|
||||
const methodName = callee.name.text;
|
||||
const obj = callee.expression;
|
||||
if (obj.kind === ts.SyntaxKind.ThisKeyword) {
|
||||
const self = selfAsyncByName?.get(methodName);
|
||||
if (self) return { desc: `this.${methodName}`, async: self.async, generator: self.generator };
|
||||
return null;
|
||||
}
|
||||
if (ts.isPropertyAccessExpression(obj) && obj.expression.kind === ts.SyntaxKind.ThisKeyword) {
|
||||
const dep = obj.name.text;
|
||||
const depType = classRec?.deps?.[dep];
|
||||
const depClass = depType ? classes.get(depType) : null;
|
||||
const m = depClass?.methods.find((mm) => mm.name === methodName);
|
||||
if (m) return { desc: `this.${dep}.${methodName}`, async: m.async, generator: !!m.generator };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (ts.isIdentifier(callee)) {
|
||||
const imp = importMap.get(callee.text);
|
||||
if (!imp) return null;
|
||||
const asyncMap = exportedFnsByFile.get(imp.file);
|
||||
const entry = asyncMap?.get(imp.imported);
|
||||
if (!entry) return null;
|
||||
return { desc: `import:${callee.text}`, async: entry.async, generator: entry.generator };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const relFile = relServer(file);
|
||||
if (isR0File(relFile)) continue;
|
||||
const fileDomain = domainOf(file);
|
||||
if (domainFilter && !domainFilter.has(fileDomain)) continue;
|
||||
|
||||
const sf = parsed.get(file);
|
||||
const importMap = new Map();
|
||||
for (const st of sf.statements) {
|
||||
if (!ts.isImportDeclaration(st) || !st.importClause || !ts.isStringLiteral(st.moduleSpecifier)) continue;
|
||||
const targetFile = resolveModuleFile(file, st.moduleSpecifier.text);
|
||||
if (!targetFile) continue;
|
||||
const clause = st.importClause;
|
||||
const nb = clause.namedBindings;
|
||||
if (nb && ts.isNamedImports(nb)) {
|
||||
for (const el of nb.elements) {
|
||||
importMap.set(el.name.text, { file: targetFile, imported: el.propertyName ? el.propertyName.text : el.name.text });
|
||||
}
|
||||
}
|
||||
// A default import's local name can't be matched against a named-export map — not resolved (see header).
|
||||
}
|
||||
|
||||
const record = (node, className, methodName) => {
|
||||
const target = resolveCallTarget(node, className.classRec, className.selfAsyncByName, importMap);
|
||||
if (!target || !target.async) return;
|
||||
if (target.generator ? isGeneratorConsumedSafely(node) : isUnawaitedSkip(node)) return;
|
||||
const reason = classifyUnawaitedShape(node);
|
||||
if (reason === 'stored-then-used') {
|
||||
const declNode = effectiveNode(node).parent;
|
||||
if (
|
||||
ts.isVariableDeclaration(declNode) &&
|
||||
ts.isIdentifier(declNode.name) &&
|
||||
isVariableUsedSafely(declNode, declNode.name.text)
|
||||
) {
|
||||
return; // every later read is already await'd / returned / combined — the in-flight-promise pattern
|
||||
}
|
||||
}
|
||||
const text = node.getText(sf).replace(/\s+/g, ' ').trim();
|
||||
unawaitedFindings.push({
|
||||
domain: fileDomain,
|
||||
file: relFile,
|
||||
class: className.name,
|
||||
method: methodName,
|
||||
line: lineOf(sf, node),
|
||||
call: text.length > 100 ? `${text.slice(0, 97)}...` : text,
|
||||
target: target.desc,
|
||||
reason,
|
||||
});
|
||||
};
|
||||
|
||||
for (const st of sf.statements) {
|
||||
if (!ts.isClassDeclaration(st) || !st.name) continue;
|
||||
const className = st.name.text;
|
||||
const classRec = allClasses.find((c) => c.file === relFile && c.name === className);
|
||||
if (!classRec || R0_CLASSES.has(className)) continue;
|
||||
const selfAsyncByName = new Map();
|
||||
for (const m of classRec.methods) {
|
||||
if (!selfAsyncByName.has(m.name)) selfAsyncByName.set(m.name, { async: m.async, generator: !!m.generator });
|
||||
}
|
||||
const ctx = { name: className, classRec, selfAsyncByName };
|
||||
|
||||
for (const member of classMemberBodies(st, sf)) {
|
||||
const visit = (node) => {
|
||||
if (node !== member.body && (ts.isClassDeclaration(node) || ts.isClassExpression(node))) return;
|
||||
if (ts.isCallExpression(node)) record(node, ctx, member.name);
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(member.body);
|
||||
}
|
||||
}
|
||||
|
||||
// Module-level function bodies: only `<importedFn>(…)` calls apply (there is no `this`).
|
||||
const moduleCtx = { name: `${path.basename(file, '.ts')} (module)`, classRec: null, selfAsyncByName: null };
|
||||
const moduleFnBodies = [];
|
||||
for (const st of sf.statements) {
|
||||
if (ts.isFunctionDeclaration(st) && st.name && st.body) moduleFnBodies.push({ name: st.name.text, body: st.body });
|
||||
if (ts.isVariableStatement(st)) {
|
||||
for (const d of st.declarationList.declarations) {
|
||||
if (d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer)) && ts.isIdentifier(d.name)) {
|
||||
moduleFnBodies.push({ name: d.name.text, body: d.initializer.body });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const fn of moduleFnBodies) {
|
||||
const visit = (node) => {
|
||||
if (ts.isCallExpression(node)) record(node, moduleCtx, fn.name);
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(fn.body);
|
||||
}
|
||||
}
|
||||
|
||||
unawaitedFindings.sort(
|
||||
(a, b) => a.domain.localeCompare(b.domain) || a.file.localeCompare(b.file) || a.line - b.line,
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------- output
|
||||
const out = [];
|
||||
function group(entries, key) {
|
||||
@@ -508,6 +925,8 @@ if (opts.json) {
|
||||
cannotBeAsync: opts.sync ? restructureSites : undefined,
|
||||
transactionSites: opts.tx ? txSelected : undefined,
|
||||
transactionSiteCount: opts.tx ? txSelected.length : undefined,
|
||||
unawaitedCalls: opts.unawaited ? unawaitedFindings : undefined,
|
||||
unawaitedCallCount: opts.unawaited ? unawaitedFindings.length : undefined,
|
||||
unknownDomains,
|
||||
},
|
||||
null,
|
||||
@@ -558,9 +977,36 @@ if (opts.json) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opts.unawaited) {
|
||||
if (opts.sync || opts.tx) out.push('');
|
||||
const scope = opts.domains ? opts.domains.join(', ') : 'all domains';
|
||||
if (!unawaitedFindings.length) {
|
||||
out.push(`unawaited async call sites: none (${scope})`);
|
||||
} else {
|
||||
out.push(`unawaited async call sites: ${unawaitedFindings.length} in ${scope}`);
|
||||
const byReason = group(unawaitedFindings, (e) => e.reason);
|
||||
const reasonOrder = ['stored-then-used', 'argument', 'property', 'condition', 'compared', 'member', 'statement', 'other'];
|
||||
const reasonSummary = reasonOrder
|
||||
.filter((r) => byReason.has(r))
|
||||
.map((r) => `${r}=${byReason.get(r).length}`)
|
||||
.join(', ');
|
||||
out.push(` by reason: ${reasonSummary}`);
|
||||
for (const [k, entries] of group(unawaitedFindings, (e) => `${e.domain}\u0000${e.file}\u0000${e.class}`)) {
|
||||
const [domain, file, cls] = k.split('\u0000');
|
||||
out.push('');
|
||||
out.push(` ${domain} · ${cls} · ${file}`);
|
||||
for (const e of entries) {
|
||||
out.push(` ${String(e.line).padStart(5)} [${e.reason}] ${e.method} — ${e.call} (→ ${e.target})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.stdout.write(out.join('\n') + '\n');
|
||||
|
||||
const found = (opts.sync && syncMethods.length > 0) || (opts.tx && txSelected.length > 0);
|
||||
const found =
|
||||
(opts.sync && syncMethods.length > 0) ||
|
||||
(opts.tx && txSelected.length > 0) ||
|
||||
(opts.unawaited && unawaitedFindings.length > 0);
|
||||
process.exit(found ? 1 : 0);
|
||||
|
||||
Reference in New Issue
Block a user