@angular-modernizer/adapter-mcp 1.2.0 → 2.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.
Files changed (130) hide show
  1. package/CHANGELOG.md +662 -0
  2. package/README.md +84 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +9 -0
  6. package/dist/index.js +1 -0
  7. package/dist/scan-host/scan-host.d.ts +7 -0
  8. package/dist/scan-host/scan-host.js +73 -10
  9. package/dist/scan-host/scan-protocol.d.ts +2 -0
  10. package/dist/scan-host/scan-worker.js +14 -8
  11. package/dist/server/limited-stdio-transport.d.ts +6 -3
  12. package/dist/server/limited-stdio-transport.js +26 -9
  13. package/dist/server/mcp-server.js +1 -1
  14. package/dist/server/sdk-server.d.ts +14 -3
  15. package/dist/server/sdk-server.js +54 -6
  16. package/dist/server/tool-registry.d.ts +3 -1
  17. package/dist/server/tool-registry.js +8 -3
  18. package/dist/streaming/progress-store.d.ts +19 -7
  19. package/dist/streaming/progress-store.js +19 -8
  20. package/dist/tools/analyze-build-impact.d.ts +7 -4
  21. package/dist/tools/analyze-build-impact.js +8 -3
  22. package/dist/tools/analyze-core-to-shared.d.ts +10 -6
  23. package/dist/tools/analyze-core-to-shared.js +63 -60
  24. package/dist/tools/analyze-parser-performance.d.ts +57 -13
  25. package/dist/tools/analyze-parser-performance.js +67 -6
  26. package/dist/tools/analyze-project.d.ts +30 -4
  27. package/dist/tools/analyze-project.js +99 -15
  28. package/dist/tools/check-incremental-compatibility.d.ts +30 -41
  29. package/dist/tools/check-incremental-compatibility.js +32 -264
  30. package/dist/tools/collect-feedback.js +15 -2
  31. package/dist/tools/extract-libraries.js +42 -27
  32. package/dist/tools/find-angular-symbol.js +3 -2
  33. package/dist/tools/find-component-hosts.js +3 -2
  34. package/dist/tools/find-usages.js +21 -12
  35. package/dist/tools/get-call-graph.js +15 -2
  36. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  37. package/dist/tools/get-operation-progress-tool.js +2 -2
  38. package/dist/tools/get-operation-progress.d.ts +4 -1
  39. package/dist/tools/get-operation-progress.js +6 -2
  40. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  41. package/dist/tools/helpers/analysis-output.js +22 -1
  42. package/dist/tools/helpers/build-cache.d.ts +27 -0
  43. package/dist/tools/helpers/build-cache.js +86 -0
  44. package/dist/tools/helpers/class-filter.d.ts +18 -0
  45. package/dist/tools/helpers/class-filter.js +30 -0
  46. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  47. package/dist/tools/helpers/cli-arguments.js +35 -0
  48. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  49. package/dist/tools/helpers/feedback-catalog.js +196 -0
  50. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  51. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  52. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  53. package/dist/tools/helpers/file-type-check.js +56 -0
  54. package/dist/tools/helpers/output-contract.d.ts +42 -0
  55. package/dist/tools/helpers/output-contract.js +54 -0
  56. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  57. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  58. package/dist/tools/helpers/project-cache.d.ts +5 -4
  59. package/dist/tools/helpers/project-cache.js +21 -16
  60. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  61. package/dist/tools/helpers/project-decorators.js +13 -6
  62. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  63. package/dist/tools/helpers/refresh-apply.js +460 -0
  64. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  65. package/dist/tools/helpers/refresh-inventory.js +610 -0
  66. package/dist/tools/helpers/rule-runner.js +3 -1
  67. package/dist/tools/helpers/scan-cache.d.ts +74 -5
  68. package/dist/tools/helpers/scan-cache.js +134 -6
  69. package/dist/tools/helpers/scan-engine.d.ts +30 -6
  70. package/dist/tools/helpers/scan-engine.js +131 -22
  71. package/dist/tools/helpers/scan-plan.js +16 -2
  72. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  73. package/dist/tools/helpers/source-map-loader.js +226 -0
  74. package/dist/tools/helpers/template-check.d.ts +76 -0
  75. package/dist/tools/helpers/template-check.js +158 -0
  76. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  77. package/dist/tools/helpers/tool-cache.js +9 -3
  78. package/dist/tools/helpers/tool-context.d.ts +18 -0
  79. package/dist/tools/helpers/tool-context.js +29 -0
  80. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  81. package/dist/tools/helpers/transform-safety.js +357 -4
  82. package/dist/tools/inspect-form-group.js +5 -0
  83. package/dist/tools/inspect-i18n.d.ts +1 -1
  84. package/dist/tools/inspect-template.js +8 -2
  85. package/dist/tools/learn-patterns.d.ts +43 -28
  86. package/dist/tools/learn-patterns.js +83 -161
  87. package/dist/tools/list-imports.d.ts +1 -1
  88. package/dist/tools/orchestrate-migration.d.ts +19 -1
  89. package/dist/tools/orchestrate-migration.js +52 -10
  90. package/dist/tools/parse-stack-trace.d.ts +48 -1
  91. package/dist/tools/parse-stack-trace.js +108 -9
  92. package/dist/tools/plan-migration.js +22 -10
  93. package/dist/tools/refresh-state.d.ts +378 -0
  94. package/dist/tools/refresh-state.js +370 -0
  95. package/dist/tools/resolve-type.js +10 -3
  96. package/dist/tools/review-feedback.d.ts +42 -7
  97. package/dist/tools/review-feedback.js +24 -17
  98. package/dist/tools/rollback-changes.d.ts +5 -0
  99. package/dist/tools/rollback-changes.js +7 -2
  100. package/dist/tools/run-angular-cli.js +36 -22
  101. package/dist/tools/run-build.d.ts +33 -28
  102. package/dist/tools/run-build.js +136 -438
  103. package/dist/tools/run-schematic.d.ts +8 -2
  104. package/dist/tools/run-schematic.js +80 -50
  105. package/dist/tools/scan-all.d.ts +31 -15
  106. package/dist/tools/scan-all.js +75 -109
  107. package/dist/tools/scan-angular.d.ts +27 -14
  108. package/dist/tools/scan-angular.js +70 -92
  109. package/dist/tools/scan-architecture.d.ts +29 -12
  110. package/dist/tools/scan-architecture.js +205 -135
  111. package/dist/tools/scan-solid.d.ts +27 -14
  112. package/dist/tools/scan-solid.js +73 -89
  113. package/dist/tools/search-codebase.d.ts +6 -1
  114. package/dist/tools/search-codebase.js +13 -7
  115. package/dist/tools/suggest-improvements.d.ts +34 -3
  116. package/dist/tools/suggest-improvements.js +34 -9
  117. package/dist/tools/trace-output-flow.js +3 -2
  118. package/dist/tools/transform-code-batch.d.ts +9 -9
  119. package/dist/tools/transform-code.d.ts +161 -12
  120. package/dist/tools/transform-code.js +715 -206
  121. package/dist/tools/validate-before-transform.js +2 -1
  122. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  123. package/dist/tools/validate-project-compatibility.js +33 -225
  124. package/dist/tools/validate-transformation.d.ts +40 -26
  125. package/dist/tools/validate-transformation.js +115 -294
  126. package/dist/tools/verify-citations.js +8 -2
  127. package/dist/types.d.ts +9 -9
  128. package/dist/utils/format-tool-response.d.ts +3 -1
  129. package/dist/utils/format-tool-response.js +8 -3
  130. package/package.json +14 -13
