@yearofthedan/warp 0.0.0-stage → 0.2.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.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/dist/analysis/complexity.d.ts +4 -0
  4. package/dist/analysis/complexity.js +84 -0
  5. package/dist/analysis/folders.d.ts +2 -0
  6. package/dist/analysis/folders.js +15 -0
  7. package/dist/analysis/imports.d.ts +13 -0
  8. package/dist/analysis/imports.js +135 -0
  9. package/dist/analysis/members.d.ts +4 -0
  10. package/dist/analysis/members.js +190 -0
  11. package/dist/analysis/source.d.ts +13 -0
  12. package/dist/analysis/source.js +29 -0
  13. package/dist/analysis/specifiers.d.ts +2 -0
  14. package/dist/analysis/specifiers.js +6 -0
  15. package/dist/analysis/typescript.d.ts +2 -0
  16. package/dist/analysis/typescript.js +105 -0
  17. package/dist/app/check.d.ts +23 -0
  18. package/dist/app/check.js +15 -0
  19. package/dist/app/checkModel.d.ts +5 -0
  20. package/dist/app/checkModel.js +30 -0
  21. package/dist/app/diff.d.ts +25 -0
  22. package/dist/app/diff.js +53 -0
  23. package/dist/app/facts.d.ts +7 -0
  24. package/dist/app/facts.js +55 -0
  25. package/dist/app/load.d.ts +13 -0
  26. package/dist/app/load.js +76 -0
  27. package/dist/app/ports.d.ts +41 -0
  28. package/dist/app/ports.js +1 -0
  29. package/dist/app/unclassified.d.ts +5 -0
  30. package/dist/app/unclassified.js +13 -0
  31. package/dist/builtins/cognitive-complexity/cognitiveComplexity.d.ts +6 -0
  32. package/dist/builtins/cognitive-complexity/cognitiveComplexity.js +26 -0
  33. package/dist/builtins/components.d.ts +2 -0
  34. package/dist/builtins/components.js +20 -0
  35. package/dist/builtins/dependency-direction/dependencyDirection.d.ts +2 -0
  36. package/dist/builtins/dependency-direction/dependencyDirection.js +68 -0
  37. package/dist/builtins/file-cohesion/fileCohesion.d.ts +6 -0
  38. package/dist/builtins/file-cohesion/fileCohesion.js +30 -0
  39. package/dist/builtins/function-cohesion/functionCohesion.d.ts +6 -0
  40. package/dist/builtins/function-cohesion/functionCohesion.js +30 -0
  41. package/dist/builtins/index.d.ts +4 -0
  42. package/dist/builtins/index.js +30 -0
  43. package/dist/builtins/loops.d.ts +25 -0
  44. package/dist/builtins/loops.js +64 -0
  45. package/dist/builtins/module-cycle/moduleCycle.d.ts +3 -0
  46. package/dist/builtins/module-cycle/moduleCycle.js +61 -0
  47. package/dist/builtins/module-externals/moduleExternals.d.ts +2 -0
  48. package/dist/builtins/module-externals/moduleExternals.js +41 -0
  49. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.d.ts +2 -0
  50. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +47 -0
  51. package/dist/builtins/no-cycle/noCycle.d.ts +3 -0
  52. package/dist/builtins/no-cycle/noCycle.js +39 -0
  53. package/dist/builtins/no-double-export/noDoubleExport.d.ts +2 -0
  54. package/dist/builtins/no-double-export/noDoubleExport.js +38 -0
  55. package/dist/builtins/packages.d.ts +2 -0
  56. package/dist/builtins/packages.js +5 -0
  57. package/dist/builtins/place.d.ts +2 -0
  58. package/dist/builtins/place.js +6 -0
  59. package/dist/builtins/shared.d.ts +10 -0
  60. package/dist/builtins/shared.js +13 -0
  61. package/dist/builtins/unused-declaration/declarations.d.ts +32 -0
  62. package/dist/builtins/unused-declaration/declarations.js +26 -0
  63. package/dist/builtins/unused-declaration/empty.d.ts +3 -0
  64. package/dist/builtins/unused-declaration/empty.js +22 -0
  65. package/dist/builtins/unused-declaration/grants.d.ts +3 -0
  66. package/dist/builtins/unused-declaration/grants.js +48 -0
  67. package/dist/builtins/unused-declaration/surfaces.d.ts +3 -0
  68. package/dist/builtins/unused-declaration/surfaces.js +57 -0
  69. package/dist/builtins/unused-declaration/unusedDeclaration.d.ts +2 -0
  70. package/dist/builtins/unused-declaration/unusedDeclaration.js +14 -0
  71. package/dist/cli.d.ts +2 -0
  72. package/dist/cli.js +168 -0
  73. package/dist/config/loadConfig.d.ts +7 -0
  74. package/dist/config/loadConfig.js +53 -0
  75. package/dist/config/toolDigest.d.ts +1 -0
  76. package/dist/config/toolDigest.js +16 -0
  77. package/dist/git/cache.d.ts +3 -0
  78. package/dist/git/cache.js +41 -0
  79. package/dist/git/repository.d.ts +3 -0
  80. package/dist/git/repository.js +76 -0
  81. package/dist/index.d.ts +8 -0
  82. package/dist/index.js +4 -0
  83. package/dist/model/archetype/builder.d.ts +183 -0
  84. package/dist/model/archetype/builder.js +85 -0
  85. package/dist/model/archetype/data.d.ts +92 -0
  86. package/dist/model/archetype/data.js +1 -0
  87. package/dist/model/archetype/draft.d.ts +37 -0
  88. package/dist/model/archetype/draft.js +275 -0
  89. package/dist/model/archetype/reach.d.ts +35 -0
  90. package/dist/model/archetype/reach.js +209 -0
  91. package/dist/model/archetype/references.d.ts +13 -0
  92. package/dist/model/archetype/references.js +166 -0
  93. package/dist/model/archetype/requirements.d.ts +5 -0
  94. package/dist/model/archetype/requirements.js +69 -0
  95. package/dist/model/archetype/resolve.d.ts +30 -0
  96. package/dist/model/archetype/resolve.js +315 -0
  97. package/dist/model/archetype/rulesets.d.ts +4 -0
  98. package/dist/model/archetype/rulesets.js +115 -0
  99. package/dist/model/archetype/settings.d.ts +21 -0
  100. package/dist/model/archetype/settings.js +64 -0
  101. package/dist/model/archetype/shared.d.ts +5 -0
  102. package/dist/model/archetype/shared.js +4 -0
  103. package/dist/model/configError.d.ts +3 -0
  104. package/dist/model/configError.js +3 -0
  105. package/dist/model/facts.d.ts +57 -0
  106. package/dist/model/facts.js +1 -0
  107. package/dist/reporters/agent.d.ts +4 -0
  108. package/dist/reporters/agent.js +24 -0
  109. package/dist/reporters/claudeHook.d.ts +2 -0
  110. package/dist/reporters/claudeHook.js +10 -0
  111. package/dist/reporters/index.d.ts +2 -0
  112. package/dist/reporters/index.js +9 -0
  113. package/dist/reporters/json.d.ts +2 -0
  114. package/dist/reporters/json.js +4 -0
  115. package/dist/reporters/model.d.ts +4 -0
  116. package/dist/reporters/model.js +60 -0
  117. package/dist/reporters/omp.d.ts +2 -0
  118. package/dist/reporters/omp.js +6 -0
  119. package/dist/reporters/reporter.d.ts +22 -0
  120. package/dist/reporters/reporter.js +5 -0
  121. package/dist/reporters/sarif.d.ts +2 -0
  122. package/dist/reporters/sarif.js +44 -0
  123. package/dist/reporters/text.d.ts +8 -0
  124. package/dist/reporters/text.js +39 -0
  125. package/dist/rules/diff.d.ts +10 -0
  126. package/dist/rules/diff.js +31 -0
  127. package/dist/rules/registry.d.ts +5 -0
  128. package/dist/rules/registry.js +33 -0
  129. package/dist/rules/rule.d.ts +59 -0
  130. package/dist/rules/rule.js +18 -0
  131. package/package.json +43 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yearofthedan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # warp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ warp checks a TypeScript codebase against a declared model of its modules. A `warp.config.ts` names the modules and
