@blundergoat/gruff-ts 0.4.0 → 0.5.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 +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/discovery.ts +39 -19
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +5 -3
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
// Shared syntax-only parse boundary (ADR-012): each analysed script is parsed exactly once per
|
|
2
|
+
// analysis run, and that one result feeds parse diagnostics, security-flow analysis, and AST
|
|
3
|
+
// function discovery. Separate parse paths would triple parser cost and drift apart; this module
|
|
4
|
+
// owns the parser, the script-kind mapping, and the AST callable enumeration consumed by the
|
|
5
|
+
// block rules (and, downstream, complexity metrics and naming ownership).
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
import type { RunDiagnostic } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
// Loaded via createRequire because typescript ships as CommonJS; usage stays bounded to syntax
|
|
10
|
+
// walking - no type checker, program, language service, or emit (ADR-012).
|
|
11
|
+
const require = createRequire(import.meta.url);
|
|
12
|
+
const typescriptSyntax = require("typescript") as typeof import("typescript");
|
|
13
|
+
|
|
14
|
+
type TsSourceFile = import("typescript").SourceFile;
|
|
15
|
+
type TsNode = import("typescript").Node;
|
|
16
|
+
type TsDiagnostic = import("typescript").DiagnosticWithLocation;
|
|
17
|
+
|
|
18
|
+
// Minimal file identity the parser needs: the display path picks the grammar and labels
|
|
19
|
+
// diagnostics; the script flag keeps config/text inputs from ever paying parser cost.
|
|
20
|
+
export interface ParsedScriptInput {
|
|
21
|
+
displayPath: string;
|
|
22
|
+
isScript: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// One parse result shared by every downstream consumer within a single analysis run.
|
|
26
|
+
export interface ParsedScript {
|
|
27
|
+
sourceFile: TsSourceFile;
|
|
28
|
+
diagnostics: RunDiagnostic[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/*
|
|
32
|
+
* Stable owner categories attached to naming inventory rows. CLI users see these categories only
|
|
33
|
+
* inside finding metadata, where they explain whether a casing comparison came from the module,
|
|
34
|
+
* one callable, one interface, or one type-literal contract.
|
|
35
|
+
*/
|
|
36
|
+
export type IdentifierOwnerKind = "module" | "function" | "interface" | "type-literal";
|
|
37
|
+
|
|
38
|
+
/*
|
|
39
|
+
* Deterministic syntax owner projected into naming diagnostics. The id contains source ranges or
|
|
40
|
+
* lexical names, never paths or TypeScript object identities; ownerName is absent when the module
|
|
41
|
+
* itself is the user-visible comparison boundary.
|
|
42
|
+
*/
|
|
43
|
+
export interface IdentifierOwner {
|
|
44
|
+
ownerId: string;
|
|
45
|
+
ownerKind: IdentifierOwnerKind;
|
|
46
|
+
ownerName?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/*
|
|
50
|
+
* One syntax-backed declaration row for the shared naming inventory. The row retains the existing
|
|
51
|
+
* name and line presented to users, while owner fields let a later rule compare only declarations
|
|
52
|
+
* that belong to the same reviewable surface.
|
|
53
|
+
*/
|
|
54
|
+
export interface OwnedDeclarationPoint extends IdentifierOwner {
|
|
55
|
+
name: string;
|
|
56
|
+
line: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/*
|
|
60
|
+
* The two non-parameter inventories collected during the shared callable walk. Keeping variable
|
|
61
|
+
* declarations and contract fields separate preserves the existing acronym input order when the
|
|
62
|
+
* analyser inserts callable parameters between them.
|
|
63
|
+
*/
|
|
64
|
+
export interface DeclarationOwnershipPoints {
|
|
65
|
+
variableDeclarations: OwnedDeclarationPoint[];
|
|
66
|
+
contractFields: OwnedDeclarationPoint[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/*
|
|
70
|
+
* One cached projection of the shared syntax tree. Function discovery and naming ownership read
|
|
71
|
+
* this same result, so enabling both rule families does not walk or parse the user's file twice.
|
|
72
|
+
*/
|
|
73
|
+
interface ParsedSyntaxIndex {
|
|
74
|
+
callablePoints: CallableMatchPoint[];
|
|
75
|
+
declarationOwnership: DeclarationOwnershipPoints;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const MODULE_IDENTIFIER_OWNER: IdentifierOwner = { ownerId: "module", ownerKind: "module" };
|
|
79
|
+
const parsedSyntaxIndexes = new WeakMap<ParsedScript, ParsedSyntaxIndex>();
|
|
80
|
+
|
|
81
|
+
// `createSourceFile` recovers from syntax errors and records them on an internal field; this
|
|
82
|
+
// narrow extension types that field without widening the public TypeScript surface.
|
|
83
|
+
interface ParsedSourceFileWithDiagnostics extends TsSourceFile {
|
|
84
|
+
parseDiagnostics: TsDiagnostic[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Test-visible parse counter backing the one-parse-per-script assertion; never drives behavior.
|
|
88
|
+
let parseCount = 0;
|
|
89
|
+
|
|
90
|
+
// Returns how many times the shared parser has run in this process; tests subtract before/after
|
|
91
|
+
// snapshots to assert one parse per analysed script.
|
|
92
|
+
export function parsedScriptParseCount(): number {
|
|
93
|
+
return parseCount;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Parses one script into the shared boundary result. Non-script inputs return undefined so a
|
|
98
|
+
* config or text file never parses; diagnostics always cover the whole file (never range-filtered).
|
|
99
|
+
*
|
|
100
|
+
* @param file - display path plus the script flag from discovery; a false script flag skips parsing
|
|
101
|
+
* @param source - decoded file text; empty script text produces a source file with no diagnostics
|
|
102
|
+
* @returns shared parse result; undefined means the input was a config or text file
|
|
103
|
+
*/
|
|
104
|
+
export function parseScript(file: ParsedScriptInput, source: string): ParsedScript | undefined {
|
|
105
|
+
// Config and text inputs do not enter the script parser, so callers receive no parse result.
|
|
106
|
+
if (!file.isScript) {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
parseCount += 1;
|
|
110
|
+
const parsedSourceFile = typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath)) as ParsedSourceFileWithDiagnostics;
|
|
111
|
+
const firstParseError = parsedSourceFile.parseDiagnostics[0];
|
|
112
|
+
return {
|
|
113
|
+
sourceFile: parsedSourceFile,
|
|
114
|
+
// One report entry per malformed file keeps diagnostics proportional to affected files.
|
|
115
|
+
diagnostics: firstParseError
|
|
116
|
+
? [summarizeParseErrors(file, parsedSourceFile, firstParseError, parsedSourceFile.parseDiagnostics.length)]
|
|
117
|
+
: [],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Maps extensions onto the matching TypeScript parser mode so TSX/JSX syntax parses as syntax.
|
|
122
|
+
// The single copy: source-text and security-flow used to carry one each.
|
|
123
|
+
export function scriptKindFor(path: string): import("typescript").ScriptKind {
|
|
124
|
+
if (path.endsWith(".tsx")) {
|
|
125
|
+
return typescriptSyntax.ScriptKind.TSX;
|
|
126
|
+
}
|
|
127
|
+
if (path.endsWith(".jsx")) {
|
|
128
|
+
return typescriptSyntax.ScriptKind.JSX;
|
|
129
|
+
}
|
|
130
|
+
if (path.endsWith(".js") || path.endsWith(".mjs") || path.endsWith(".cjs")) {
|
|
131
|
+
return typescriptSyntax.ScriptKind.JS;
|
|
132
|
+
}
|
|
133
|
+
return typescriptSyntax.ScriptKind.TS;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Builds the single parse-error entry reported for a source file.
|
|
138
|
+
* Multiple parser errors retain their count and first location so one malformed file cannot flood the report.
|
|
139
|
+
*
|
|
140
|
+
* @param file - discovered source metadata used for the reported path
|
|
141
|
+
* @param sourceFile - parser output used to translate the first error offset into a source line
|
|
142
|
+
* @param firstParseError - first parser error; a missing offset falls back to line 1
|
|
143
|
+
* @param parseErrorCount - total errors in this file; callers provide at least one
|
|
144
|
+
* @returns one diagnostic for the file; reports parser errors without throwing
|
|
145
|
+
*/
|
|
146
|
+
function summarizeParseErrors(file: ParsedScriptInput, sourceFile: TsSourceFile, firstParseError: TsDiagnostic, parseErrorCount: number): RunDiagnostic {
|
|
147
|
+
// TypeScript can omit an offset for malformed input; line 1 remains a usable report anchor.
|
|
148
|
+
const firstErrorLine = firstParseError.start === undefined
|
|
149
|
+
? 1
|
|
150
|
+
: sourceFile.getLineAndCharacterOfPosition(firstParseError.start).line + 1;
|
|
151
|
+
const firstErrorMessage = typescriptSyntax.flattenDiagnosticMessageText(firstParseError.messageText, " ");
|
|
152
|
+
// A single error keeps the established wording; larger sets expose their count without repeated entries.
|
|
153
|
+
const parseErrorMessage = parseErrorCount === 1
|
|
154
|
+
? `TypeScript syntax error: ${firstErrorMessage}`
|
|
155
|
+
: `TypeScript syntax errors: ${parseErrorCount} diagnostics in this file; first: ${firstErrorMessage}`;
|
|
156
|
+
return {
|
|
157
|
+
diagnosticType: "parse-error",
|
|
158
|
+
message: parseErrorMessage,
|
|
159
|
+
filePath: file.displayPath,
|
|
160
|
+
line: firstErrorLine,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/*
|
|
165
|
+
* One discovered callable declaration point: the zero-based line index where the legacy regex
|
|
166
|
+
* scanner would have matched, the reported block name, raw parameter text, actual AST parameter
|
|
167
|
+
* count, and the callable node used by later syntax metrics. The block parser turns points into
|
|
168
|
+
* FunctionBlocks with the exact same start/end/body slicing it always used, so the retained
|
|
169
|
+
* fingerprint invariant cannot move.
|
|
170
|
+
*/
|
|
171
|
+
export interface CallableMatchPoint extends IdentifierOwner {
|
|
172
|
+
lineIndex: number;
|
|
173
|
+
// Zero-based first line of the declaration itself, modifiers included but leading documentation
|
|
174
|
+
// excluded. Equals `lineIndex` for every single-line declaration; it moves earlier only when a
|
|
175
|
+
// declaration splits its modifiers onto their own line, where the line above the name is
|
|
176
|
+
// `export async function` rather than the docblock a reader can plainly see.
|
|
177
|
+
declarationLineIndex: number;
|
|
178
|
+
// Zero-based line of the callable's final token. The block parser prefers this over its legacy
|
|
179
|
+
// brace walk: a `{}` inside a multi-line parameter default would otherwise close the walk early
|
|
180
|
+
// and slice an empty body.
|
|
181
|
+
endLineIndex: number;
|
|
182
|
+
name: string;
|
|
183
|
+
params: string;
|
|
184
|
+
parameterCount: number;
|
|
185
|
+
isTestCallable: boolean;
|
|
186
|
+
// Syntax-backed visibility keeps split-line modifiers and file-level re-exports scoped to the
|
|
187
|
+
// declaration that owns them without moving the legacy name-line finding anchor.
|
|
188
|
+
isDirectlyExported: boolean;
|
|
189
|
+
isExplicitlyPublic: boolean;
|
|
190
|
+
isModuleScoped: boolean;
|
|
191
|
+
// False for signature-only declarations: interface and type-literal methods, overload
|
|
192
|
+
// signatures, and abstract or ambient members. The block rules use this instead of guessing
|
|
193
|
+
// from text, because a multi-line signature reads like an implementation on its first line.
|
|
194
|
+
hasBody: boolean;
|
|
195
|
+
// Shared-parse node whose parameters and body belong to this stable analysed block.
|
|
196
|
+
callableNode: TsNode;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Enumerates callable declarations from the shared syntax tree: function declarations (including
|
|
201
|
+
* generic and multi-line signatures the regex missed), class/object methods and constructors,
|
|
202
|
+
* interface/type-literal method signatures, const/let arrow and function initializers (including
|
|
203
|
+
* parenless single-argument arrows), and test/it callbacks. At most one point per source line is
|
|
204
|
+
* returned (source order wins) - the legacy scanner's one-block-per-line invariant.
|
|
205
|
+
*
|
|
206
|
+
* @param parsed Shared parse result for the script.
|
|
207
|
+
* @returns Match points sorted by line, ready for the block parser.
|
|
208
|
+
*/
|
|
209
|
+
export function callableMatchPoints(parsed: ParsedScript): CallableMatchPoint[] {
|
|
210
|
+
return parsedSyntaxIndex(parsed).callablePoints;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Returns variable and contract-field owners from the same syntax walk used for callable blocks.
|
|
215
|
+
* @param parsed Shared parse for the user's script; it is always present for a deep script scan.
|
|
216
|
+
* @returns Ordered rows; empty arrays mean the source declares no currently inventoried names.
|
|
217
|
+
*/
|
|
218
|
+
export function declarationOwnershipPoints(parsed: ParsedScript): DeclarationOwnershipPoints {
|
|
219
|
+
return parsedSyntaxIndex(parsed).declarationOwnership;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Builds one deterministic syntax index per parsed script so block and naming rules share a walk.
|
|
223
|
+
// Stable contract: repeated consumers receive the same ordered rows and owner ids.
|
|
224
|
+
function parsedSyntaxIndex(parsed: ParsedScript): ParsedSyntaxIndex {
|
|
225
|
+
const cachedIndex = parsedSyntaxIndexes.get(parsed);
|
|
226
|
+
// Multiple rule consumers reach the same file, so a completed projection is reused verbatim.
|
|
227
|
+
if (cachedIndex) {
|
|
228
|
+
return cachedIndex;
|
|
229
|
+
}
|
|
230
|
+
const callablePointsByLine = new Map<number, CallableMatchPoint>();
|
|
231
|
+
const variableDeclarations: OwnedDeclarationPoint[] = [];
|
|
232
|
+
const contractFields: OwnedDeclarationPoint[] = [];
|
|
233
|
+
const sourceLines = parsed.sourceFile.text.split(/\r?\n/);
|
|
234
|
+
// Carries the nearest callable owner for local declarations and the lexical type scope for
|
|
235
|
+
// declaration merging while one depth-first walk visits the user's syntax tree.
|
|
236
|
+
const visitSyntaxNode = (node: TsNode, declarationOwner: IdentifierOwner, contractScopeId: string): void => {
|
|
237
|
+
recordCallablePoint(callablePointsByLine, matchPointFor(parsed.sourceFile, node));
|
|
238
|
+
recordVariableDeclaration(parsed.sourceFile, node, declarationOwner, variableDeclarations);
|
|
239
|
+
recordContractFields(parsed.sourceFile, sourceLines, node, contractScopeId, contractFields);
|
|
240
|
+
const callableOwner = functionLikeOwner(parsed.sourceFile, node);
|
|
241
|
+
const childDeclarationOwner = callableOwner ?? declarationOwner;
|
|
242
|
+
const childContractScopeId = nestedContractScopeId(parsed.sourceFile, node, callableOwner, contractScopeId);
|
|
243
|
+
// Nested declarations inherit the nearest user-visible callable and lexical contract boundary.
|
|
244
|
+
node.forEachChild((child) => visitSyntaxNode(child, childDeclarationOwner, childContractScopeId));
|
|
245
|
+
};
|
|
246
|
+
// Top-level declarations begin in the module owner shown to CLI and report consumers.
|
|
247
|
+
parsed.sourceFile.forEachChild((node) => visitSyntaxNode(node, MODULE_IDENTIFIER_OWNER, MODULE_IDENTIFIER_OWNER.ownerId));
|
|
248
|
+
const syntaxIndex: ParsedSyntaxIndex = {
|
|
249
|
+
callablePoints: [...callablePointsByLine.values()].sort((left, right) => left.lineIndex - right.lineIndex),
|
|
250
|
+
declarationOwnership: { variableDeclarations, contractFields },
|
|
251
|
+
};
|
|
252
|
+
parsedSyntaxIndexes.set(parsed, syntaxIndex);
|
|
253
|
+
return syntaxIndex;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Applies the established one-block-per-line policy while the shared syntax index is built.
|
|
257
|
+
function recordCallablePoint(callablePointsByLine: Map<number, CallableMatchPoint>, callablePoint: CallableMatchPoint | undefined): void {
|
|
258
|
+
// Most syntax nodes are not callable declarations, so they add no report block.
|
|
259
|
+
if (!callablePoint) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const existingPoint = callablePointsByLine.get(callablePoint.lineIndex);
|
|
263
|
+
// Test callbacks outrank same-line declarations; otherwise the first source declaration wins.
|
|
264
|
+
if (!existingPoint || (callablePoint.isTestCallable && !existingPoint.isTestCallable)) {
|
|
265
|
+
callablePointsByLine.set(callablePoint.lineIndex, callablePoint);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const CONTRACT_FIELD_LINE = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
|
|
270
|
+
|
|
271
|
+
/*
|
|
272
|
+
* Inputs for projecting one named contract into naming inventory rows. Bundling the syntax owner,
|
|
273
|
+
* source view, and result sink keeps the traversal call readable when a CLI scan reaches an
|
|
274
|
+
* interface or type-literal declaration.
|
|
275
|
+
*/
|
|
276
|
+
interface ContractFieldCollection {
|
|
277
|
+
sourceFile: TsSourceFile;
|
|
278
|
+
sourceLines: string[];
|
|
279
|
+
members: import("typescript").NodeArray<import("typescript").TypeElement>;
|
|
280
|
+
ownerName: string;
|
|
281
|
+
ownerKind: "interface" | "type-literal";
|
|
282
|
+
contractScopeId: string;
|
|
283
|
+
declarationPosition: number;
|
|
284
|
+
contractFields: OwnedDeclarationPoint[];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Records the first simple binding from each declaration list, matching the inventory users saw
|
|
288
|
+
// before ownership was added. A comma-separated second binding remains outside this rule's scope.
|
|
289
|
+
function recordVariableDeclaration(sourceFile: TsSourceFile, node: TsNode, owner: IdentifierOwner, variableDeclarations: OwnedDeclarationPoint[]): void {
|
|
290
|
+
// Other syntax nodes cannot introduce the const/let/var rows this naming inventory covers.
|
|
291
|
+
if (!typescriptSyntax.isVariableDeclarationList(node)) {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const firstDeclaration = node.declarations[0];
|
|
295
|
+
// Destructuring or an empty recovered declaration stays outside the existing simple-name rule.
|
|
296
|
+
if (!firstDeclaration || !typescriptSyntax.isIdentifier(firstDeclaration.name)) {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
variableDeclarations.push({
|
|
300
|
+
name: firstDeclaration.name.text,
|
|
301
|
+
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
302
|
+
...owner,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Adds direct interface or named type-literal fields to the report inventory. Member methods,
|
|
307
|
+
// computed keys, mapped types, and same-line bodies remain outside the established rule surface.
|
|
308
|
+
function recordContractFields(sourceFile: TsSourceFile, sourceLines: string[], node: TsNode, contractScopeId: string, contractFields: OwnedDeclarationPoint[]): void {
|
|
309
|
+
// Interface declaration blocks with the same name and lexical scope intentionally share an owner.
|
|
310
|
+
if (typescriptSyntax.isInterfaceDeclaration(node)) {
|
|
311
|
+
recordNamedContractFields({ sourceFile, sourceLines, members: node.members, ownerName: node.name.text, ownerKind: "interface", contractScopeId, declarationPosition: node.name.getStart(sourceFile), contractFields });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
// Only a named alias whose direct value is an object type matches the existing type-literal scan.
|
|
315
|
+
if (typescriptSyntax.isTypeAliasDeclaration(node) && typescriptSyntax.isTypeLiteralNode(node.type)) {
|
|
316
|
+
recordNamedContractFields({ sourceFile, sourceLines, members: node.type.members, ownerName: node.name.text, ownerKind: "type-literal", contractScopeId, declarationPosition: node.name.getStart(sourceFile), contractFields });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Projects direct property signatures for one contract owner while retaining the old line filter.
|
|
321
|
+
function recordNamedContractFields(args: ContractFieldCollection): void {
|
|
322
|
+
const declarationLineIndex = args.sourceFile.getLineAndCharacterOfPosition(args.declarationPosition).line;
|
|
323
|
+
const owner = contractIdentifierOwner(args.ownerKind, args.contractScopeId, args.ownerName);
|
|
324
|
+
// Each direct member is evaluated once in source order, which keeps report ordering stable.
|
|
325
|
+
for (const member of args.members) {
|
|
326
|
+
// Methods, indexes, and computed property names are not simple field declarations for users.
|
|
327
|
+
if (!typescriptSyntax.isPropertySignature(member) || !typescriptSyntax.isIdentifier(member.name)) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const lineIndex = args.sourceFile.getLineAndCharacterOfPosition(member.name.getStart(args.sourceFile)).line;
|
|
331
|
+
// The legacy line walker begins after the header, so a one-line contract remains un-inventoried.
|
|
332
|
+
if (lineIndex <= declarationLineIndex) {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const sourceName = args.sourceLines[lineIndex]?.match(CONTRACT_FIELD_LINE)?.[1];
|
|
336
|
+
// Multi-line or non-leading property syntax stays outside the current user-visible coverage.
|
|
337
|
+
if (sourceName !== member.name.text) {
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
args.contractFields.push({ name: member.name.text, line: lineIndex + 1, ...owner });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Builds the merged contract identity shown in finding metadata. Names are syntactic identifiers,
|
|
345
|
+
// while the lexical prefix separates equally named contracts in unrelated user scopes.
|
|
346
|
+
function contractIdentifierOwner(ownerKind: "interface" | "type-literal", contractScopeId: string, ownerName: string): IdentifierOwner {
|
|
347
|
+
return {
|
|
348
|
+
ownerId: `${ownerKind}:${contractScopeId}:${ownerName}`,
|
|
349
|
+
ownerKind,
|
|
350
|
+
ownerName,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Returns a stable callable owner for descendants, or no replacement when this node is ordinary
|
|
355
|
+
// syntax. An absent owner means local declarations keep the nearest callable or module boundary.
|
|
356
|
+
function functionLikeOwner(sourceFile: TsSourceFile, node: TsNode): IdentifierOwner | undefined {
|
|
357
|
+
// Only function-like syntax starts a new local naming boundary for the user's declarations.
|
|
358
|
+
if (!typescriptSyntax.isFunctionLike(node)) {
|
|
359
|
+
return undefined;
|
|
360
|
+
}
|
|
361
|
+
return callableIdentifierOwner(sourceFile, node);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Creates a range-derived callable identity without exposing TypeScript node objects or file paths.
|
|
365
|
+
function callableIdentifierOwner(sourceFile: TsSourceFile, callableNode: TsNode): IdentifierOwner {
|
|
366
|
+
const ownerName = functionLikeOwnerName(callableNode);
|
|
367
|
+
// Anonymous callbacks retain their range identity while omitting a misleading display name.
|
|
368
|
+
return {
|
|
369
|
+
ownerId: `function:${callableNode.getStart(sourceFile)}:${callableNode.getEnd()}`,
|
|
370
|
+
ownerKind: "function",
|
|
371
|
+
...(ownerName === undefined ? {} : { ownerName }),
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Chooses the first human label a CLI user recognizes across declaration, binding, and test shapes.
|
|
376
|
+
function functionLikeOwnerName(node: TsNode): string | undefined {
|
|
377
|
+
// The precedence matches existing block labels; no recognized shape means an anonymous owner.
|
|
378
|
+
return declaredFunctionLikeOwnerName(node) ?? boundFunctionLikeOwnerName(node) ?? testFunctionLikeOwnerName(node);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Reads names written directly on functions and methods, including the constructor label.
|
|
382
|
+
function declaredFunctionLikeOwnerName(node: TsNode): string | undefined {
|
|
383
|
+
const namedNode = node as TsNode & { name?: TsNode };
|
|
384
|
+
// Named functions, methods, accessors, and signatures already carry their user-facing label.
|
|
385
|
+
if (namedNode.name && typescriptSyntax.isIdentifier(namedNode.name)) {
|
|
386
|
+
return namedNode.name.text;
|
|
387
|
+
}
|
|
388
|
+
// Constructors have no name node but are recognizable as one callable in class diagnostics.
|
|
389
|
+
if (typescriptSyntax.isConstructorDeclaration(node)) {
|
|
390
|
+
return "constructor";
|
|
391
|
+
}
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// Reads the variable or property label that presents an otherwise anonymous callable to users.
|
|
396
|
+
function boundFunctionLikeOwnerName(node: TsNode): string | undefined {
|
|
397
|
+
const parent = node.parent;
|
|
398
|
+
// Variable-bound arrows and function expressions are presented under their declared variable.
|
|
399
|
+
if (typescriptSyntax.isVariableDeclaration(parent) && typescriptSyntax.isIdentifier(parent.name)) {
|
|
400
|
+
return parent.name.text;
|
|
401
|
+
}
|
|
402
|
+
// Object and class property callbacks can use the property label without a discovered block row.
|
|
403
|
+
if ((typescriptSyntax.isPropertyAssignment(parent) || typescriptSyntax.isPropertyDeclaration(parent)) && typescriptSyntax.isIdentifier(parent.name)) {
|
|
404
|
+
return parent.name.text;
|
|
405
|
+
}
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Reads a literal test title, matching the test block symbol a CLI user already sees.
|
|
410
|
+
function testFunctionLikeOwnerName(node: TsNode): string | undefined {
|
|
411
|
+
const parent = node.parent;
|
|
412
|
+
// Ordinary callback arguments have no stable test label and remain anonymous owner metadata.
|
|
413
|
+
if (!typescriptSyntax.isCallExpression(parent) || parent.arguments[1] !== node || !typescriptSyntax.isIdentifier(parent.expression) || (parent.expression.text !== "test" && parent.expression.text !== "it")) {
|
|
414
|
+
return undefined;
|
|
415
|
+
}
|
|
416
|
+
const title = parent.arguments[0];
|
|
417
|
+
// Dynamic test titles have no stable human label, so only literal titles are included.
|
|
418
|
+
if (!title || !typescriptSyntax.isStringLiteralLike(title)) {
|
|
419
|
+
return undefined;
|
|
420
|
+
}
|
|
421
|
+
return title.text;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Advances the lexical scope used only for merging named contracts. Ordinary function body blocks
|
|
425
|
+
// stay under their callable, while nested blocks and namespaces separate same-name declarations.
|
|
426
|
+
function nestedContractScopeId(sourceFile: TsSourceFile, node: TsNode, callableOwner: IdentifierOwner | undefined, currentScopeId: string): string {
|
|
427
|
+
// A function-like boundary is the lexical contract scope users see around local type declarations.
|
|
428
|
+
if (callableOwner) {
|
|
429
|
+
return callableOwner.ownerId;
|
|
430
|
+
}
|
|
431
|
+
// Namespace bodies can contain same-name interfaces that must not merge with module contracts.
|
|
432
|
+
// TypeScript merges every block of one namespace into a single declaration space, so the scope
|
|
433
|
+
// is keyed on the namespace path - byte offsets would split a re-opened namespace in two.
|
|
434
|
+
if (typescriptSyntax.isModuleBlock(node)) {
|
|
435
|
+
return `module-block:${namespaceDeclarationPath(node)}`;
|
|
436
|
+
}
|
|
437
|
+
// A nested statement block is a distinct type-declaration scope; the function body itself is not.
|
|
438
|
+
if (typescriptSyntax.isBlock(node) && !typescriptSyntax.isFunctionLike(node.parent)) {
|
|
439
|
+
return `block:${node.getStart(sourceFile)}:${node.getEnd()}`;
|
|
440
|
+
}
|
|
441
|
+
return currentScopeId;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Joins every enclosing namespace name so the two spellings a user can write for one declaration
|
|
445
|
+
// space - `namespace A.B` and `namespace A { namespace B }` - land on the same contract scope.
|
|
446
|
+
function namespaceDeclarationPath(moduleBlock: TsNode): string {
|
|
447
|
+
const names: string[] = [];
|
|
448
|
+
for (let ancestor = moduleBlock.parent; ancestor && !typescriptSyntax.isSourceFile(ancestor); ancestor = ancestor.parent) {
|
|
449
|
+
// Only the namespace headers carry a name; intervening blocks are walked through, not recorded.
|
|
450
|
+
if (typescriptSyntax.isModuleDeclaration(ancestor)) {
|
|
451
|
+
names.push(ancestor.name.text);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return names.reverse().join(".");
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// Classifies one AST node into a callable match point, or undefined for non-callable nodes.
|
|
458
|
+
// Accessors and anonymous/default-export-anonymous functions stay excluded: the legacy scanner
|
|
459
|
+
// never discovered them, and naming policy for those shapes is deferred to a separate decision.
|
|
460
|
+
function matchPointFor(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
|
|
461
|
+
if (typescriptSyntax.isFunctionDeclaration(node) && node.name) {
|
|
462
|
+
return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
|
|
463
|
+
}
|
|
464
|
+
if ((typescriptSyntax.isMethodDeclaration(node) || typescriptSyntax.isMethodSignature(node)) && typescriptSyntax.isIdentifier(node.name)) {
|
|
465
|
+
return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
|
|
466
|
+
}
|
|
467
|
+
if (typescriptSyntax.isConstructorDeclaration(node)) {
|
|
468
|
+
// Constructors carry no name node; the parameter-list position sits on the declaration line.
|
|
469
|
+
return declarationPoint(sourceFile, node.parameters.pos, node, "constructor", node.parameters);
|
|
470
|
+
}
|
|
471
|
+
if (typescriptSyntax.isVariableDeclaration(node)) {
|
|
472
|
+
return variableInitializerPoint(sourceFile, node);
|
|
473
|
+
}
|
|
474
|
+
if (typescriptSyntax.isCallExpression(node)) {
|
|
475
|
+
return testCallbackPoint(sourceFile, node);
|
|
476
|
+
}
|
|
477
|
+
return undefined;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Builds the point for a named declaration: the anchor line is the name's line, matching where
|
|
481
|
+
// the legacy line-oriented patterns fired; the end line is the declaration's final token.
|
|
482
|
+
function declarationPoint(sourceFile: TsSourceFile, position: number, callableNode: TsNode, name: string, parameters: readonly TsNode[]): CallableMatchPoint {
|
|
483
|
+
const visibilityNode = callableVisibilityNode(callableNode);
|
|
484
|
+
const isDirectlyExported = hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.ExportKeyword);
|
|
485
|
+
const lineIndex = sourceFile.getLineAndCharacterOfPosition(position).line;
|
|
486
|
+
// `getStart` skips leading documentation, so this lands on the first modifier or keyword. Clamped
|
|
487
|
+
// to `lineIndex` so the declaration anchor can only ever move earlier than the reported name line.
|
|
488
|
+
const declarationStartLine = sourceFile.getLineAndCharacterOfPosition(visibilityNode.getStart(sourceFile)).line;
|
|
489
|
+
return {
|
|
490
|
+
...callableIdentifierOwner(sourceFile, callableNode),
|
|
491
|
+
lineIndex,
|
|
492
|
+
declarationLineIndex: Math.min(declarationStartLine, lineIndex),
|
|
493
|
+
endLineIndex: sourceFile.getLineAndCharacterOfPosition(callableNode.getEnd()).line,
|
|
494
|
+
name,
|
|
495
|
+
params: parametersText(sourceFile, parameters),
|
|
496
|
+
parameterCount: parameters.length,
|
|
497
|
+
isTestCallable: false,
|
|
498
|
+
isDirectlyExported,
|
|
499
|
+
isExplicitlyPublic: isDirectlyExported || hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.PublicKeyword),
|
|
500
|
+
isModuleScoped: visibilityNode.parent === sourceFile,
|
|
501
|
+
hasBody: callableNodeHasBody(callableNode),
|
|
502
|
+
callableNode,
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Variable-backed callables inherit export modifiers and module scope from their statement;
|
|
507
|
+
// declaration-shaped callables already carry both facts on their own node.
|
|
508
|
+
function callableVisibilityNode(callableNode: TsNode): TsNode {
|
|
509
|
+
const declaration = callableNode.parent;
|
|
510
|
+
if (!typescriptSyntax.isVariableDeclaration(declaration)) {
|
|
511
|
+
return callableNode;
|
|
512
|
+
}
|
|
513
|
+
const declarationList = declaration.parent;
|
|
514
|
+
if (!typescriptSyntax.isVariableDeclarationList(declarationList)) {
|
|
515
|
+
return callableNode;
|
|
516
|
+
}
|
|
517
|
+
const statement = declarationList.parent;
|
|
518
|
+
return typescriptSyntax.isVariableStatement(statement) ? statement : callableNode;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Reads a modifier only when the syntax node can own modifiers.
|
|
522
|
+
function hasNodeModifier(node: TsNode, modifierKind: import("typescript").SyntaxKind): boolean {
|
|
523
|
+
const modifiers = typescriptSyntax.canHaveModifiers(node) ? typescriptSyntax.getModifiers(node) : undefined;
|
|
524
|
+
return modifiers?.some((modifier) => modifier.kind === modifierKind) === true;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Arrow functions and function expressions always carry a body, so only declaration-shaped nodes
|
|
528
|
+
// can answer false here: a method signature has no `body` property at all, and an overload or
|
|
529
|
+
// abstract member leaves it undefined.
|
|
530
|
+
function callableNodeHasBody(callableNode: TsNode): boolean {
|
|
531
|
+
return (callableNode as { body?: unknown }).body !== undefined;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// const/let initializer arrows and function expressions become blocks named after the variable;
|
|
535
|
+
// `var` stays excluded because the legacy pattern never matched it.
|
|
536
|
+
function variableInitializerPoint(sourceFile: TsSourceFile, node: import("typescript").VariableDeclaration): CallableMatchPoint | undefined {
|
|
537
|
+
if (!typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
if (!typescriptSyntax.isArrowFunction(node.initializer) && !typescriptSyntax.isFunctionExpression(node.initializer)) {
|
|
541
|
+
return undefined;
|
|
542
|
+
}
|
|
543
|
+
const declarationList = node.parent;
|
|
544
|
+
if (!typescriptSyntax.isVariableDeclarationList(declarationList) || (declarationList.flags & typescriptSyntax.NodeFlags.Const) === 0 && (declarationList.flags & typescriptSyntax.NodeFlags.Let) === 0) {
|
|
545
|
+
return undefined;
|
|
546
|
+
}
|
|
547
|
+
return declarationPoint(sourceFile, node.name.getStart(sourceFile), node.initializer, node.name.text, node.initializer.parameters);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// `test("name", () => …)` / `it("name", …)` callbacks become blocks named by the test title,
|
|
551
|
+
// anchored at the call line - the legacy scanner's highest-priority pattern.
|
|
552
|
+
function testCallbackPoint(sourceFile: TsSourceFile, node: import("typescript").CallExpression): CallableMatchPoint | undefined {
|
|
553
|
+
if (!typescriptSyntax.isIdentifier(node.expression) || (node.expression.text !== "test" && node.expression.text !== "it")) {
|
|
554
|
+
return undefined;
|
|
555
|
+
}
|
|
556
|
+
const [title, callback] = node.arguments;
|
|
557
|
+
if (!title || !typescriptSyntax.isStringLiteralLike(title) || !callback) {
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
if (!typescriptSyntax.isArrowFunction(callback) && !typescriptSyntax.isFunctionExpression(callback)) {
|
|
561
|
+
return undefined;
|
|
562
|
+
}
|
|
563
|
+
const lineIndex = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line;
|
|
564
|
+
return {
|
|
565
|
+
...callableIdentifierOwner(sourceFile, callback),
|
|
566
|
+
lineIndex,
|
|
567
|
+
// A test callback is anchored at its call expression, which is already the declaration line.
|
|
568
|
+
declarationLineIndex: lineIndex,
|
|
569
|
+
endLineIndex: sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line,
|
|
570
|
+
name: title.text,
|
|
571
|
+
params: parametersText(sourceFile, callback.parameters),
|
|
572
|
+
parameterCount: callback.parameters.length,
|
|
573
|
+
isTestCallable: true,
|
|
574
|
+
isDirectlyExported: false,
|
|
575
|
+
isExplicitlyPublic: false,
|
|
576
|
+
isModuleScoped: false,
|
|
577
|
+
hasBody: true,
|
|
578
|
+
callableNode: callback,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Joins each AST parameter span without the inter-parameter trivia where an end-of-line comment
|
|
583
|
+
// could otherwise swallow the following name after newlines are flattened.
|
|
584
|
+
function parametersText(sourceFile: TsSourceFile, parameters: readonly TsNode[]): string {
|
|
585
|
+
return parameters
|
|
586
|
+
.map((parameter) => sourceFile.text.slice(parameter.getStart(sourceFile), parameter.getEnd()))
|
|
587
|
+
.join(", ")
|
|
588
|
+
.replace(/\r?\n/g, " ");
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/*
|
|
592
|
+
* One exported, documented function declaration as the docblock rules consume it: the JSDoc text
|
|
593
|
+
* between its markers, the declared name, identifier parameter names (destructured parameters stay
|
|
594
|
+
* intentionally invisible, matching the legacy text splitter), the docblock's one-based start line
|
|
595
|
+
* (the docblock rules' stable finding anchor), and the declared return type text ("" when absent).
|
|
596
|
+
*/
|
|
597
|
+
export interface DocumentedExportFunction {
|
|
598
|
+
docText: string;
|
|
599
|
+
name: string;
|
|
600
|
+
parameterNames: string[];
|
|
601
|
+
line: number;
|
|
602
|
+
returnTypeText: string;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Enumerates every exported function declaration that carries a leading JSDoc block. Anchoring to
|
|
607
|
+
* the syntax tree means prose containing the word `export` inside a comment can no longer suppress
|
|
608
|
+
* detection, and `export async function` plus generic and multi-line signatures are covered.
|
|
609
|
+
*
|
|
610
|
+
* @param parsed Shared parse result for the script.
|
|
611
|
+
* @returns Documented exported functions in source order; empty when the file has none.
|
|
612
|
+
*/
|
|
613
|
+
export function documentedExportFunctions(parsed: ParsedScript): DocumentedExportFunction[] {
|
|
614
|
+
const results: DocumentedExportFunction[] = [];
|
|
615
|
+
// Full-depth walk so namespaced exported functions keep their docblock coverage too.
|
|
616
|
+
const visit = (node: TsNode): void => {
|
|
617
|
+
const documented = documentedExportFunction(parsed.sourceFile, node);
|
|
618
|
+
if (documented) {
|
|
619
|
+
results.push(documented);
|
|
620
|
+
}
|
|
621
|
+
node.forEachChild(visit);
|
|
622
|
+
};
|
|
623
|
+
parsed.sourceFile.forEachChild(visit);
|
|
624
|
+
return results;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// Projects one function declaration into the documented-export shape, or undefined when it is not
|
|
628
|
+
// an exported named function with a JSDoc block. `export default function` never matched the
|
|
629
|
+
// legacy pattern, so it stays excluded until a deliberate policy change covers it.
|
|
630
|
+
function documentedExportFunction(sourceFile: TsSourceFile, node: TsNode): DocumentedExportFunction | undefined {
|
|
631
|
+
if (!typescriptSyntax.isFunctionDeclaration(node) || !node.name) {
|
|
632
|
+
return undefined;
|
|
633
|
+
}
|
|
634
|
+
const flags = typescriptSyntax.getCombinedModifierFlags(node);
|
|
635
|
+
if ((flags & typescriptSyntax.ModifierFlags.Export) === 0 || (flags & typescriptSyntax.ModifierFlags.Default) !== 0) {
|
|
636
|
+
return undefined;
|
|
637
|
+
}
|
|
638
|
+
const jsDocs = (node as { jsDoc?: readonly import("typescript").JSDoc[] }).jsDoc;
|
|
639
|
+
const jsDoc = jsDocs?.[jsDocs.length - 1];
|
|
640
|
+
if (!jsDoc) {
|
|
641
|
+
return undefined;
|
|
642
|
+
}
|
|
643
|
+
return {
|
|
644
|
+
docText: sourceFile.text.slice(jsDoc.getStart(sourceFile) + 3, jsDoc.getEnd() - 2),
|
|
645
|
+
name: node.name.text,
|
|
646
|
+
parameterNames: node.parameters
|
|
647
|
+
.map((parameter) => (typescriptSyntax.isIdentifier(parameter.name) ? parameter.name.text : undefined))
|
|
648
|
+
.filter((name): name is string => name !== undefined),
|
|
649
|
+
line: sourceFile.getLineAndCharacterOfPosition(jsDoc.getStart(sourceFile)).line + 1,
|
|
650
|
+
returnTypeText: node.type ? node.type.getText(sourceFile).replace(/\s+/g, " ").trim() : "",
|
|
651
|
+
};
|
|
652
|
+
}
|