@@ -1,11 +1,68 @@
1
1
  /**
2
- * @angular-modernizer/adapter-mcp - scan-all cache entries
2
+ * @angular-modernizer/adapter-mcp - scan cache entries
3
3
  *
4
- * scan-all caches the findings of each analyzed `.ts` file under that file,
5
- * including findings reported on its template (`.html`) and files without any
6
- * finding. Template files are stored as dependencies so an edit to the
7
- * template alone invalidates the entry.
4
+ * scan-all, scan-angular and scan-solid cache the findings of each analyzed
5
+ * `.ts` file under that file, including findings reported on its template
6
+ * (`.html`) and files without any finding. Template files are stored as
7
+ * dependencies so an edit to the template alone invalidates the entry.
8
8
  */
9
+ import { type CacheManager } from '@angular-modernizer/core';
10
+ /**
11
+ * Cache version of scan-angular and scan-solid. Their entries before this
12
+ * layout were filed under each finding's file (the template's `.html` for
13
+ * template rules, never read back) and missing for files without findings;
14
+ * `scan-3` also drops entries whose cross-file findings saw only their batch,
15
+ * `scan-4` entries that hold project rule findings of another file.
16
+ */
17
+ export declare const SCAN_TOOL_CACHE_VERSION = "scan-4";
18
+ /**
19
+ * Cache version for a scan of `rootPath`: the layout version plus a hash of
20
+ * the configuration the rules read. Rule options, `parser`, `layers` and the
21
+ * `layersSource` module change findings of unchanged files, so a change makes
22
+ * every entry stale. The `tools` sections only steer the scan call (patterns,
23
+ * page) and stay out of the hash. A scan limited to `ruleIds` runs only those
24
+ * rules, so its entries hold only their findings and get a version of their
25
+ * own; a scan of all rules keeps the version without a selection. The same
26
+ * holds for the scope: rules with `scope: 'project'` see only the files of
27
+ * the scan, so a scan with its own `includePatterns` or `excludePatterns`
28
+ * gets a version of its own (pattern order does not count) and a scan with
29
+ * the default patterns keeps the version without a scope. Entries are kept
30
+ * per file, so a scan with another version replaces the entries of the files
31
+ * it analyzed, and the next scan with the first version analyzes them again.
32
+ *
33
+ * @throws the loader's error for an invalid `.angular-modernizer.json`
34
+ */
35
+ export declare function scanCacheVersion(layout: string, rootPath: string, ruleIds?: readonly string[], scope?: ScanCacheScope): string;
36
+ /**
37
+ * Glob patterns of a scan as the call and the `tools` section gave them;
38
+ * unset means the tool's default patterns.
39
+ */
40
+ export interface ScanCacheScope {
41
+ /** Include patterns of the scan, unset for the default. */
42
+ readonly includePatterns?: readonly string[];
43
+ /** Exclude patterns of the scan, unset for the default. */
44
+ readonly excludePatterns?: readonly string[];
45
+ }
46
+ /**
47
+ * How a scan uses its cache: `use` serves unchanged files from it, `refresh`
48
+ * ignores the existing entries, analyzes every file and overwrites them.
49
+ */
50
+ export type ScanCacheMode = 'use' | 'refresh';
51
+ /**
52
+ * JSON Schema of the `cache` argument of scan-all, scan-solid, scan-angular
53
+ * and scan-architecture.
54
+ */
55
+ export declare const SCAN_CACHE_MODE_SCHEMA: {
56
+ readonly type: "string";
57
+ readonly enum: readonly ["use", "refresh"];
58
+ readonly default: "use";
59
+ readonly description: "use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Read from the call only, never from the tools section of .angular-modernizer.json";
60
+ };
61
+ /**
62
+ * Cache mode of a call. Only the call's own arguments count: a `refresh`
63
+ * kept in a config section would make every scan cold.
64
+ */
65
+ export declare function scanCacheMode(callArgs: Record<string, unknown>): ScanCacheMode;
9
66
  /**
10
67
  * Template files a cache entry depends on: `templateUrl` targets in the
11
68
  * source text and every other file a finding of this source points at.
@@ -19,4 +76,16 @@ export declare function templateDependencies(sourcePath: string, sourceText: str
19
76
  * was modified after the entry was written.
20
77
  */
