crap-ts 0.1.1 → 1.0.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.
@@ -4,81 +4,178 @@ import { basename, join } from "node:path";
4
4
 
5
5
  import ts from "typescript";
6
6
 
7
- import { calculateCrapScoreFromPercent } from "./crap-score.js";
8
-
9
- export function extractCoverageFunctions(coverageJson) {
10
- const coverageByFile = new Map();
11
-
12
- for (const [filePath, coverage] of Object.entries(coverageJson)) {
13
- const functions = Object.entries(coverage.fnMap ?? {}).flatMap(
14
- ([id, metadata]) => {
15
- const startLine = metadata.loc?.start?.line;
16
- const endLine = metadata.loc?.end?.line;
17
-
18
- if (!startLine || !endLine) {
19
- return [];
20
- }
21
-
22
- return [
23
- {
24
- coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
25
- declarationLine: metadata.line ?? startLine,
26
- endLine,
27
- startLine,
28
- },
29
- ];
30
- },
31
- );
7
+ import { calculateCrapScore } from "./crap-score.js";
32
8
 
33
- coverageByFile.set(filePath, functions);
34
- }
9
+ // TypeScript 7 has no `createSourceFile`; its AST lives behind the unstable API.
10
+ const ts7Ast = ts.createSourceFile
11
+ ? null
12
+ : await import("typescript/unstable/ast");
13
+ const defaultAdapter = ts7Ast
14
+ ? { SyntaxKind: ts7Ast.SyntaxKind, forEachChild: forEachTs7Child }
15
+ : { SyntaxKind: ts.SyntaxKind, forEachChild: ts.forEachChild };
16
+
17
+ export async function analyzeFileRisk({
18
+ coverage,
19
+ filePath,
20
+ minLines = 1,
21
+ sourceFilePath,
22
+ sourceText,
23
+ }) {
24
+ const { functions } = await analyzeSource({
25
+ coverage,
26
+ filePath,
27
+ sourceFilePath,
28
+ sourceText,
29
+ });
35
30
 
36
- return coverageByFile;
31
+ return functions.filter((risk) => risk.lineCount >= minLines);
37
32
  }
38
33
 
39
- export async function analyzeFileRisk({
40
- coverageFunctions,
34
+ export async function analyzeSource({
35
+ coverage,
41
36
  filePath,
42
- minLines,
43
37
  sourceFilePath,
44
38
  sourceText,
45
39
  }) {
46
- const adapter = await getTypescriptAdapter({
40
+ const sourceFile = await parseSourceFile({
47
41
  filePath,
48
42
  sourceFilePath,
49
43
  sourceText,
50
44
  });
51
- const { sourceFile } = adapter;
52
- const risks = [];
45
+ const adapter = { ...defaultAdapter, sourceFile };
46
+ const ignore = findIgnoreComments(sourceText, collectLiteralRanges(adapter));
47
+ const functions = collectFunctions(adapter, filePath, ignore);
48
+
49
+ if (coverage) {
50
+ assertStatementsInSource(coverage, sourceText, filePath);
51
+ assignStatementCoverage(functions, coverage);
52
+ }
53
+
54
+ return {
55
+ executable:
56
+ !ignore.file &&
57
+ (functions.length > 0 || hasExecutableModuleStatements(adapter)),
58
+ functions: functions.map(({ ignored, risk }) => {
59
+ // No counters is only acceptable where an ignore comment removed them.
60
+ if (ignored && risk.evidence === "missing") {
61
+ risk.evidence = "ignored";
62
+ }
63
+
64
+ risk.crapScore = calculateCrapScore({
65
+ complexity: risk.complexity,
66
+ coverage: risk.coveragePercent,
67
+ });
68
+ return risk;
69
+ }),
70
+ };
71
+ }
72
+
73
+ export function calculateCyclomaticComplexity(node, adapter = defaultAdapter) {
74
+ let complexity = 1;
75
+
76
+ function visit(child) {
77
+ // Nested functions get their own rows; never charge their decisions here.
78
+ if (isFunctionLikeNode(adapter, child)) {
79
+ return;
80
+ }
81
+
82
+ if (addsDecisionPath(adapter, child)) {
83
+ complexity += 1;
84
+ }
85
+
86
+ adapter.forEachChild(child, visit);
87
+ }
88
+
89
+ if (isFunctionLikeNode(adapter, node)) {
90
+ adapter.forEachChild(node, visit);
91
+ } else {
92
+ visit(node);
93
+ }
94
+
95
+ return complexity;
96
+ }
97
+
98
+ function addsDecisionPath({ SyntaxKind }, node) {
99
+ switch (node.kind) {
100
+ case SyntaxKind.IfStatement:
101
+ case SyntaxKind.ConditionalExpression:
102
+ case SyntaxKind.ForStatement:
103
+ case SyntaxKind.ForInStatement:
104
+ case SyntaxKind.ForOfStatement:
105
+ case SyntaxKind.WhileStatement:
106
+ case SyntaxKind.DoStatement:
107
+ case SyntaxKind.CaseClause:
108
+ case SyntaxKind.CatchClause:
109
+ return true;
110
+ case SyntaxKind.BinaryExpression:
111
+ return [
112
+ SyntaxKind.AmpersandAmpersandToken,
113
+ SyntaxKind.BarBarToken,
114
+ SyntaxKind.QuestionQuestionToken,
115
+ SyntaxKind.AmpersandAmpersandEqualsToken,
116
+ SyntaxKind.BarBarEqualsToken,
117
+ SyntaxKind.QuestionQuestionEqualsToken,
118
+ ].includes(node.operatorToken.kind);
119
+ case SyntaxKind.Parameter:
120
+ case SyntaxKind.BindingElement:
121
+ return Boolean(node.initializer);
122
+ case SyntaxKind.ShorthandPropertyAssignment:
123
+ return Boolean(node.objectAssignmentInitializer);
124
+ default:
125
+ return false;
126
+ }
127
+ }
128
+
129
+ function collectFunctions(adapter, filePath, ignore) {
130
+ const { SyntaxKind, sourceFile } = adapter;
131
+ const functions = [];
53
132
 
54
133
  function visit(node) {
55
- if (isFunctionLikeNode(adapter, node) && node.body) {
56
- const startLine =
57
- sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
58
- .line + 1;
59
- const endLine =
60
- sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
61
- const lineCount = endLine - startLine + 1;
62
-
63
- if (lineCount >= minLines) {
64
- const complexity = calculateCyclomaticComplexity(node.body, adapter);
65
- const coveragePercent = getFunctionCoveragePercent({
66
- coverageFunctions,
67
- endLine,
68
- startLine,
134
+ const start = toPosition(sourceFile, node.getStart(sourceFile));
135
+
136
+ const targetKey = positionKey(start);
137
+ const directive = ignore.nextTargets.get(targetKey);
138
+
139
+ // An `ignore next|if|else` comment applies to the outermost node after it.
140
+ if (directive && node.kind !== SyntaxKind.SourceFile) {
141
+ ignore.nextTargets.delete(targetKey);
142
+ const target =
143
+ directive === "next"
144
+ ? node
145
+ : node.kind === SyntaxKind.IfStatement
146
+ ? node[directive === "if" ? "thenStatement" : "elseStatement"]
147
+ : undefined;
148
+
149
+ if (target) {
150
+ ignore.ranges.push({
151
+ end: toPosition(sourceFile, target.getEnd()),
152
+ start: toPosition(sourceFile, target.getStart(sourceFile)),
69
153
  });
154
+ }
155
+ }
70
156
 
71
- risks.push({
72
- complexity,
73
- coveragePercent,
74
- crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
75
- endLine,
157
+ if (isFunctionLikeNode(adapter, node) && node.body) {
158
+ const end = toPosition(sourceFile, node.getEnd());
159
+
160
+ functions.push({
161
+ bodyStart: toPosition(sourceFile, node.body.getStart(sourceFile)),
162
+ ignored: isIgnored(ignore, start),
163
+ range: { end, start },
164
+ risk: {
165
+ complexity: calculateCyclomaticComplexity(node, adapter),
166
+ coveragePercent: 0,
167
+ coveredStatements: 0,
168
+ crapScore: 0,
169
+ endLine: end.line,
170
+ evidence: "missing",
76
171
  filePath,
77
- lineCount,
78
- name: getFunctionName(adapter, node, sourceFile),
79
- startLine,
80
- });
81
- }
172
+ lineCount: end.line - start.line + 1,
173
+ name: getFunctionName(adapter, node),
174
+ startColumn: start.column + 1,
175
+ startLine: start.line,
176
+ statements: 0,
177
+ },
178
+ });
82
179
  }
83
180
 
84
181
  adapter.forEachChild(node, visit);
@@ -86,191 +183,384 @@ export async function analyzeFileRisk({
86
183
 
87
184
  visit(sourceFile);
88
185
 
89
- return risks;
186
+ return functions;
90
187
  }
91
188
 
92
- export function formatRiskLine(risk) {
93
- return [
94
- `${risk.filePath}:${risk.startLine}`,
95
- risk.name,
96
- `CRAP ${risk.crapScore.toFixed(1)}`,
97
- `complexity ${risk.complexity}`,
98
- `coverage ${risk.coveragePercent.toFixed(0)}%`,
99
- `${risk.lineCount} lines`,
100
- ].join(" | ");
101
- }
189
+ function assignStatementCoverage(functions, coverage) {
190
+ for (const [id, location] of Object.entries(coverage.statementMap)) {
191
+ const owner = findOwner(functions, location.start);
102
192
 
103
- export function calculateCyclomaticComplexity(
104
- node,
105
- adapter = getDefaultComplexityAdapter(),
106
- ) {
107
- let complexity = 1;
193
+ // Module-level statements belong to no function row.
194
+ if (!owner) {
195
+ continue;
196
+ }
108
197
 
109
- function visit(child) {
110
- if (addsDecisionPath(adapter, child)) {
111
- complexity += 1;
198
+ owner.risk.statements += 1;
199
+ owner.risk.coveredStatements += coverage.s[id] > 0 ? 1 : 0;
200
+ }
201
+
202
+ const v8Layout = hasFirstTokenCounters(functions, coverage.fnMap);
203
+ const countersByOwner = groupCountersBy(coverage.fnMap, (start) =>
204
+ findCounterOwner(functions, start, v8Layout),
205
+ );
206
+
207
+ for (const fn of functions) {
208
+ const { risk } = fn;
209
+
210
+ if (risk.statements > 0) {
211
+ risk.coveragePercent = (risk.coveredStatements / risk.statements) * 100;
212
+ risk.evidence = "statements";
213
+ continue;
112
214
  }
113
215
 
114
- adapter.forEachChild(child, visit);
216
+ const counters = countersByOwner.get(fn) ?? [];
217
+
218
+ if (counters.length === 1) {
219
+ risk.coveragePercent = coverage.f[counters[0]] > 0 ? 100 : 0;
220
+ risk.evidence = "function";
221
+ }
115
222
  }
223
+ }
116
224
 
117
- visit(node);
225
+ // Istanbul places a function counter at the function's body; per-line V8
226
+ // converters place it at the function's first token. Only V8 puts a counter at
227
+ // the first token of a function that is not another arrow's expression body.
228
+ function hasFirstTokenCounters(functions, fnMap) {
229
+ const counterStarts = new Set(
230
+ Object.values(fnMap).map(({ loc }) => positionKey(loc.start)),
231
+ );
232
+ const expressionBodies = new Set(
233
+ functions.map((fn) => positionKey(fn.bodyStart)),
234
+ );
118
235
 
119
- return complexity;
236
+ return functions.some((fn) => {
237
+ const start = positionKey(fn.range.start);
238
+ return !expressionBodies.has(start) && counterStarts.has(start);
239
+ });
120
240
  }
121
241
 
122
- function addsDecisionPath(adapter, node) {
123
- if (
124
- adapter.isIfStatement(node) ||
125
- adapter.isForStatement(node) ||
126
- adapter.isForInStatement(node) ||
127
- adapter.isForOfStatement(node) ||
128
- adapter.isWhileStatement(node) ||
129
- adapter.isDoStatement(node) ||
130
- adapter.isCaseClause(node) ||
131
- adapter.isCatchClause(node) ||
132
- adapter.isConditionalExpression(node)
133
- ) {
134
- return true;
242
+ // The two layouts meet only where an arrow is another arrow's expression body
243
+ // (`a => b => 1`): Istanbul's counter there is the outer arrow's, V8's is the
244
+ // inner arrow's.
245
+ function findCounterOwner(functions, start, v8Layout) {
246
+ const startingHere = functions.findLast(
247
+ (fn) => comparePositions(fn.range.start, start) === 0,
248
+ );
249
+
250
+ if (!startingHere) {
251
+ // A nested function's counter must never stand in for its parent's.
252
+ return findOwner(functions, start);
135
253
  }
136
254
 
137
- return (
138
- adapter.isBinaryExpression(node) &&
139
- (node.operatorToken.kind === adapter.SyntaxKind.AmpersandAmpersandToken ||
140
- node.operatorToken.kind === adapter.SyntaxKind.BarBarToken ||
141
- node.operatorToken.kind === adapter.SyntaxKind.QuestionQuestionToken)
255
+ const parent = functions.find(
256
+ (fn) => comparePositions(fn.bodyStart, start) === 0,
142
257
  );
258
+
259
+ return parent && !v8Layout ? parent : startingHere;
143
260
  }
144
261
 
145
- function getFunctionCoveragePercent({ coverageFunctions, endLine, startLine }) {
146
- const exactMatch = coverageFunctions.find(
147
- (coverageFunction) =>
148
- coverageFunction.declarationLine === startLine ||
149
- (coverageFunction.startLine === startLine &&
150
- coverageFunction.endLine === endLine),
151
- );
262
+ function groupCountersBy(fnMap, getFunction) {
263
+ const groups = new Map();
152
264
 
153
- if (exactMatch) {
154
- return exactMatch.coveragePercent;
265
+ for (const [id, metadata] of Object.entries(fnMap)) {
266
+ const fn = getFunction(metadata.loc.start);
267
+
268
+ if (fn) {
269
+ groups.set(fn, [...(groups.get(fn) ?? []), id]);
270
+ }
155
271
  }
156
272
 
157
- const containingMatch = coverageFunctions.find(
158
- (coverageFunction) =>
159
- (coverageFunction.declarationLine >= startLine &&
160
- coverageFunction.declarationLine <= endLine) ||
161
- (coverageFunction.startLine <= endLine &&
162
- coverageFunction.endLine >= startLine),
273
+ return groups;
274
+ }
275
+
276
+ // Functions are collected in preorder, so the last match is the innermost.
277
+ function findOwner(functions, position) {
278
+ return functions.findLast((fn) => containsPosition(fn.range, position));
279
+ }
280
+
281
+ // The start is exclusive: Istanbul places initializer counters and an outer
282
+ // arrow's expression body at a function's first token, and those belong to
283
+ // the enclosing scope.
284
+ function containsPosition(range, position) {
285
+ return (
286
+ comparePositions(range.start, position) < 0 &&
287
+ comparePositions(position, range.end) < 0
163
288
  );
289
+ }
164
290
 
165
- return containingMatch?.coveragePercent ?? 0;
291
+ function comparePositions(left, right) {
292
+ return left.line - right.line || left.column - right.column;
166
293
  }
167
294
 
168
- function getFunctionName(adapter, node, sourceFile) {
169
- if (
170
- (adapter.isFunctionDeclaration(node) ||
171
- adapter.isFunctionExpression(node)) &&
172
- node.name
295
+ // The line terminators TypeScript and Babel recognise.
296
+ const lineTerminatorPattern = /\r\n|[\n\r\u2028\u2029]/g;
297
+ const commentPattern = /\/\*([\s\S]*?)\*\/|\/\/([^\n\r\u2028\u2029]*)/g;
298
+ const ignoreDirectivePattern =
299
+ /^\s*(?:istanbul|v8|c8)\s+ignore\s+(next|if|else|start|stop|file)(?:\s+(\d+))?(?=\W|$)/;
300
+ const triviaPattern = /(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n\r\u2028\u2029]*)*/y;
301
+
302
+ // Coverage tools drop counters for code under these comments:
303
+ // `istanbul|v8|c8 ignore next [lines]`, `ignore if|else`, `ignore start` … `ignore stop`,
304
+ // `ignore file`.
305
+ function findIgnoreComments(sourceText, literalRanges) {
306
+ const lineStarts = [0];
307
+
308
+ for (const match of sourceText.matchAll(lineTerminatorPattern)) {
309
+ lineStarts.push(match.index + match[0].length);
310
+ }
311
+
312
+ const toSourcePosition = (offset) => {
313
+ const line = lineStarts.findLastIndex((lineStart) => lineStart <= offset);
314
+ return { column: offset - lineStarts[line], line: line + 1 };
315
+ };
316
+ const toOffset = ({ column, line }) => lineStarts[line - 1] + column;
317
+ const literals = literalRanges.map(({ end, start }) => ({
318
+ end: toOffset(end),
319
+ start: toOffset(start),
320
+ }));
321
+ const ignore = {
322
+ file: false,
323
+ lineRanges: [],
324
+ nextTargets: new Map(),
325
+ ranges: [],
326
+ };
327
+ let regionStart;
328
+
329
+ commentPattern.lastIndex = 0;
330
+
331
+ for (
332
+ let match = commentPattern.exec(sourceText);
333
+ match;
334
+ match = commentPattern.exec(sourceText)
173
335
  ) {
174
- return node.name.getText(sourceFile);
336
+ const literal = literals.find(
337
+ ({ end, start }) => start <= match.index && match.index < end,
338
+ );
339
+
340
+ // Comment-like text inside a literal is not a comment; resume after it.
341
+ if (literal) {
342
+ commentPattern.lastIndex = literal.end;
343
+ continue;
344
+ }
345
+
346
+ const directive = ignoreDirectivePattern.exec(match[1] ?? match[2]);
347
+
348
+ if (!directive) {
349
+ continue;
350
+ }
351
+
352
+ const [, kind, lineCount] = directive;
353
+ const commentEnd = match.index + match[0].length;
354
+
355
+ if (kind === "file") {
356
+ ignore.file = true;
357
+ } else if (kind === "start") {
358
+ regionStart ??= toSourcePosition(commentEnd);
359
+ } else if (kind === "stop" && regionStart) {
360
+ ignore.ranges.push({
361
+ end: toSourcePosition(match.index),
362
+ start: regionStart,
363
+ });
364
+ regionStart = undefined;
365
+ } else if (kind === "next" && lineCount) {
366
+ // c8 style: the next N lines.
367
+ const { line } = toSourcePosition(commentEnd);
368
+ ignore.lineRanges.push([line + 1, line + Number(lineCount)]);
369
+ } else if (kind === "next" || kind === "if" || kind === "else") {
370
+ triviaPattern.lastIndex = commentEnd;
371
+ triviaPattern.exec(sourceText);
372
+ ignore.nextTargets.set(
373
+ positionKey(toSourcePosition(triviaPattern.lastIndex)),
374
+ kind,
375
+ );
376
+ }
175
377
  }
176
378
 
177
- if (adapter.isMethodDeclaration(node) && node.name) {
178
- return node.name.getText(sourceFile);
379
+ if (regionStart) {
380
+ ignore.ranges.push({
381
+ end: { column: 0, line: Number.POSITIVE_INFINITY },
382
+ start: regionStart,
383
+ });
179
384
  }
180
385
 
181
- const parent = node.parent;
386
+ return ignore;
387
+ }
182
388
 
183
- if (adapter.isVariableDeclaration(parent) && parent.name) {
184
- return parent.name.getText(sourceFile);
185
- }
389
+ // Strings, templates, regex literals and JSX text can contain `/*` or `//`.
390
+ function collectLiteralRanges(adapter) {
391
+ const { SyntaxKind, sourceFile } = adapter;
392
+ const literalKinds = new Set([
393
+ SyntaxKind.StringLiteral,
394
+ SyntaxKind.NoSubstitutionTemplateLiteral,
395
+ SyntaxKind.TemplateHead,
396
+ SyntaxKind.TemplateMiddle,
397
+ SyntaxKind.TemplateTail,
398
+ SyntaxKind.RegularExpressionLiteral,
399
+ SyntaxKind.JsxText,
400
+ ]);
401
+ const ranges = [];
186
402
 
187
- if (adapter.isPropertyAssignment(parent) && parent.name) {
188
- return parent.name.getText(sourceFile);
403
+ function visit(node) {
404
+ if (literalKinds.has(node.kind)) {
405
+ ranges.push({
406
+ end: toPosition(sourceFile, node.getEnd()),
407
+ // JSX text has no leading trivia; its full start is its text.
408
+ start: toPosition(
409
+ sourceFile,
410
+ node.kind === SyntaxKind.JsxText
411
+ ? node.pos
412
+ : node.getStart(sourceFile),
413
+ ),
414
+ });
415
+ }
416
+
417
+ adapter.forEachChild(node, visit);
189
418
  }
190
419
 
191
- return "<anonymous>";
420
+ visit(sourceFile);
421
+
422
+ return ranges;
192
423
  }
193
424
 
194
- function isFunctionLikeNode(adapter, node) {
425
+ function isIgnored(ignore, position) {
195
426
  return (
196
- adapter.isFunctionDeclaration(node) ||
197
- adapter.isFunctionExpression(node) ||
198
- adapter.isArrowFunction(node) ||
199
- adapter.isMethodDeclaration(node)
427
+ ignore.file ||
428
+ ignore.ranges.some(
429
+ (range) =>
430
+ comparePositions(range.start, position) <= 0 &&
431
+ comparePositions(position, range.end) < 0,
432
+ ) ||
433
+ ignore.lineRanges.some(
434
+ ([first, last]) => position.line >= first && position.line <= last,
435
+ )
200
436
  );
201
437
  }
202
438
 
203
- function getTs5Adapter() {
204
- return {
205
- ...ts,
206
- forEachChild: ts.forEachChild,
207
- };
439
+ function positionKey({ column, line }) {
440
+ return `${line}:${column}`;
208
441
  }
209
442
 
210
- function getDefaultComplexityAdapter() {
211
- if (ts.createSourceFile) {
212
- return getTs5Adapter();
443
+ function assertStatementsInSource(coverage, sourceText, filePath) {
444
+ const lines = sourceText.split(lineTerminatorPattern);
445
+
446
+ for (const { start } of Object.values(coverage.statementMap)) {
447
+ const line = lines[start.line - 1];
448
+
449
+ if (line === undefined || start.column > line.length) {
450
+ throw new Error(
451
+ `Coverage for ${filePath} does not match its current source (statement at ${start.line}:${start.column + 1}). Re-run coverage.`,
452
+ );
453
+ }
213
454
  }
455
+ }
214
456
 
215
- return getTs7NodeAdapter();
457
+ function hasExecutableModuleStatements({ SyntaxKind, sourceFile }) {
458
+ return hasExecutableStatements(SyntaxKind, sourceFile.statements);
216
459
  }
217
460
 
218
- function getTs7NodeAdapter() {
219
- return {
220
- SyntaxKind: ts7SyntaxKind,
221
- forEachChild(node, visitor) {
222
- node.forEachChild?.(visitor);
223
- },
224
- isBinaryExpression: isSyntaxKind(ts7SyntaxKind.BinaryExpression),
225
- isCaseClause: isSyntaxKind(ts7SyntaxKind.CaseClause),
226
- isCatchClause: isSyntaxKind(ts7SyntaxKind.CatchClause),
227
- isConditionalExpression: isSyntaxKind(ts7SyntaxKind.ConditionalExpression),
228
- isDoStatement: isSyntaxKind(ts7SyntaxKind.DoStatement),
229
- isForInStatement: isSyntaxKind(ts7SyntaxKind.ForInStatement),
230
- isForOfStatement: isSyntaxKind(ts7SyntaxKind.ForOfStatement),
231
- isForStatement: isSyntaxKind(ts7SyntaxKind.ForStatement),
232
- isIfStatement: isSyntaxKind(ts7SyntaxKind.IfStatement),
233
- isWhileStatement: isSyntaxKind(ts7SyntaxKind.WhileStatement),
234
- };
461
+ function hasExecutableStatements(SyntaxKind, statements) {
462
+ return statements.some((statement) => {
463
+ if (
464
+ statement.modifiers?.some(
465
+ (modifier) => modifier.kind === SyntaxKind.DeclareKeyword,
466
+ )
467
+ ) {
468
+ return false;
469
+ }
470
+
471
+ switch (statement.kind) {
472
+ case SyntaxKind.ImportEqualsDeclaration:
473
+ return !statement.isTypeOnly;
474
+ case SyntaxKind.ImportDeclaration:
475
+ // Side-effect imports (`import "./x"`) run code; binding imports do not.
476
+ return !statement.importClause;
477
+ case SyntaxKind.ModuleDeclaration:
478
+ // TypeScript emits a namespace only when its body has runtime code.
479
+ return isExecutableNamespace(SyntaxKind, statement);
480
+ case SyntaxKind.ExportDeclaration:
481
+ case SyntaxKind.InterfaceDeclaration:
482
+ case SyntaxKind.TypeAliasDeclaration:
483
+ case SyntaxKind.FunctionDeclaration:
484
+ case SyntaxKind.EmptyStatement:
485
+ return false;
486
+ default:
487
+ return true;
488
+ }
489
+ });
235
490
  }
236
491
 
237
- function isSyntaxKind(kind) {
238
- return (node) => node?.kind === kind;
492
+ function isExecutableNamespace(SyntaxKind, declaration) {
493
+ const { body } = declaration;
494
+
495
+ if (!body) {
496
+ return false;
497
+ }
498
+
499
+ // `namespace A.B {}` nests one ModuleDeclaration per name.
500
+ return body.kind === SyntaxKind.ModuleDeclaration
501
+ ? isExecutableNamespace(SyntaxKind, body)
502
+ : hasExecutableStatements(SyntaxKind, body.statements);
239
503
  }
240
504
 
241
- const ts7SyntaxKind = {
242
- AmpersandAmpersandToken: 55,
243
- BarBarToken: 56,
244
- BinaryExpression: 227,
245
- CaseClause: 297,
246
- CatchClause: 300,
247
- ConditionalExpression: 228,
248
- DoStatement: 247,
249
- ForInStatement: 250,
250
- ForOfStatement: 251,
251
- ForStatement: 249,
252
- IfStatement: 246,
253
- QuestionQuestionToken: 60,
254
- WhileStatement: 248,
255
- };
256
-
257
- async function getTypescriptAdapter({ filePath, sourceFilePath, sourceText }) {
258
- if (ts.createSourceFile) {
259
- return {
260
- ...getTs5Adapter(),
261
- sourceFile: ts.createSourceFile(
262
- filePath,
263
- sourceText,
264
- ts.ScriptTarget.Latest,
265
- true,
266
- ),
267
- };
505
+ function toPosition(sourceFile, offset) {
506
+ const { character, line } = sourceFile.getLineAndCharacterOfPosition(offset);
507
+
508
+ return { column: character, line: line + 1 };
509
+ }
510
+
511
+ function getFunctionName({ SyntaxKind, sourceFile }, node) {
512
+ if (node.kind === SyntaxKind.Constructor) {
513
+ return "constructor";
268
514
  }
269
515
 
270
- const [{ API }, ast] = await Promise.all([
271
- import("typescript/unstable/sync"),
272
- import("typescript/unstable/ast"),
273
- ]);
516
+ if (node.name) {
517
+ return node.name.getText(sourceFile);
518
+ }
519
+
520
+ const parent = node.parent;
521
+
522
+ if (
523
+ (parent?.kind === SyntaxKind.VariableDeclaration ||
524
+ parent?.kind === SyntaxKind.PropertyAssignment ||
525
+ parent?.kind === SyntaxKind.PropertyDeclaration) &&
526
+ parent.name
527
+ ) {
528
+ return parent.name.getText(sourceFile);
529
+ }
530
+
531
+ return "<anonymous>";
532
+ }
533
+
534
+ function isFunctionLikeNode({ SyntaxKind }, node) {
535
+ switch (node.kind) {
536
+ case SyntaxKind.FunctionDeclaration:
537
+ case SyntaxKind.FunctionExpression:
538
+ case SyntaxKind.ArrowFunction:
539
+ case SyntaxKind.MethodDeclaration:
540
+ case SyntaxKind.Constructor:
541
+ case SyntaxKind.GetAccessor:
542
+ case SyntaxKind.SetAccessor:
543
+ return true;
544
+ default:
545
+ return false;
546
+ }
547
+ }
548
+
549
+ function forEachTs7Child(node, visitor) {
550
+ ts7Ast.visitEachChild(node, visitor, null);
551
+ }
552
+
553
+ async function parseSourceFile({ filePath, sourceFilePath, sourceText }) {
554
+ if (!ts7Ast) {
555
+ return ts.createSourceFile(
556
+ filePath,
557
+ sourceText,
558
+ ts.ScriptTarget.Latest,
559
+ true,
560
+ );
561
+ }
562
+
563
+ const { API } = await import("typescript/unstable/sync");
274
564
  const temporaryDirectory = mkdtempSync(join(tmpdir(), "crap-ts-"));
275
565
  const resolvedPath = join(
276
566
  temporaryDirectory,
@@ -290,13 +580,7 @@ async function getTypescriptAdapter({ filePath, sourceFilePath, sourceText }) {
290
580
  throw new Error(`Unable to parse TypeScript source file: ${filePath}`);
291
581
  }
292
582
 
293
- return {
294
- ...ast,
295
- forEachChild(node, visitor) {
296
- ast.visitEachChild(node, visitor, null);
297
- },
298
- sourceFile,
299
- };
583
+ return sourceFile;
300
584
  } finally {
301
585
  api.close();
302
586