4
+ what each may use, and warp reports the code that steps outside it:
5
+
6
+ - imports outside a module's reach, including packages it doesn't list.
7
+ - imports and re-exports that go around a module's surface.
8
+ - import loops between files and between modules.
9
+ - files and functions that are too large or too tangled to follow.
10
+ - parts of the config that the code no longer uses.
11
+
12
+ `warp diff` reports only what a change made new or worse, so it can run on a pull request or after every edit of a
13
+ coding agent.
14
+
15
+ ## Quick start
16
+
17
+ warp needs Node 26 or later. Add it to the project as a dev dependency:
18
+
19
+ ```sh
20
+ pnpm add -D @yearofthedan/warp
21
+ ```
22
+
23
+ Describe the codebase as it is, one module per folder under `src/`, in a `warp.config.ts` next to the project's
24
+ `tsconfig.json`:
25
+
26
+ ```ts
27
+ // warp.config.ts
28
+ import { all, archetype, defineConfig, dir, exposes, files, pkg, ruleset, using } from '@yearofthedan/warp';
29
+
30
+ const app = archetype('app')
31
+ .contains((c) =>
32
+ c
33
+ .module('utils', dir('src/utils'), exposes(all()))
34
+ .module('db', dir('src/db'), exposes(all()))
35
+ .module('api', dir('src/api'), exposes(all()).using((m) => [m.db, m.utils, pkg('*')])),
36
+ )
37
+ .entry(files('src/index.ts'))
38
+ .tests(using([pkg('vitest')]));
39
+
40
+ const base = ruleset().on(app.modules.tests, { 'function-cohesion': false });
41
+
42
+ export default defineConfig({ root: app, tests: files('src/**/*.test.ts'), rulesets: { default: base } });
43
+ ```
44
+
45
+ Then check it, and after an edit, see what the edit broke:
46
+
47
+ ```sh
48
+ pnpm exec warp check # every finding in the working tree
49
+ pnpm exec warp diff HEAD # what changed since the last commit made new or worse
50
+ ```
51
+
52
+ ```text
53
+ new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (app.utils src/utils) imports src/db/client.ts (app.db src/db), which is outside utils's reach: utils may use nothing. Add what holds src/db/client.ts to a using if the dependency is intended, or move the code.
54
+ ```
55
+
56
+ ## Read next
57
+
58
+ - [Getting started](docs/getting-started.md): from this config to a clean `warp check` and a first `diff`, step by
59
+ step.
60
+ - [Fixing findings](docs/fixing-findings.md): how to read a finding and decide between changing the code and changing
61
+ the config.
62
+ - [Concepts](docs/concepts.md): what each of warp's terms means.
63
+ - [Config](docs/config.md) and [CLI](docs/cli.md): the reference for each.
64
+ - [Rules](docs/rules.md): every rule warp checks, each with its page.
65
+ - [Agents and CI](docs/agents-and-ci.md): running warp after each edit of Claude Code or omp, and on pull requests.
66
+ - [Hexagonal layout](docs/examples/hexagonal.md): a stricter config, for ports and adapters.
67
+
68
+ ## Limits
69
+
70
+ - warp follows static `import` and `export … from` declarations. Dependencies through `import()`, `require()` and
71
+ `import x = require()` go unchecked.
72
+ - A namespace import (`import * as x`) points at the module the specifier resolves to, a barrel included.
73
+ - Each class method is checked as a function of its own, and a class is one member of its file.
@@ -0,0 +1,4 @@
1
+ import type { Node } from 'typescript/ast';
2
+ import type { Complexity } from '../model/facts.ts';
3
+ import { type Source } from './source.ts';
4
+ export declare const cognitiveComplexity: (fn: Node, self: string | undefined, source: Source) => Complexity;
@@ -0,0 +1,84 @@
1
+ import { SyntaxKind } from 'typescript/ast';
2
+ import { isBinaryExpression, isBreakOrContinueStatement, isCallExpression, isCatchClause, isConditionalExpression, isDoStatement, isForInStatement, isForOfStatement, isForStatement, isFunctionLikeDeclaration, isIdentifier, isIfStatement, isPropertyAccessExpression, isSwitchStatement, isWhileStatement, } from 'typescript/ast/is';
3
+ import { symbolKey } from './source.js';
4
+ export const cognitiveComplexity = (fn, self, source) => {
5
+ const walker = { fn, self, source, increments: [] };
6
+ visit(walker, fn, 0);
7
+ return {
8
+ total: walker.increments.reduce((sum, increment) => sum + increment.amount, 0),
9
+ increments: walker.increments,
10
+ };
11
+ };
12
+ const add = (walker, node, amount, reason) => walker.increments.push({ line: walker.source.line(node), amount, reason });
13
+ const visitChildren = (walker, node, nesting) => node.forEachChild((child) => {
14
+ visit(walker, child, nesting);
15
+ });
16
+ const visit = (walker, node, nesting) => {
17
+ if (isIfStatement(node))
18
+ return visitIf(walker, node, nesting);
19
+ if (isConditionalExpression(node))
20
+ return visitTernary(walker, node, nesting);
21
+ const structure = nestingStructure(node);
22
+ if (structure)
23
+ add(walker, node, 1 + nesting, structure);
24
+ const nested = structure !== undefined || (node !== walker.fn && isFunctionLikeDeclaration(node));
25
+ if (!nested)
26
+ addFlat(walker, node);
27
+ visitChildren(walker, node, nested ? nesting + 1 : nesting);
28
+ };
29
+ const visitIf = (walker, node, nesting) => {
30
+ const elseIf = isIfStatement(node.parent) && node.parent.elseStatement === node;
31
+ add(walker, node, elseIf ? 1 : 1 + nesting, elseIf ? 'else if' : 'if');
32
+ visit(walker, node.expression, nesting);
33
+ visit(walker, node.thenStatement, nesting + 1);
34
+ const otherwise = node.elseStatement;
35
+ if (!otherwise)
36
+ return;
37
+ if (isIfStatement(otherwise))
38
+ return visit(walker, otherwise, nesting);
39
+ add(walker, otherwise, 1, 'else');
40
+ visit(walker, otherwise, nesting + 1);
41
+ };
42
+ const visitTernary = (walker, node, nesting) => {
43
+ add(walker, node, 1 + nesting, 'ternary');
44
+ visit(walker, node.condition, nesting);
45
+ visit(walker, node.whenTrue, nesting + 1);
46
+ visit(walker, node.whenFalse, nesting + 1);
47
+ };
48
+ const addFlat = (walker, node) => {
49
+ if (isBreakOrContinueStatement(node) && node.label) {
50
+ add(walker, node, 1, `labelled ${node.kind === SyntaxKind.BreakStatement ? 'break' : 'continue'}`);
51
+ }
52
+ if (isBinaryExpression(node) && isLogical(node) && !(isBinaryExpression(node.parent) && isLogical(node.parent))) {
53
+ const operators = logicalSequence(node);
54
+ add(walker, node, 1 + operators.filter((op, index) => index > 0 && op !== operators[index - 1]).length, 'logical operators');
55
+ }
56
+ if (isCallExpression(node) && walker.self && calleeKey(walker, node.expression) === walker.self)
57
+ add(walker, node, 1, 'recursion');
58
+ };
59
+ const nestingStructure = (node) => {
60
+ if (isSwitchStatement(node))
61
+ return 'switch';
62
+ if (isForStatement(node) || isForInStatement(node) || isForOfStatement(node))
63
+ return 'for';
64
+ if (isWhileStatement(node))
65
+ return 'while';
66
+ if (isDoStatement(node))
67
+ return 'do';
68
+ if (isCatchClause(node))
69
+ return 'catch';
70
+ return undefined;
71
+ };
72
+ const logicalKinds = new Set([
73
+ SyntaxKind.AmpersandAmpersandToken,
74
+ SyntaxKind.BarBarToken,
75
+ SyntaxKind.QuestionQuestionToken,
76
+ ]);
77
+ const isLogical = (node) => logicalKinds.has(node.operatorToken.kind);
78
+ const logicalSequence = (node) => isBinaryExpression(node) && isLogical(node)
79
+ ? [...logicalSequence(node.left), node.operatorToken.kind, ...logicalSequence(node.right)]
80
+ : [];
81
+ const calleeKey = (walker, callee) => {
82
+ const name = isPropertyAccessExpression(callee) ? callee.name : callee;
83
+ return isIdentifier(name) ? symbolKey(walker.source.symbolOf(name)) : undefined;
84
+ };
@@ -0,0 +1,2 @@
1
+ import type { Folders } from '../model/archetype/resolve.ts';
2
+ export declare const diskFolders: (root: string) => Folders;
@@ -0,0 +1,15 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const skipped = (name) => name.startsWith('.') || name === 'node_modules';
4
+ export const diskFolders = (root) => ({
5
+ folders: (dir) => {
6
+ const path = join(root, dir);
7
+ if (!existsSync(path))
8
+ return [];
9
+ return readdirSync(path, { withFileTypes: true })
10
+ .filter((entry) => entry.isDirectory() && !skipped(entry.name))
11
+ .map((entry) => entry.name)
12
+ .sort();
13
+ },
14
+ exists: (path) => existsSync(join(root, path)),
15
+ });
@@ -0,0 +1,13 @@
1
+ import { type Checker, type Program } from 'typescript/sync';
2
+ import type { ExternalImport, ImportEdge } from '../model/facts.ts';
3
+ import type { Source } from './source.ts';
4
+ export interface Resolver {
5
+ checker: Checker;
6
+ program: Program;
7
+ relative: (pathOrFileName: string) => string | undefined;
8
+ }
9
+ export interface FileEdges {
10
+ imports: ImportEdge[];
11
+ externals: ExternalImport[];
12
+ }
13
+ export declare const fileEdges: (source: Source, resolver: Resolver) => FileEdges;
@@ -0,0 +1,135 @@
1
+ import { SyntaxKind } from 'typescript/ast';
2
+ import { isExportAssignment, isExportDeclaration, isIdentifier, isImportDeclaration, isNamedExports, isNamedImports, isNamespaceImport, isStringLiteralLikeNode, } from 'typescript/ast/is';
3
+ import { SymbolFlags } from 'typescript/sync';
4
+ import { isBuiltin } from 'node:module';
5
+ export const fileEdges = (source, resolver) => {
6
+ const exported = locallyExportedNames(source.sourceFile);
7
+ const edges = { imports: [], externals: [] };
8
+ for (const statement of source.sourceFile.statements) {
9
+ const declaration = moduleDeclaration(statement, exported);
10
+ if (!declaration)
11
+ continue;
12
+ const resolved = resolver.program.getResolvedModuleFromModuleSpecifier(declaration.specifier, source.sourceFile.fileName);
13
+ const via = resolved?.resolvedFileName ? resolver.relative(resolved.resolvedFileName) : undefined;
14
+ if (via)
15
+ edges.imports.push(...statementEdges(statement, declaration, via, source, resolver));
16
+ else if (isBare(declaration.specifier.text))
17
+ edges.externals.push(externalImport(statement, declaration, source));
18
+ }
19
+ return edges;
20
+ };
21
+ const isBare = (specifier) => !specifier.startsWith('.') && !specifier.startsWith('/');
22
+ const packageOf = (specifier) => {
23
+ const segments = specifier.split('/');
24
+ if (specifier.startsWith('@'))
25
+ return segments.slice(0, 2).join('/');
26
+ const [name] = segments;
27
+ return !name.includes(':') && isBuiltin(name) ? `node:${name}` : name;
28
+ };
29
+ const externalImport = (statement, declaration, source) => {
30
+ const reExport = declaration.reExport || declaration.bindings.some((binding) => binding.reExport);
31
+ return {
32
+ from: source.file,
33
+ package: packageOf(declaration.specifier.text),
34
+ specifier: declaration.specifier.text,
35
+ names: declaration.bindings.map((binding) => binding.identifier.text),
36
+ typeOnly: declaration.typeOnly ||
37
+ (declaration.bindings.length > 0 && declaration.bindings.every((binding) => binding.typeOnly)),
38
+ ...(reExport ? { reExport } : {}),
39
+ line: source.line(statement),
40
+ };
41
+ };
42
+ const statementEdges = (statement, declaration, via, source, resolver) => {
43
+ const edge = (to, names, typeOnly, reExport) => ({
44
+ from: source.file,
45
+ to,
46
+ ...(to === via ? {} : { via }),
47
+ specifier: declaration.specifier.text,
48
+ names,
49
+ typeOnly,
50
+ ...(reExport ? { reExport } : {}),
51
+ line: source.line(statement),
52
+ });
53
+ if (declaration.bindings.length === 0)
54
+ return [edge(via, [], declaration.typeOnly, declaration.reExport)];
55
+ const byTarget = new Map();
56
+ for (const binding of declaration.bindings) {
57
+ const target = resolveBinding(binding, source, resolver) ?? { file: via, typeOnly: false };
58
+ const key = `${target.file}\0${binding.reExport}`;
59
+ const entry = byTarget.get(key) ?? { to: target.file, names: [], typeOnly: true, reExport: binding.reExport };
60
+ entry.names.push(binding.identifier.text);
61
+ entry.typeOnly &&= declaration.typeOnly || binding.typeOnly || target.typeOnly;
62
+ byTarget.set(key, entry);
63
+ }
64
+ return [...byTarget.values()].map(({ to, names, typeOnly, reExport }) => edge(to, names, typeOnly, reExport));
65
+ };
66
+ const moduleDeclaration = (statement, exported) => isImportDeclaration(statement)
67
+ ? importStatement(statement, exported)
68
+ : isExportDeclaration(statement)
69
+ ? reExportStatement(statement)
70
+ : undefined;
71
+ const locallyExportedNames = (sourceFile) => {
72
+ const names = new Set();
73
+ for (const statement of sourceFile.statements) {
74
+ if (isExportDeclaration(statement) &&
75
+ !statement.moduleSpecifier &&
76
+ statement.exportClause &&
77
+ isNamedExports(statement.exportClause)) {
78
+ for (const element of statement.exportClause.elements) {
79
+ const local = element.propertyName ?? element.name;
80
+ if (isIdentifier(local))
81
+ names.add(local.text);
82
+ }
83
+ }
84
+ else if (isExportAssignment(statement) && isIdentifier(statement.expression)) {
85
+ names.add(statement.expression.text);
86
+ }
87
+ }
88
+ return names;
89
+ };
90
+ const importStatement = (statement, exported) => {
91
+ if (!isStringLiteralLikeNode(statement.moduleSpecifier))
92
+ return undefined;
93
+ const clause = statement.importClause;
94
+ const named = clause?.namedBindings;
95
+ const binding = (identifier, typeOnly) => ({
96
+ identifier,
97
+ typeOnly,
98
+ reExport: exported.has(identifier.text),
99
+ });
100
+ const bindings = [
101
+ ...(clause?.name ? [binding(clause.name, false)] : []),
102
+ ...(named && isNamespaceImport(named) ? [binding(named.name, false)] : []),
103
+ ...(named && isNamedImports(named)
104
+ ? named.elements.map((element) => binding(element.name, element.isTypeOnly))
105
+ : []),
106
+ ];
107
+ return {
108
+ specifier: statement.moduleSpecifier,
109
+ typeOnly: clause?.phaseModifier === SyntaxKind.TypeKeyword,
110
+ reExport: false,
111
+ bindings,
112
+ };
113
+ };
114
+ const reExportStatement = (statement) => {
115
+ if (!statement.moduleSpecifier || !isStringLiteralLikeNode(statement.moduleSpecifier))
116
+ return undefined;
117
+ const clause = statement.exportClause;
118
+ const elements = clause && isNamedExports(clause) ? clause.elements : [];
119
+ const bindings = elements.flatMap((element) => isIdentifier(element.name) ? [{ identifier: element.name, typeOnly: element.isTypeOnly, reExport: true }] : []);
120
+ return { specifier: statement.moduleSpecifier, typeOnly: statement.isTypeOnly, reExport: true, bindings };
121
+ };
122
+ const resolveBinding = (binding, source, resolver) => {
123
+ const symbol = source.symbolOf(binding.identifier);
124
+ if (!symbol || !(symbol.flags & SymbolFlags.Alias))
125
+ return undefined;
126
+ const target = resolver.checker.getAliasedSymbol(symbol);
127
+ if (resolver.checker.isUnknownSymbol(target))
128
+ return undefined;
129
+ const file = target.declarations
130
+ .map((declaration) => resolver.relative(declaration.path))
131
+ .find((path) => path !== undefined);
132
+ if (!file)
133
+ return undefined;
134
+ return { file, typeOnly: (target.flags & SymbolFlags.Value) === 0 };
135
+ };
@@ -0,0 +1,4 @@
1
+ import type { FunctionFacts, MemberGraph } from '../model/facts.ts';
2
+ import { type Source } from './source.ts';
3
+ export declare const fileMembers: (source: Source) => MemberGraph;
4
+ export declare const functionFacts: (source: Source) => FunctionFacts[];
@@ -0,0 +1,190 @@
1
+ import { isArrowFunction, isBindingElement, isBlock, isCallExpression, isClassDeclaration, isClassLikeDeclaration, isConstructorDeclaration, isEnumDeclaration, isExportDeclaration, isFunctionDeclaration, isFunctionExpression, isFunctionLikeDeclaration, isIdentifier, isImportDeclaration, isImportEqualsDeclaration, isInterfaceDeclaration, isModuleDeclaration, isParameterDeclaration, isPropertyAccessExpression, isPropertyAssignment, isPropertyDeclaration, isStringLiteralLikeNode, isThisExpression, isTypeAliasDeclaration, isVariableDeclaration, isVariableStatement, } from 'typescript/ast/is';
2
+ import { cognitiveComplexity } from './complexity.js';
3
+ import { symbolKey, walk } from './source.js';
4
+ export const fileMembers = (source) => {
5
+ const declared = source.sourceFile.statements.flatMap((statement) => declarations(statement, source));
6
+ const loose = source.sourceFile.statements.filter((statement) => isLooseCode(statement));
7
+ if (loose.length > 0) {
8
+ declared.push({
9
+ member: {
10
+ name: '<top-level code>',
11
+ kind: 'code',
12
+ line: source.line(loose[0]),
13
+ endLine: source.endLine(loose[loose.length - 1]),
14
+ },
15
+ node: source.sourceFile,
16
+ keys: [],
17
+ });
18
+ }
19
+ const owner = new Map();
20
+ declared.forEach((entry, index) => {
21
+ for (const key of entry.keys)
22
+ owner.set(key, index);
23
+ });
24
+ const links = [];
25
+ declared.forEach((entry, index) => {
26
+ const nodes = entry.member.kind === 'code' ? loose : [entry.node];
27
+ for (const node of nodes) {
28
+ for (const key of references(node, source)) {
29
+ const other = owner.get(key);
30
+ if (other !== undefined && other !== index)
31
+ links.push([index, other]);
32
+ }
33
+ }
34
+ });
35
+ return { members: declared.map((entry) => entry.member), links };
36
+ };
37
+ const declarations = (statement, source) => {
38
+ const member = (name, kind, node, nameNode) => ({
39
+ member: { name, kind, line: source.line(node), endLine: source.endLine(node) },
40
+ node,
41
+ keys: nameNode ? declaredKeys(nameNode, source) : [],
42
+ });
43
+ if (isFunctionDeclaration(statement))
44
+ return [member(statement.name?.text ?? 'default', 'function', statement, statement.name)];
45
+ if (isClassDeclaration(statement))
46
+ return [member(statement.name?.text ?? 'default', 'class', statement, statement.name)];
47
+ if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement) || isEnumDeclaration(statement)) {
48
+ return [member(statement.name.text, 'type', statement, statement.name)];
49
+ }
50
+ if (isModuleDeclaration(statement))
51
+ return [member(statement.name.getText(source.sourceFile), 'type', statement, statement.name)];
52
+ if (isVariableStatement(statement)) {
53
+ return statement.declarationList.declarations.map((declaration) => {
54
+ const fn = declaration.initializer &&
55
+ (isArrowFunction(declaration.initializer) || isFunctionExpression(declaration.initializer));
56
+ return member(declaration.name.getText(source.sourceFile), fn ? 'function' : 'state', declaration, declaration.name);
57
+ });
58
+ }
59
+ return [];
60
+ };
61
+ const isLooseCode = (statement) => !isImportDeclaration(statement) &&
62
+ !isImportEqualsDeclaration(statement) &&
63
+ !isExportDeclaration(statement) &&
64
+ !isFunctionDeclaration(statement) &&
65
+ !isClassDeclaration(statement) &&
66
+ !isInterfaceDeclaration(statement) &&
67
+ !isTypeAliasDeclaration(statement) &&
68
+ !isEnumDeclaration(statement) &&
69
+ !isModuleDeclaration(statement) &&
70
+ !isVariableStatement(statement);
71
+ const declaredKeys = (name, source) => {
72
+ const keys = [];
73
+ walk(name, (node) => {
74
+ if (isIdentifier(node)) {
75
+ const key = symbolKey(source.symbolOf(node));
76
+ if (key)
77
+ keys.push(key);
78
+ }
79
+ });
80
+ return keys;
81
+ };
82
+ const references = (node, source) => {
83
+ const keys = new Set();
84
+ walk(node, (child) => {
85
+ if (isIdentifier(child)) {
86
+ const key = symbolKey(source.symbolOf(child));
87
+ if (key)
88
+ keys.add(key);
89
+ }
90
+ if (isPropertyAccessExpression(child) && isThisExpression(child.expression) && isIdentifier(child.name)) {
91
+ keys.add(`this.${child.name.text}`);
92
+ }
93
+ });
94
+ return keys;
95
+ };
96
+ export const functionFacts = (source) => {
97
+ const facts = [];
98
+ const visit = (node, outermost) => {
99
+ if (isFunctionLikeDeclaration(node) && node.body) {
100
+ const name = functionName(node, source);
101
+ const line = source.line(node);
102
+ const endLine = source.endLine(node);
103
+ facts.push({
104
+ name,
105
+ line,
106
+ endLine,
107
+ lines: endLine - line + 1,
108
+ statements: isBlock(node.body)
109
+ ? statementGraph(node, node.body.statements, source)
110
+ : { members: [], links: [] },
111
+ ...(outermost ? { complexity: cognitiveComplexity(node, selfKey(node, source), source) } : {}),
112
+ });
113
+ node.forEachChild((child) => {
114
+ visit(child, false);
115
+ });
116
+ return;
117
+ }
118
+ node.forEachChild((child) => {
119
+ visit(child, outermost);
120
+ });
121
+ };
122
+ visit(source.sourceFile, true);
123
+ return facts;
124
+ };
125
+ const statementGraph = (fn, statements, source) => {
126
+ const locals = localKeys(fn, source);
127
+ const members = [];
128
+ const firstUser = new Map();
129
+ const links = [];
130
+ for (const statement of statements) {
131
+ const touched = [...references(statement, source)].filter((key) => locals.has(key) || key.startsWith('this.'));
132
+ if (touched.length === 0)
133
+ continue;
134
+ const line = source.line(statement);
135
+ const index = members.push({ name: `line ${line}`, kind: 'code', line, endLine: source.endLine(statement) }) - 1;
136
+ for (const key of touched) {
137
+ const first = firstUser.get(key);
138
+ if (first === undefined)
139
+ firstUser.set(key, index);
140
+ else
141
+ links.push([first, index]);
142
+ }
143
+ }
144
+ return { members, links };
145
+ };
146
+ const localKeys = (fn, source) => {
147
+ const keys = new Set();
148
+ walk(fn, (node) => {
149
+ const name = node !== fn ? declaredName(node) : undefined;
150
+ const key = name && symbolKey(source.symbolOf(name));
151
+ if (key)
152
+ keys.add(key);
153
+ });
154
+ return keys;
155
+ };
156
+ const declaredName = (node) => {
157
+ const named = isVariableDeclaration(node) ||
158
+ isParameterDeclaration(node) ||
159
+ isBindingElement(node) ||
160
+ isFunctionDeclaration(node) ||
161
+ isClassDeclaration(node);
162
+ return named && node.name && isIdentifier(node.name) ? node.name : undefined;
163
+ };
164
+ const functionName = (node, source) => {
165
+ const own = 'name' in node && node.name ? node.name.getText(source.sourceFile) : undefined;
166
+ const parent = node.parent;
167
+ const owner = isClassLikeDeclaration(parent) ? `${parent.name?.text ?? '<class>'}.` : '';
168
+ if (isConstructorDeclaration(node))
169
+ return `${owner}constructor`;
170
+ if (own)
171
+ return `${owner}${own}`;
172
+ if (isVariableDeclaration(parent) || isPropertyAssignment(parent) || isPropertyDeclaration(parent)) {
173
+ return parent.name.getText(source.sourceFile);
174
+ }
175
+ if (isCallExpression(parent)) {
176
+ const [first] = parent.arguments;
177
+ const label = first && isStringLiteralLikeNode(first) ? `(${JSON.stringify(first.text)})` : '';
178
+ return `<callback to ${parent.expression.getText(source.sourceFile)}${label}>`;
179
+ }
180
+ return isFunctionDeclaration(node) ? 'default' : '<anonymous>';
181
+ };
182
+ const selfKey = (node, source) => {
183
+ const parent = node.parent;
184
+ const name = 'name' in node && node.name
185
+ ? node.name
186
+ : isVariableDeclaration(parent) || isPropertyAssignment(parent) || isPropertyDeclaration(parent)
187
+ ? parent.name
188
+ : undefined;
189
+ return name && isIdentifier(name) ? symbolKey(source.symbolOf(name)) : undefined;
190
+ };
@@ -0,0 +1,13 @@
1
+ import type { Identifier, Node, SourceFile } from 'typescript/ast';
2
+ import type { Checker, Symbol } from 'typescript/sync';
3
+ export interface Source {
4
+ file: string;
5
+ sourceFile: SourceFile;
6
+ symbolOf: (identifier: Identifier) => Symbol | undefined;
7
+ line: (node: Node) => number;
8
+ endLine: (node: Node) => number;
9
+ }
10
+ export declare const readSource: (checker: Checker, sourceFile: SourceFile, file: string) => Source;
11
+ export declare const symbolKey: (symbol: Symbol | undefined) => string | undefined;
12
+ export declare const walk: (node: Node, visit: (node: Node) => boolean | void) => void;
13
+ export declare const countLines: (text: string) => number;
@@ -0,0 +1,29 @@
1
+ import { isIdentifier } from 'typescript/ast/is';
2
+ export const readSource = (checker, sourceFile, file) => {
3
+ const identifiers = [];
4
+ walk(sourceFile, (node) => {
5
+ if (isIdentifier(node))
6
+ identifiers.push(node);
7
+ });
8
+ const symbols = identifiers.length > 0 ? checker.getSymbolAtLocation(identifiers) : [];
9
+ const byNode = new Map(identifiers.map((identifier, index) => [identifier, symbols[index]]));
10
+ return {
11
+ file,
12
+ sourceFile,
13
+ symbolOf: (identifier) => byNode.get(identifier),
14
+ line: (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
15
+ endLine: (node) => sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1,
16
+ };
17
+ };
18
+ export const symbolKey = (symbol) => {
19
+ const declaration = symbol?.declarations[0];
20
+ return declaration ? `${declaration.path}#${declaration.index}` : undefined;
21
+ };
22
+ export const walk = (node, visit) => {
23
+ if (visit(node) === false)
24
+ return;
25
+ node.forEachChild((child) => {
26
+ walk(child, visit);
27
+ });
28
+ };
29
+ export const countLines = (text) => text.replace(/\n$/, '').split('\n').length;
@@ -0,0 +1,2 @@
1
+ import type { SourceFile } from 'typescript/ast';
2
+ export declare const moduleSpecifiers: (sourceFile: SourceFile) => string[];
@@ -0,0 +1,6 @@
1
+ import { isExportDeclaration, isImportDeclaration, isStringLiteralLikeNode } from 'typescript/ast/is';
2
+ export const moduleSpecifiers = (sourceFile) => sourceFile.statements.flatMap((statement) => (isImportDeclaration(statement) || isExportDeclaration(statement)) &&
3
+ statement.moduleSpecifier &&
4
+ isStringLiteralLikeNode(statement.moduleSpecifier)
5
+ ? [statement.moduleSpecifier.text]
6
+ : []);
@@ -0,0 +1,2 @@
1
+ import type { Analyzer } from '../app/ports.ts';
2
+ export declare const typescriptAnalyzer: Analyzer;