21
78
  export declare function dependenciesUnchanged(dependencies: readonly string[], cachedAt: number, modifiedAt: (path: string) => number | undefined): boolean;
79
+ /**
80
+ * Cached findings of one analyzed file, or `null` when it must be analyzed.
81
+ * An entry is a hit even without findings, but stale once one of its
82
+ * template dependencies changed after it was written.
83
+ */
84
+ export declare function readCachedFindings(filePath: string, cache: CacheManager): Promise<unknown[] | null>;
85
+ /**
86
+ * Findings of all files in file path order, each file's findings in the order
87
+ * they were reported. Cache hits and newly analyzed files then give the same
88
+ * order, ids and pages as a cold run, whichever part came from the cache.
89
+ */
90
+ export declare function findingsInFileOrder<T>(findingsByFile: ReadonlyMap<string, readonly T[]>): T[];
22
91
  //# sourceMappingURL=scan-cache.d.ts.map
@@ -1,12 +1,108 @@
1
1
  /**
2
- * @angular-modernizer/adapter-mcp - scan-all cache entries
2
+ * @angular-modernizer/adapter-mcp - scan cache entries
3
3
  *
4
- * scan-all caches the findings of each analyzed `.ts` file under that file,
5
- * including findings reported on its template (`.html`) and files without any
6
- * finding. Template files are stored as dependencies so an edit to the
7
- * template alone invalidates the entry.
4
+ * scan-all, scan-angular and scan-solid cache the findings of each analyzed
5
+ * `.ts` file under that file, including findings reported on its template
6
+ * (`.html`) and files without any finding. Template files are stored as
7
+ * dependencies so an edit to the template alone invalidates the entry.
8
8
  */
9
- import { dirname, resolve } from 'node:path';
9
+ import { createHash } from 'node:crypto';
10
+ import { readFileSync, statSync } from 'node:fs';
11
+ import { dirname, isAbsolute, resolve } from 'node:path';
12
+ import { loadConfig } from '@angular-modernizer/core';
13
+ /**
14
+ * Cache version of scan-angular and scan-solid. Their entries before this
15
+ * layout were filed under each finding's file (the template's `.html` for
16
+ * template rules, never read back) and missing for files without findings;
17
+ * `scan-3` also drops entries whose cross-file findings saw only their batch,
18
+ * `scan-4` entries that hold project rule findings of another file.
19
+ */
20
+ export const SCAN_TOOL_CACHE_VERSION = 'scan-4';
21
+ /**
22
+ * Cache version for a scan of `rootPath`: the layout version plus a hash of
23
+ * the configuration the rules read. Rule options, `parser`, `layers` and the
24
+ * `layersSource` module change findings of unchanged files, so a change makes
25
+ * every entry stale. The `tools` sections only steer the scan call (patterns,
26
+ * page) and stay out of the hash. A scan limited to `ruleIds` runs only those
27
+ * rules, so its entries hold only their findings and get a version of their
28
+ * own; a scan of all rules keeps the version without a selection. The same
29
+ * holds for the scope: rules with `scope: 'project'` see only the files of
30
+ * the scan, so a scan with its own `includePatterns` or `excludePatterns`
31
+ * gets a version of its own (pattern order does not count) and a scan with
32
+ * the default patterns keeps the version without a scope. Entries are kept
33
+ * per file, so a scan with another version replaces the entries of the files
34
+ * it analyzed, and the next scan with the first version analyzes them again.
35
+ *
36
+ * @throws the loader's error for an invalid `.angular-modernizer.json`
37
+ */
38
+ export function scanCacheVersion(layout, rootPath, ruleIds, scope = {}) {
39
+ const { tools: _tools, $schema: _schema, ...ruleConfig } = loadConfig(rootPath);
40
+ const hash = createHash('sha256').update(stableJson(ruleConfig));
41
+ if (ruleIds !== undefined && ruleIds.length > 0) {
42
+ hash.update(`rules:${[...new Set(ruleIds)].sort().join(',')}`);
43
+ }
44
+ for (const [name, patterns] of [
45
+ ['include', scope.includePatterns],
46
+ ['exclude', scope.excludePatterns],
47
+ ]) {
48
+ if (patterns !== undefined) {
49
+ hash.update(`${name}:${stableJson([...new Set(patterns)].sort())}`);
50
+ }
51
+ }
52
+ const layersSourcePath = layersSourceFile(ruleConfig['layersSource'], rootPath);
53
+ if (layersSourcePath !== undefined) {
54
+ hash.update(readOrEmpty(layersSourcePath));
55
+ }
56
+ return `${layout}+${hash.digest('hex').slice(0, 16)}`;
57
+ }
58
+ function layersSourceFile(layersSource, rootPath) {
59
+ if (typeof layersSource !== 'object' || layersSource === null) {
60
+ return undefined;
61
+ }
62
+ const path = layersSource.path;
63
+ if (typeof path !== 'string') {
64
+ return undefined;
65
+ }
66
+ return isAbsolute(path) ? path : resolve(rootPath, path);
67
+ }
68
+ function readOrEmpty(path) {
69
+ try {
70
+ return readFileSync(path, 'utf8');
71
+ }
72
+ catch {
73
+ return '';
74
+ }
75
+ }
76
+ /** JSON with object keys sorted, so the same config always hashes the same. */
77
+ function stableJson(value) {
78
+ if (Array.isArray(value)) {
79
+ return `[${value.map(stableJson).join(',')}]`;
80
+ }
81
+ if (typeof value === 'object' && value !== null) {
82
+ const entries = Object.entries(value)
83
+ .filter(([, v]) => v !== undefined)
84
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
85
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(',')}}`;
86
+ }
87
+ return JSON.stringify(value) ?? 'null';
88
+ }
89
+ /**
90
+ * JSON Schema of the `cache` argument of scan-all, scan-solid, scan-angular
91
+ * and scan-architecture.
92
+ */
93
+ export const SCAN_CACHE_MODE_SCHEMA = {
94
+ type: 'string',
95
+ enum: ['use', 'refresh'],
96
+ default: 'use',
97
+ description: 'use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Read from the call only, never from the tools section of .angular-modernizer.json',
98
+ };
99
+ /**
100
+ * Cache mode of a call. Only the call's own arguments count: a `refresh`
101
+ * kept in a config section would make every scan cold.
102
+ */
103
+ export function scanCacheMode(callArgs) {
104
+ return callArgs['cache'] === 'refresh' ? 'refresh' : 'use';
105
+ }
10
106
  const TEMPLATE_URL = /templateUrl\s*:\s*['"`]([^'"`]+)['"`]/g;
11
107
  /**
12
108
  * Template files a cache entry depends on: `templateUrl` targets in the
@@ -31,4 +127,36 @@ export function dependenciesUnchanged(dependencies, cachedAt, modifiedAt) {
31
127
  return mtime !== undefined && mtime <= cachedAt;
32
128
  });
33
129
  }
130
+ /**
131
+ * Cached findings of one analyzed file, or `null` when it must be analyzed.
132
+ * An entry is a hit even without findings, but stale once one of its
133
+ * template dependencies changed after it was written.
134
+ */
135
+ export async function readCachedFindings(filePath, cache) {
136
+ const entry = await cache.getAnalysisResult(filePath);
137
+ if (entry === null) {
138
+ return null;
139
+ }
140
+ return dependenciesUnchanged(entry.dependencies, entry.metadata.cachedAt, modifiedAt)
141
+ ? entry.results
142
+ : null;
143
+ }
144
+ function modifiedAt(path) {
145
+ try {
146
+ return statSync(path).mtimeMs;
147
+ }
148
+ catch {
149
+ return undefined;
150
+ }
151
+ }
152
+ /**
153
+ * Findings of all files in file path order, each file's findings in the order
154
+ * they were reported. Cache hits and newly analyzed files then give the same
155
+ * order, ids and pages as a cold run, whichever part came from the cache.
156
+ */
157
+ export function findingsInFileOrder(findingsByFile) {
158
+ return [...findingsByFile.keys()]
159
+ .sort()
160
+ .flatMap((filePath) => findingsByFile.get(filePath) ?? []);
161
+ }
34
162
  //# sourceMappingURL=scan-cache.js.map
@@ -11,6 +11,7 @@
11
11
  * The engine does not write to disk (the kernel gets no cache config), so a
12
12
  * worker killed in the middle leaves nothing half written.
13
13
  */
14
+ import { type ConfigWarning, type UnreadableSourceFile } from '@angular-modernizer/core';
14
15
  import { type RuleRunResult, type RuleRunnerViolation } from './rule-runner.js';
15
16
  /** Plugins a scan runs. */
16
17
  export type ScanPluginSet = 'all' | 'solid' | 'angular' | 'architecture' | 'analyzer';
@@ -28,25 +29,37 @@ export interface ScanSpec {
28
29
  /** Files to analyze, absolute, in analysis order. */
29
30
  files: string[];
30
31
  /**
31
- * - `batches`: per batch remove all files, add the batch, analyze it
32
- * (scan-all, scan-solid, scan-angular).
32
+ * - `batches`: rules with `scope: 'project'` over `contextFiles` and
33
+ * `files` in one project, then the other rules batch by batch, each batch
34
+ * replacing the project's files (scan-all, scan-solid, scan-angular).
33
35
  * - `runner`: add all files, then run the rules with the time budget
34
36
  * (scan-architecture).
35
37
  * - `sequential`: project from the tsconfig, files added one by one
36
38
  * (analyze-project).
37
39
  */
38
40
  mode: 'batches' | 'runner' | 'sequential';
39
- /** Batch size of `batches`. */
41
+ /**
42
+ * Batch size of `batches`: files the project holds at once for the rules
43
+ * with file scope. It bounds the memory and does not change the findings.
44
+ */
40
45
  batchSize?: number;
41
46
  /**
42
- * `batches`: analyze every file the project holds after the load
43
- * (scan-solid, scan-angular) instead of the loaded ones (scan-all).
47
+ * `batches`: files the project pass holds besides `files`, not analyzed
48
+ * (the scan's files served from its cache). Rules with `scope: 'project'`
49
+ * then see the same project whether a file is analyzed cold or alone in a
50
+ * warm run.
44
51
  */
45
- analyzeProjectFiles?: boolean;
52
+ contextFiles?: string[];
46
53
  /** Record the template dependencies of each analyzed file (scan-all cache). */
47
54
  templateDependencies?: boolean;
48
55
  /** `runner`: run only these rules; none left is an error. */
49
56
  ruleIds?: string[];
57
+ /**
58
+ * Run only the rules of this `AnalysisRule.scope` (`'file'` includes rules
59
+ * without a scope). When the filter leaves no rule, the scan runs nothing
60
+ * and reports no error.
61
+ */
62
+ ruleScope?: 'file' | 'project';
50
63
  /** `runner`: time budget in ms, `0` disables it. */
51
64
  maxDurationMs?: number;
52
65
  /** `runner`: start of the budget (epoch ms). */
@@ -94,6 +107,17 @@ export interface ScanEngineResult {
94
107
  ruleIds: string[];
95
108
  /** `runner` mode only. */
96
109
  run?: ScanRunSummary;
110
+ /**
111
+ * `sequential` mode only: program files and files to analyze that could
112
+ * not be read; they are left out of the project and not analyzed.
113
+ */
114
+ unreadableFiles?: UnreadableSourceFile[];
115
+ /**
116
+ * Config warnings of a worker run (the worker's own scope); the host
117
+ * reports them into the caller's scope. Unset in-process, where the
118
+ * plugins report into the caller's scope directly.
119
+ */
120
+ configWarnings?: ConfigWarning[];
97
121
  }
98
122
  /** Cancellation of an in-thread run; a worker is terminated instead. */
99
123
  export interface ScanControl {
@@ -12,7 +12,7 @@
12
12
  * worker killed in the middle leaves nothing half written.
13
13
  */
14
14
  import { existsSync } from 'node:fs';
15
- import { Kernel, loadConfig } from '@angular-modernizer/core';
15
+ import { Kernel, applySuppressionComments, loadConfig, } from '@angular-modernizer/core';
16
16
  import { createPublicApi } from '@angular-modernizer/api';
17
17
  import { ContextFactory, } from '@angular-modernizer/plugin-system';
18
18
  import { loadSourceFiles } from './load-source-files.js';
@@ -64,12 +64,33 @@ export async function runScanEngine(spec, sink, control = {}) {
64
64
  const allRules = kernel
65
65
  .getAllPlugins()
66
66
  .flatMap((p) => p.getAnalysisRules());
67
- const rules = spec.ruleIds === undefined
67
+ const requested = spec.ruleIds === undefined
68
68
  ? allRules
69
69
  : allRules.filter((rule) => spec.ruleIds.includes(rule.id));
70
- if (rules.length === 0 && spec.mode === 'runner') {
70
+ if (requested.length === 0 && spec.mode === 'runner') {
71
71
  throw new Error('No matching rules found');
72
72
  }
73
+ const rules = spec.ruleScope === undefined
74
+ ? requested
75
+ : requested.filter((rule) => (rule.scope ?? 'file') === spec.ruleScope);
76
+ if (rules.length === 0 && spec.ruleScope !== undefined) {
77
+ sink.ready?.([]);
78
+ return {
79
+ cancelled: false,
80
+ ruleIds: [],
81
+ ...(spec.mode === 'runner'
82
+ ? {
83
+ run: {
84
+ filesAnalyzed: 0,
85
+ incomplete: false,
86
+ skippedFiles: 0,
87
+ ruleTimings: [],
88
+ durationMs: 0,
89
+ },
90
+ }
91
+ : {}),
92
+ };
93
+ }
73
94
  const ruleIds = rules.map((r) => r.id);
74
95
  sink.ready?.(ruleIds);
75
96
  // Per-rule overrides of .angular-modernizer.json (BUG-3)
@@ -88,6 +109,21 @@ async function runBatches(kernel, rules, config, spec, sink, control, ruleIds) {
88
109
  const batchSize = spec.batchSize ?? 100;
89
110
  const totalBatches = Math.ceil(spec.files.length / batchSize);
90
111
  const project = kernel.getProject();
112
+ const projectRules = rules.filter((rule) => rule.scope === 'project');
113
+ const fileRules = rules.filter((rule) => rule.scope !== 'project');
114
+ // Rules that read other files of the project run first, over the whole
115
+ // scope in one project (path order), so their findings do not depend on the
116
+ // batch size or on which files a warm run analyzes. The other rules run in
117
+ // batches that replace the project's files: with the whole scope loaded,
118
+ // all 52 rules took 2.2 GB of heap on a large app, above the worker limit.
119
+ // The project pass has a project of its own: what the rules keep per
120
+ // project (indexes, wrapped nodes) is dropped with it before the batches.
121
+ const projectFindings = projectRules.length > 0 && spec.files.length > 0
122
+ ? await runProjectPass(projectRules, config, spec, signal)
123
+ : new Map();
124
+ if (projectFindings === 'cancelled') {
125
+ return { cancelled: true, ruleIds };
126
+ }
91
127
  for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
92
128
  const batchFiles = spec.files.slice(batchNum * batchSize, (batchNum + 1) * batchSize);
93
129
  console.info(`\n${spec.tool} batch ${batchNum + 1}/${totalBatches}: ${batchFiles.length} files`);
@@ -102,30 +138,80 @@ async function runBatches(kernel, rules, config, spec, sink, control, ruleIds) {
102
138
  return { cancelled: true, ruleIds };
103
139
  }
104
140
  const api = createPublicApi(project);
105
- const sourceFiles = spec.analyzeProjectFiles === true ? project.getSourceFiles() : loaded.sourceFiles;
106
- for (const sourceFile of sourceFiles) {
141
+ for (const sourceFile of loaded.sourceFiles) {
107
142
  await yieldIfCancellable(signal);
108
143
  if (signal?.aborted === true) {
109
144
  return { cancelled: true, ruleIds };
110
145
  }
111
- const findings = [];
112
- for (const rule of rules) {
113
- try {
114
- const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
115
- for (const result of results) {
116
- findings.push(toFinding(rule, result));
117
- }
118
- }
119
- catch (error) {
120
- console.warn(`Failed to analyze with rule ${rule.id}:`, error);
121
- }
122
- }
146
+ const findings = await analyzeFile(fileRules, sourceFile, project, api, config);
147
+ findings.push(...(projectFindings.get(sourceFile.getFilePath()) ?? []));
123
148
  sink.file(fileEvent(sourceFile, findings, spec));
124
149
  }
125
150
  sink.batchDone?.(batchFiles.length);
126
151
  }
127
152
  return { cancelled: false, ruleIds };
128
153
  }
154
+ /**
155
+ * Rules with `scope: 'project'` over `files` in a project that holds the
156
+ * whole scope; findings by the analyzed file they point at ({@link ownerOf}).
157
+ */
158
+ async function runProjectPass(rules, config, spec, signal) {
159
+ // A kernel without plugins gives a project with the scan kernel's options
160
+ const kernel = new Kernel({
161
+ tsConfigPath: spec.tsConfigPath,
162
+ plugins: [],
163
+ fileSystem: undefined,
164
+ projectOptions: { skipAddingFilesFromTsConfig: true },
165
+ });
166
+ await kernel.initialize();
167
+ const project = kernel.getProject();
168
+ const scope = [...new Set([...(spec.contextFiles ?? []), ...spec.files])].sort();
169
+ const loaded = await loadSourceFiles(project, scope, { signal });
170
+ if (loaded.cancelled) {
171
+ return 'cancelled';
172
+ }
173
+ const api = createPublicApi(project);
174
+ const scanned = spec.files.flatMap((filePath) => project.getSourceFile(filePath) ?? []);
175
+ const findings = new Map(scanned.map((sourceFile) => [sourceFile.getFilePath(), []]));
176
+ for (const sourceFile of scanned) {
177
+ await yieldIfCancellable(signal);
178
+ if (signal?.aborted === true) {
179
+ return 'cancelled';
180
+ }
181
+ for (const finding of await analyzeFile(rules, sourceFile, project, api, config)) {
182
+ findings.get(ownerOf(finding, sourceFile, project))?.push(finding);
183
+ }
184
+ }
185
+ return findings;
186
+ }
187
+ /**
188
+ * File a finding of a project rule is cached under: the source file of the
189
+ * scope it points at, else (a template, a file outside the scope) the file
190
+ * the rule ran for. A rule like library-extraction-opportunity reports on
191
+ * other files than the one it is called for; filed under that one, a warm
192
+ * scan that analyzes another file first would report it a second time next
193
+ * to the cached entry. A finding on a scope file the scan does not analyze
194
+ * finds no owner and is left out: that file's cache entry holds it.
195
+ */
196
+ function ownerOf(finding, analyzed, project) {
197
+ return (project.getSourceFile(finding.filePath) ?? analyzed).getFilePath();
198
+ }
199
+ /** Findings of `rules` for one file; a rule that throws is skipped with a warning. */
200
+ async function analyzeFile(rules, sourceFile, project, api, config) {
201
+ const findings = [];
202
+ for (const rule of rules) {
203
+ try {
204
+ const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
205
+ for (const result of applySuppressionComments(results, rule.id, config, project)) {
206
+ findings.push(toFinding(rule, result));
207
+ }
208
+ }
209
+ catch (error) {
210
+ console.warn(`Failed to analyze with rule ${rule.id}:`, error);
211
+ }
212
+ }
213
+ return findings;
214
+ }
129
215
  async function runRunner(kernel, rules, config, spec, sink, control, ruleIds) {
130
216
  const project = kernel.getProject();
131
217
  const run = await runRulesOverFiles({
@@ -147,18 +233,41 @@ async function runSequential(kernel, rules, config, spec, sink, control, ruleIds
147
233
  const { signal } = control;
148
234
  const project = kernel.getProject();
149
235
  const api = createPublicApi(project);
236
+ // The kernel left unreadable program files out; an analyzed file that
237
+ // fails to load is reported once, also when it is one of them
238
+ const unreadable = new Map(kernel.getUnreadableFiles().map((f) => [f.filePath, f]));
239
+ const result = (cancelled) => ({
240
+ cancelled,
241
+ ruleIds,
242
+ ...(unreadable.size > 0 ? { unreadableFiles: [...unreadable.values()] } : {}),
243
+ });
150
244
  for (const filePath of spec.files) {
151
245
  await yieldIfCancellable(signal);
152
246
  if (signal?.aborted === true) {
153
- return { cancelled: true, ruleIds };
247
+ return result(true);
248
+ }
249
+ // A file that cannot be loaded is not analyzed and gets no file event
250
+ // (before, it counted as analyzed); a file whose rules fail counts as
251
+ // analyzed with the findings it got so far
252
+ let sourceFile;
253
+ try {
254
+ sourceFile = project.addSourceFileAtPath(filePath);
255
+ }
256
+ catch (error) {
257
+ console.warn(`Error loading ${filePath}:`, error);
258
+ if (!unreadable.has(filePath)) {
259
+ unreadable.set(filePath, {
260
+ filePath,
261
+ reason: error instanceof Error ? error.message : String(error),
262
+ });
263
+ }
264
+ continue;
154
265
  }
155
- // A file that fails counts as analyzed with the findings it got so far
156
266
  const findings = [];
157
267
  try {
158
- const sourceFile = project.addSourceFileAtPath(filePath);
159
268
  for (const rule of rules) {
160
269
  const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
161
- for (const result of results) {
270
+ for (const result of applySuppressionComments(results, rule.id, config, project)) {
162
271
  findings.push(toFinding(rule, result));
163
272
  }
164
273
  }
@@ -168,7 +277,7 @@ async function runSequential(kernel, rules, config, spec, sink, control, ruleIds
168
277
  }
169
278
  sink.file({ filePath, findings });
170
279
  }
171
- return { cancelled: false, ruleIds };
280
+ return result(false);
172
281
  }
173
282
  function toFinding(rule, result) {
174
283
  return {
@@ -10,7 +10,7 @@
10
10
  import { existsSync, readFileSync } from 'node:fs';
11
11
  import { isAbsolute, relative, resolve } from 'node:path';
12
12
  import { Project } from 'ts-morph';
13
- import { ConfigLoader, DependencyGraphBuilder, buildViolationPlan, } from '@angular-modernizer/core';
13
+ import { ConfigLoader, DependencyGraphBuilder, buildViolationPlan, addReadableSourceFiles, tsConfigFileNames, unreadableFilesWarning, } from '@angular-modernizer/core';
14
14
  import { LayerPathMatcher, loadLayersFromSource, } from '@angular-modernizer/plugin-architecture';
15
15
  import { findTsConfig } from './find-ts-config.js';
16
16
  function isRecord(value) {
@@ -71,6 +71,20 @@ function isScanViolation(value) {
71
71
  typeof value['ruleId'] === 'string' &&
72
72
  typeof value['severity'] === 'string');
73
73
  }
74
+ /**
75
+ * Project of a tsconfig with its program files, added one by one: an
76
+ * unreadable file is left out and named in `warnings` instead of failing the
77
+ * plan.
78
+ */
79
+ function loadProgram(tsConfigPath, warnings) {
80
+ const project = new Project({ tsConfigFilePath: tsConfigPath, skipAddingFilesFromTsConfig: true });
81
+ const warning = unreadableFilesWarning(addReadableSourceFiles(project, tsConfigFileNames(tsConfigPath)));
82
+ if (warning !== undefined) {
83
+ warnings.push(warning);
84
+ }
85
+ project.resolveSourceFileDependencies();
86
+ return project;
87
+ }
74
88
  /**
75
89
  * Build the file-level plan for violations that carry a file path.
76
90
  */
@@ -81,7 +95,7 @@ export async function buildScanPlan(options) {
81
95
  if (!tsConfigPath) {
82
96
  throw new Error(`tsconfig.json not found in project: ${projectRoot}`);
83
97
  }
84
- const project = (await options.loadProject?.(tsConfigPath)) ?? new Project({ tsConfigFilePath: tsConfigPath });
98
+ const project = (await options.loadProject?.(tsConfigPath)) ?? loadProgram(tsConfigPath, warnings);
85
99
  const graph = new DependencyGraphBuilder(project, { templateEdges: true });
86
100
  await graph.buildGraph();
87
101
  const { layers, source } = await loadLayers(projectRoot, warnings);
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Loads the source maps of bundle stack frames (`main.js`) for the api
3
+ * `StackTraceParser`.
4
+ *
5
+ * Order per bundle: a map on disk first (the bundle resolved under the project
6
+ * root or a build output folder `dist/<app>/browser`, its `sourceMappingURL`
7
+ * comment or `<bundle>.map`), then, when allowed, one HTTP fetch of
8
+ * `<bundle url>.map` from a loopback host (dev server). Other hosts are never
9
+ * contacted.
10
+ */
11
+ import { type SourceMapLookup } from '@angular-modernizer/api';
12
+ /** Fetches a URL as text; `undefined` on any failure. Called only for loopback URLs. */
13
+ export type SourceMapFetcher = (url: string, timeoutMs: number) => Promise<string | undefined>;
14
+ /** Timeout of one source map fetch. */
15
+ export declare const SOURCE_MAP_FETCH_TIMEOUT_MS = 2000;
16
+ /** Where the map of one bundle came from, or why there is none. */
17
+ export interface SourceMapOrigin {
18
+ /** Bundle as the frames name it (without query). */
19
+ bundle: string;
20
+ /** Path or URL of the map; absent when none was found. */
21
+ map?: string;
22
+ /** `disk` or `http`; absent when none was found. */
23
+ from?: 'disk' | 'http';
24
+ /** Why no map was used, when none was found. */
25
+ reason?: string;
26
+ }
27
+ /** Options of {@link loadSourceMaps}. */
28
+ export interface SourceMapLoadOptions {
29
+ /** Absolute project root; disk lookups stay inside it. */
30
+ projectRoot: string;
31
+ /** `false` skips the HTTP step. */
32
+ fetchSourceMaps: boolean;
33
+ /** HTTP fetcher (injected in tests). */
34
+ fetchText: SourceMapFetcher;
35
+ }
36
+ /** Result of {@link loadSourceMaps}. */
37
+ export interface SourceMapLoadResult {
38
+ /** Lookup for the parser. */
39
+ lookup: SourceMapLookup;
40
+ /** One entry per requested bundle. */
41
+ origins: SourceMapOrigin[];
42
+ }
43
+ /** `true` for `http(s)://` URLs on localhost, 127.0.0.1 or ::1. */
44
+ export declare function isLoopbackUrl(url: string): boolean;
45
+ /**
46
+ * Default {@link SourceMapFetcher}: global `fetch` with a timeout. Refuses
47
+ * anything but loopback URLs as a second guard.
48
+ */
49
+ export declare function fetchLoopbackText(url: string, timeoutMs: number): Promise<string | undefined>;
50
+ /**
51
+ * Loads the maps of the given bundles (keys from `StackTraceParser.sourceMapBundles`).
52
+ * At most one fetch per bundle; bundles are distinct.
53
+ */
54
+ export declare function loadSourceMaps(bundles: readonly string[], options: SourceMapLoadOptions): Promise<SourceMapLoadResult>;
55
+ //# sourceMappingURL=source-map-loader.d.ts.map