@angular-modernizer/adapter-mcp 2.0.0 → 2.1.1

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 (46) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +3 -1
  3. package/dist/cli.js +6 -1
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.js +1 -0
  6. package/dist/server/build-staleness.d.ts +92 -0
  7. package/dist/server/build-staleness.js +159 -0
  8. package/dist/server/limited-stdio-transport.js +28 -1
  9. package/dist/server/sdk-server.d.ts +6 -0
  10. package/dist/server/sdk-server.js +21 -2
  11. package/dist/server/tool-registry.d.ts +2 -1
  12. package/dist/server/tool-registry.js +8 -2
  13. package/dist/tools/analyze-project.d.ts +26 -1
  14. package/dist/tools/analyze-project.js +8 -3
  15. package/dist/tools/compare-health.d.ts +40 -4
  16. package/dist/tools/compare-health.js +22 -5
  17. package/dist/tools/helpers/analysis-output.js +3 -0
  18. package/dist/tools/helpers/health-delta.d.ts +6 -0
  19. package/dist/tools/helpers/health-delta.js +4 -1
  20. package/dist/tools/helpers/library-import-warning.d.ts +33 -0
  21. package/dist/tools/helpers/library-import-warning.js +38 -0
  22. package/dist/tools/helpers/library-imports.d.ts +38 -14
  23. package/dist/tools/helpers/library-imports.js +128 -23
  24. package/dist/tools/helpers/output-contract.d.ts +24 -2
  25. package/dist/tools/helpers/output-contract.js +15 -2
  26. package/dist/tools/helpers/refresh-apply.js +1 -1
  27. package/dist/tools/helpers/refresh-inventory.d.ts +1 -1
  28. package/dist/tools/helpers/refresh-inventory.js +24 -3
  29. package/dist/tools/helpers/scan-cache.d.ts +45 -2
  30. package/dist/tools/helpers/scan-cache.js +47 -2
  31. package/dist/tools/helpers/scan-engine.d.ts +13 -0
  32. package/dist/tools/helpers/scan-engine.js +10 -0
  33. package/dist/tools/learn-patterns.js +6 -6
  34. package/dist/tools/list-imports.d.ts +1 -1
  35. package/dist/tools/refresh-state.js +1 -1
  36. package/dist/tools/scan-all.d.ts +7 -1
  37. package/dist/tools/scan-all.js +8 -13
  38. package/dist/tools/scan-angular.d.ts +7 -1
  39. package/dist/tools/scan-angular.js +7 -2
  40. package/dist/tools/scan-architecture.d.ts +8 -0
  41. package/dist/tools/scan-architecture.js +25 -14
  42. package/dist/tools/scan-solid.d.ts +7 -1
  43. package/dist/tools/scan-solid.js +7 -2
  44. package/dist/tools/server-status.d.ts +6 -24
  45. package/dist/tools/server-status.js +9 -57
  46. package/package.json +11 -11
@@ -1,6 +1,7 @@
1
1
  import { type FileSystemAdapter } from '@angular-modernizer/core';
2
2
  import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
3
3
  import { type FileDelta, type HealthViolation, type RuleDelta } from './helpers/health-delta.js';
4
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
4
5
  /** The part of a scan-all result the comparison needs. */
5
6
  export interface HealthScanResult {
6
7
  /** All violations of the scan. */
@@ -28,6 +29,8 @@ export interface HealthScanResult {
28
29
  /** Ids of the rules that ran. */
29
30
  rulesExecuted: string[];
30
31
  };
32
+ /** Library imports that do not resolve; absent when all resolve. */
33
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
31
34
  /** Set by scan-all when the client cancelled the scan. */
32
35
  execution?: {
33
36
  /** `cancelled` when the client cancelled the scan. */
@@ -43,9 +46,12 @@ export type HealthScan = (args: Record<string, unknown>, ctx?: ToolContext) => P
43
46
  * - `no-baseline`: no snapshot existed and `updateSnapshot` was `false`.
44
47
  * - `scope-mismatch`: the snapshot used other rules or include/exclude
45
48
  * patterns; nothing was compared.
49
+ * - `environment-mismatch`: library imports resolved in one run and not in
50
+ * the other (node_modules missing or incomplete), so rules that need
51
+ * library types are not comparable; nothing was compared.
46
52
  * - `invalid-snapshot`: the snapshot could not be read; nothing was compared.
47
53
  */
48
- export type CompareHealthStatus = 'compared' | 'baseline-created' | 'no-baseline' | 'scope-mismatch' | 'invalid-snapshot';
54
+ export type CompareHealthStatus = 'compared' | 'baseline-created' | 'no-baseline' | 'scope-mismatch' | 'environment-mismatch' | 'invalid-snapshot';
49
55
  /** Counts of one run. */
50
56
  export interface HealthRunInfo {
51
57
  /** Time of the run (ISO 8601). */
@@ -111,6 +117,10 @@ export interface CompareHealthOutput {
111
117
  scopeDifferences: string[];
112
118
  /** `true` when `maxResults` cut one of the lists. */
113
119
  truncated: boolean;
120
+ /** The warning of a run whose library imports do not resolve. */
121
+ warnings?: string[];
122
+ /** Library imports of the current run that do not resolve; absent when all resolve. */
123
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
114
124
  /** Human-readable summary for LLM consumption. */
115
125
  summary: string;
116
126
  }
@@ -204,6 +214,35 @@ export declare class CompareHealthTool implements MCPTool {
204
214
  readonly outputSchema: {
205
215
  type: string;
206
216
  properties: {
217
+ summary: {
218
+ type: string;
219
+ };
220
+ unresolvedLibraryImports: {
221
+ readonly type: "object";
222
+ readonly description: "Library imports of the scanned files that do not resolve (node_modules missing or incomplete); rules that need library types can report less. Absent when all resolve.";
223
+ readonly properties: {
224
+ readonly imports: {
225
+ readonly type: "integer";
226
+ };
227
+ readonly packages: {
228
+ readonly type: "integer";
229
+ };
230
+ readonly examples: {
231
+ readonly type: "array";
232
+ readonly items: {
233
+ readonly type: "string";
234
+ };
235
+ };
236
+ };
237
+ readonly required: readonly ["imports", "packages", "examples"];
238
+ };
239
+ warnings: {
240
+ readonly type: "array";
241
+ readonly items: {
242
+ readonly type: "string";
243
+ };
244
+ readonly description: "Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.";
245
+ };
207
246
  status: {
208
247
  type: string;
209
248
  enum: string[];
@@ -400,9 +439,6 @@ export declare class CompareHealthTool implements MCPTool {
400
439
  truncated: {
401
440
  type: string;
402
441
  };
403
- summary: {
404
- type: string;
405
- };
406
442
  };
407
443
  required: string[];
408
444
  };
@@ -2,6 +2,8 @@ import { isAbsolute, relative, resolve } from 'node:path';
2
2
  import { RealFileSystemAdapter, } from '@angular-modernizer/core';
3
3
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
4
4
  import { DEFAULT_HEALTH_SNAPSHOT_PATH, HEALTH_SNAPSHOT_VERSION, compareHealth, compareViolations, parseHealthSnapshot, scopeDifferences, serializeHealthSnapshot, } from './helpers/health-delta.js';
5
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
6
+ import { UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA, WARNINGS_OUTPUT_SCHEMA, } from './helpers/output-contract.js';
5
7
  import { ScanAllTool } from './scan-all.js';
6
8
  /** Violations spelled out per list in the summary; the rest is in the lists. */
7
9
  const SUMMARY_LINES = 15;
@@ -61,7 +63,9 @@ export class CompareHealthTool {
61
63
  'with digits ignored, not by line, so code moving up or down stays unchanged. The first run writes the ' +
62
64
  'baseline (status baseline-created). After a comparison the snapshot is replaced by the current run ' +
63
65
  'unless updateSnapshot is false. A snapshot taken with other rules or include/exclude patterns is not ' +
64
- 'compared (status scope-mismatch) and is only replaced with updateSnapshot: true. currentRun.bySeverity ' +
66
+ 'compared (status scope-mismatch) and is only replaced with updateSnapshot: true; the same for a snapshot ' +
67
+ 'whose library imports resolved while the current ones do not, or the other way round (status ' +
68
+ 'environment-mismatch, missing node_modules). currentRun.bySeverity ' +
65
69
  'and byCategory count all violations. Writes only the snapshot file.';
66
70
  annotations = {
67
71
  readOnlyHint: false,
@@ -124,6 +128,7 @@ export class CompareHealthTool {
124
128
  'baseline-created',
125
129
  'no-baseline',
126
130
  'scope-mismatch',
131
+ 'environment-mismatch',
127
132
  'invalid-snapshot',
128
133
  ],
129
134
  },
@@ -191,6 +196,8 @@ export class CompareHealthTool {
191
196
  rulesRemoved: STRING_LIST,
192
197
  scopeDifferences: STRING_LIST,
193
198
  truncated: { type: 'boolean' },
199
+ ...WARNINGS_OUTPUT_SCHEMA,
200
+ ...UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA,
194
201
  summary: { type: 'string' },
195
202
  },
196
203
  required: [
@@ -234,6 +241,7 @@ export class CompareHealthTool {
234
241
  scope: input.scope,
235
242
  rulesExecuted: [...scanResult.metadata.rulesExecuted].sort(),
236
243
  analyzedFiles: scanResult.counts.analyzedFiles,
244
+ libraryTypesResolved: (scanResult.unresolvedLibraryImports?.imports ?? 0) === 0,
237
245
  violations: scanResult.violations
238
246
  .map(toHealthViolation)
239
247
  .sort(compareViolations),
@@ -243,7 +251,7 @@ export class CompareHealthTool {
243
251
  const differences = previous === undefined
244
252
  ? []
245
253
  : scopeDifferences(previous.scope, current.scope);
246
- const status = decideStatus(stored, differences);
254
+ const status = decideStatus(stored, differences, current);
247
255
  const write = input.updateSnapshot === true ||
248
256
  (input.updateSnapshot === undefined &&
249
257
  (status === 'compared' || status === 'baseline-created'));
@@ -260,7 +268,7 @@ export class CompareHealthTool {
260
268
  differences,
261
269
  compact,
262
270
  });
263
- return output;
271
+ return withLibraryImportWarning(output, scanResult.unresolvedLibraryImports);
264
272
  }
265
273
  async readSnapshot(path) {
266
274
  if (!(await this.fileSystem.exists(path))) {
@@ -334,14 +342,19 @@ function toHealthViolation(v) {
334
342
  ...(v.line === undefined ? {} : { line: v.line }),
335
343
  };
336
344
  }
337
- function decideStatus(stored, differences) {
345
+ function decideStatus(stored, differences, current) {
338
346
  if (!stored.exists) {
339
347
  return 'baseline-created';
340
348
  }
341
349
  if (stored.snapshot === undefined) {
342
350
  return 'invalid-snapshot';
343
351
  }
344
- return differences.length > 0 ? 'scope-mismatch' : 'compared';
352
+ if (differences.length > 0) {
353
+ return 'scope-mismatch';
354
+ }
355
+ return stored.snapshot.libraryTypesResolved === current.libraryTypesResolved
356
+ ? 'compared'
357
+ : 'environment-mismatch';
345
358
  }
346
359
  function buildOutput(parts) {
347
360
  const { root, snapshotLabel, written, previous, current, differences, compact, } = parts;
@@ -470,6 +483,10 @@ function describeOther(status, snapshotLabel, previous, current, differences, wr
470
483
  case 'scope-mismatch':
471
484
  return (`The previous run (${previous?.createdAt ?? '?'}) used another scope, so nothing was compared: ` +
472
485
  `${differences.join('; ')}.${replaced}`);
486
+ case 'environment-mismatch':
487
+ return (`Library imports ${current.libraryTypesResolved ? 'resolve now but did not' : 'do not resolve now but did'} ` +
488
+ `in the previous run (${previous?.createdAt ?? '?'}), so rules that need library types are not ` +
489
+ `comparable and nothing was compared; is node_modules missing or incomplete in one of the runs?${replaced}`);
473
490
  case 'invalid-snapshot':
474
491
  return `${snapshotLabel} is not a readable health snapshot (version ${HEALTH_SNAPSHOT_VERSION}); nothing was compared.${replaced}`;
475
492
  case 'compared':
@@ -4,6 +4,7 @@
4
4
  * Schema pieces and summary helpers shared by analyze-project and the scans.
5
5
  * Objects stay open, see `output-contract.ts`.
6
6
  */
7
+ import { UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA, WARNINGS_OUTPUT_SCHEMA, } from './output-contract.js';
7
8
  /** `pagination` of a paged result list. */
8
9
  export const PAGINATION_SCHEMA = {
9
10
  type: 'object',
@@ -136,6 +137,8 @@ export function scanOutputSchema(extra = {}) {
136
137
  },
137
138
  pagination: PAGINATION_SCHEMA,
138
139
  orchestration: { type: 'object' },
140
+ ...WARNINGS_OUTPUT_SCHEMA,
141
+ ...UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA,
139
142
  ...extra,
140
143
  summary: { type: 'string' },
141
144
  },
@@ -26,6 +26,12 @@ export interface HealthSnapshot {
26
26
  scope: HealthScope;
27
27
  rulesExecuted: string[];
28
28
  analyzedFiles: number;
29
+ /**
30
+ * Whether every library import of the scan resolved (node_modules
31
+ * complete); rules that need library types report differently without
32
+ * them. Absent in snapshots written before the flag: read as `true`.
33
+ */
34
+ libraryTypesResolved: boolean;
29
35
  violations: HealthViolation[];
30
36
  }
31
37
  /** Counts of one rule in the previous and the current run. */
@@ -30,6 +30,7 @@ export function serializeHealthSnapshot(snapshot) {
30
30
  scope: snapshot.scope,
31
31
  rulesExecuted: snapshot.rulesExecuted,
32
32
  analyzedFiles: snapshot.analyzedFiles,
33
+ libraryTypesResolved: snapshot.libraryTypesResolved,
33
34
  totalViolations: snapshot.violations.length,
34
35
  });
35
36
  const lines = [...files].map(([file, list]) => `${JSON.stringify(file)}:${JSON.stringify(list)}`);
@@ -52,11 +53,12 @@ export function parseHealthSnapshot(text) {
52
53
  if (!isRecord(data) || data['version'] !== HEALTH_SNAPSHOT_VERSION) {
53
54
  return undefined;
54
55
  }
55
- const { createdAt, scope, rulesExecuted, analyzedFiles, files } = data;
56
+ const { createdAt, scope, rulesExecuted, analyzedFiles, libraryTypesResolved, files } = data;
56
57
  const valid = typeof createdAt === 'string' &&
57
58
  isScope(scope) &&
58
59
  isStringArray(rulesExecuted) &&
59
60
  typeof analyzedFiles === 'number' &&
61
+ (libraryTypesResolved === undefined || typeof libraryTypesResolved === 'boolean') &&
60
62
  isRecord(files);
61
63
  if (!valid) {
62
64
  return undefined;
@@ -83,6 +85,7 @@ export function parseHealthSnapshot(text) {
83
85
  scope,
84
86
  rulesExecuted,
85
87
  analyzedFiles,
88
+ libraryTypesResolved: libraryTypesResolved ?? true,
86
89
  violations,
87
90
  };
88
91
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Warning about unresolved library imports
3
+ *
4
+ * Counts, warning text and the result helper of the library import check
5
+ * (`library-imports.ts`). Kept apart from the check so the scan tools can
6
+ * add the warning without loading ts-morph (their unit tests mock `node:fs`).
7
+ */
8
+ /** Library imports of a project that do not resolve. */
9
+ export interface UnresolvedLibraryImports {
10
+ /** Import and `export ... from` declarations with an unresolved library specifier. */
11
+ imports: number;
12
+ /** Distinct packages among them (`@scope/name` or `name`). */
13
+ packages: number;
14
+ /** Up to {@link EXAMPLE_PACKAGES} package names, most imported first. */
15
+ examples: string[];
16
+ }
17
+ /** Package names listed in the warning. */
18
+ export declare const EXAMPLE_PACKAGES = 5;
19
+ /** Warning text for `warnings` and the summary, or `undefined` when all resolve. */
20
+ export declare function libraryImportWarning(found: UnresolvedLibraryImports): string | undefined;
21
+ /**
22
+ * Adds the library import warning of a scan to its result: one entry in
23
+ * `warnings` (after the existing ones), `unresolvedLibraryImports` and one
24
+ * `Warning:` line in the summary. Returns the result unchanged when every
25
+ * library import resolved or nothing was checked (a cancelled worker run).
26
+ */
27
+ export declare function withLibraryImportWarning<T extends {
28
+ summary: string;
29
+ warnings?: string[];
30
+ }>(result: T, found: UnresolvedLibraryImports | undefined): T & {
31
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
32
+ };
33
+ //# sourceMappingURL=library-import-warning.d.ts.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Warning about unresolved library imports
3
+ *
4
+ * Counts, warning text and the result helper of the library import check
5
+ * (`library-imports.ts`). Kept apart from the check so the scan tools can
6
+ * add the warning without loading ts-morph (their unit tests mock `node:fs`).
7
+ */
8
+ /** Package names listed in the warning. */
9
+ export const EXAMPLE_PACKAGES = 5;
10
+ /** Warning text for `warnings` and the summary, or `undefined` when all resolve. */
11
+ export function libraryImportWarning(found) {
12
+ if (found.imports === 0) {
13
+ return undefined;
14
+ }
15
+ const more = found.packages > found.examples.length ? ', ...' : '';
16
+ return (`${found.imports} library import(s) from ${found.packages} package(s) do not resolve ` +
17
+ `(${found.examples.join(', ')}${more}); is node_modules missing or incomplete? ` +
18
+ 'Results that depend on library types (dialogs, subscriptions, injected services) can be incomplete.');
19
+ }
20
+ /**
21
+ * Adds the library import warning of a scan to its result: one entry in
22
+ * `warnings` (after the existing ones), `unresolvedLibraryImports` and one
23
+ * `Warning:` line in the summary. Returns the result unchanged when every
24
+ * library import resolved or nothing was checked (a cancelled worker run).
25
+ */
26
+ export function withLibraryImportWarning(result, found) {
27
+ const warning = found === undefined ? undefined : libraryImportWarning(found);
28
+ if (found === undefined || warning === undefined) {
29
+ return result;
30
+ }
31
+ return {
32
+ ...result,
33
+ warnings: [...(result.warnings ?? []), warning],
34
+ unresolvedLibraryImports: found,
35
+ summary: `${result.summary}\nWarning: ${warning}`,
36
+ };
37
+ }
38
+ //# sourceMappingURL=library-import-warning.js.map
@@ -25,18 +25,9 @@
25
25
  * JavaScript such as `moment/locale/de-at` have no types to resolve). No
26
26
  * program is created.
27
27
  */
28
- import { type FileSystemHost, type Project } from 'ts-morph';
29
- /** Library imports of a project that do not resolve. */
30
- export interface UnresolvedLibraryImports {
31
- /** Import and `export ... from` declarations with an unresolved library specifier. */
32
- imports: number;
33
- /** Distinct packages among them (`@scope/name` or `name`). */
34
- packages: number;
35
- /** Up to {@link EXAMPLE_PACKAGES} package names, most imported first. */
36
- examples: string[];
37
- }
38
- /** Package names listed in the warning. */
39
- export declare const EXAMPLE_PACKAGES = 5;
28
+ import { Project, type FileSystemHost } from 'ts-morph';
29
+ import { type UnresolvedLibraryImports } from './library-import-warning.js';
30
+ export { EXAMPLE_PACKAGES, libraryImportWarning, withLibraryImportWarning, type UnresolvedLibraryImports, } from './library-import-warning.js';
40
31
  /** `@scope/name/sub` -> `@scope/name`, `name/sub` -> `name`. */
41
32
  export declare function packageName(specifier: string): string;
42
33
  /**
@@ -52,6 +43,39 @@ export declare function declaredPackages(fs: FileSystemHost, dir: string): Set<s
52
43
  * declared packages is looked up from its directory upwards.
53
44
  */
54
45
  export declare function findUnresolvedLibraryImports(project: Project, tsConfigPath: string): UnresolvedLibraryImports;
55
- /** Warning text for `warnings` and the summary, or `undefined` when all resolve. */
56
- export declare function libraryImportWarning(found: UnresolvedLibraryImports): string | undefined;
46
+ /**
47
+ * Like {@link findUnresolvedLibraryImports}, for files that are not (all)
48
+ * in the project: the scans hold only a batch of their scope at a time and
49
+ * none on a warm run. Each file is read and scanned for its imports without
50
+ * a parse; besides import and `export ... from` declarations this also
51
+ * counts `import x = require(...)` and dynamic `import(...)` of a library.
52
+ * Files that cannot be read are skipped; the specifiers of a file are
53
+ * remembered per process until its mtime or size changes.
54
+ *
55
+ * @param project - Gives compiler options, module resolution host and file
56
+ * system of the tsconfig; its source files are not read.
57
+ * @param tsConfigPath - As in {@link findUnresolvedLibraryImports}.
58
+ * @param filePaths - Absolute paths of the files to check.
59
+ */
60
+ export declare function findUnresolvedLibraryImportsInFiles(project: Project, tsConfigPath: string, filePaths: Iterable<string>): UnresolvedLibraryImports;
61
+ /** Library imports of a scan scope, see {@link checkScanScope}. */
62
+ export interface ScanScopeLibraryImports {
63
+ /** Counts and examples for the warning. */
64
+ unresolved: UnresolvedLibraryImports;
65
+ /** Every package with an unresolved import, sorted; empty when all resolve. */
66
+ packages: string[];
67
+ }
68
+ /**
69
+ * Library imports of a scan scope that do not resolve, checked before the
70
+ * scan reads its cache: the packages go into the cache version, so entries
71
+ * written while node_modules was missing or incomplete are not served once
72
+ * it is complete (and the other way round). Runs on the calling thread and
73
+ * yields to the event loop every {@link FILES_PER_TURN} files; repeated
74
+ * calls only stat unchanged files (see {@link findUnresolvedLibraryImportsInFiles}).
75
+ *
76
+ * @param tsConfigPath - tsconfig of the scan; gives compiler options and
77
+ * the `package.json` with the declared packages.
78
+ * @param filePaths - Absolute paths of the scan scope.
79
+ */
80
+ export declare function checkScanScope(tsConfigPath: string, filePaths: readonly string[]): Promise<ScanScopeLibraryImports>;
57
81
  //# sourceMappingURL=library-imports.d.ts.map
@@ -26,10 +26,11 @@
26
26
  * program is created.
27
27
  */
28
28
  import { isRelativeSpecifier, matchPathPattern, } from '@angular-modernizer/core';
29
+ import { statSync } from 'node:fs';
29
30
  import { dirname, join } from 'node:path';
30
- import { ts } from 'ts-morph';
31
- /** Package names listed in the warning. */
32
- export const EXAMPLE_PACKAGES = 5;
31
+ import { Project, ts } from 'ts-morph';
32
+ import { EXAMPLE_PACKAGES, } from './library-import-warning.js';
33
+ export { EXAMPLE_PACKAGES, libraryImportWarning, withLibraryImportWarning, } from './library-import-warning.js';
33
34
  /** Module specifiers of the import and re-export declarations of one file. */
34
35
  function moduleSpecifiers(sourceFile) {
35
36
  const specifiers = [];
@@ -89,13 +90,11 @@ function packageFolderExists(host, fromFile, pkg) {
89
90
  }
90
91
  }
91
92
  /**
92
- * Resolves every distinct library specifier of `project` once and counts the
93
- * declarations whose specifier does not resolve.
94
- *
95
- * @param tsConfigPath - The project's tsconfig; the `package.json` with the
96
- * declared packages is looked up from its directory upwards.
93
+ * Resolves every distinct library specifier of `files` once against the
94
+ * compiler options and module resolution host of `project` and counts the
95
+ * imports whose specifier does not resolve.
97
96
  */
98
- export function findUnresolvedLibraryImports(project, tsConfigPath) {
97
+ function countUnresolved(project, tsConfigPath, files) {
99
98
  const declared = declaredPackages(project.getFileSystem(), dirname(tsConfigPath));
100
99
  const options = project.getCompilerOptions();
101
100
  const host = project.getModuleResolutionHost();
@@ -105,12 +104,8 @@ export function findUnresolvedLibraryImports(project, tsConfigPath) {
105
104
  const resolved = new Map();
106
105
  const unresolvedPerPackage = new Map();
107
106
  let imports = 0;
108
- for (const sourceFile of project.getSourceFiles()) {
109
- if (sourceFile.isInNodeModules()) {
110
- continue;
111
- }
112
- const containingFile = sourceFile.getFilePath();
113
- for (const specifier of moduleSpecifiers(sourceFile.compilerNode)) {
107
+ for (const { path: containingFile, specifiers } of files) {
108
+ for (const specifier of specifiers) {
114
109
  const isLibrary = !isRelativeSpecifier(specifier) &&
115
110
  declared.has(packageName(specifier)) &&
116
111
  !isAlias(specifier);
@@ -136,16 +131,126 @@ export function findUnresolvedLibraryImports(project, tsConfigPath) {
136
131
  .sort(([a, countA], [b, countB]) => countB - countA || a.localeCompare(b))
137
132
  .slice(0, EXAMPLE_PACKAGES)
138
133
  .map(([name]) => name);
139
- return { imports, packages: unresolvedPerPackage.size, examples };
134
+ return {
135
+ found: { imports, packages: unresolvedPerPackage.size, examples },
136
+ packages: [...unresolvedPerPackage.keys()].sort(),
137
+ };
140
138
  }
141
- /** Warning text for `warnings` and the summary, or `undefined` when all resolve. */
142
- export function libraryImportWarning(found) {
143
- if (found.imports === 0) {
139
+ /** Import specifiers of the source files of `project` outside node_modules. */
140
+ function* projectFiles(project) {
141
+ for (const sourceFile of project.getSourceFiles()) {
142
+ if (!sourceFile.isInNodeModules()) {
143
+ yield {
144
+ path: sourceFile.getFilePath(),
145
+ specifiers: moduleSpecifiers(sourceFile.compilerNode),
146
+ };
147
+ }
148
+ }
149
+ }
150
+ /**
151
+ * Resolves every distinct library specifier of `project` once and counts the
152
+ * declarations whose specifier does not resolve.
153
+ *
154
+ * @param tsConfigPath - The project's tsconfig; the `package.json` with the
155
+ * declared packages is looked up from its directory upwards.
156
+ */
157
+ export function findUnresolvedLibraryImports(project, tsConfigPath) {
158
+ return countUnresolved(project, tsConfigPath, projectFiles(project)).found;
159
+ }
160
+ /** Most files whose specifiers {@link fileSpecifiers} keeps. */
161
+ const MAX_REMEMBERED_FILES = 50000;
162
+ /** Specifiers per file path, valid while mtime and size are unchanged. */
163
+ const rememberedSpecifiers = new Map();
164
+ /**
165
+ * Import specifiers of one file, read through `fs`; `undefined` when it
166
+ * cannot be read. Remembered per process by mtime and size, so a repeated
167
+ * scan (a warm run checks its whole scope) only stats the file; a file
168
+ * that cannot be stat'ed (in-memory file systems) is read every time.
169
+ */
170
+ function fileSpecifiers(fs, path) {
171
+ let stat;
172
+ try {
173
+ stat = statSync(path);
174
+ }
175
+ catch {
176
+ stat = undefined;
177
+ }
178
+ const known = rememberedSpecifiers.get(path);
179
+ if (stat !== undefined && known?.mtimeMs === stat.mtimeMs && known.size === stat.size) {
180
+ return known.specifiers;
181
+ }
182
+ let text;
183
+ try {
184
+ text = fs.readFileSync(path);
185
+ }
186
+ catch {
144
187
  return undefined;
145
188
  }
146
- const more = found.packages > found.examples.length ? ', ...' : '';
147
- return (`${found.imports} library import(s) from ${found.packages} package(s) do not resolve ` +
148
- `(${found.examples.join(', ')}${more}); is node_modules missing or incomplete? ` +
149
- 'Results that depend on library types (dialogs, subscriptions, injected services) can be incomplete.');
189
+ // The scanner pass of preProcessFile is several times faster than a parse
190
+ const specifiers = ts.preProcessFile(text, true, false).importedFiles.map((f) => f.fileName);
191
+ if (stat !== undefined) {
192
+ if (rememberedSpecifiers.size >= MAX_REMEMBERED_FILES) {
193
+ rememberedSpecifiers.clear();
194
+ }
195
+ rememberedSpecifiers.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, specifiers });
196
+ }
197
+ return specifiers;
198
+ }
199
+ /** Import specifiers of `filePaths`, read through the project's file system. */
200
+ function* filesOnDisk(project, filePaths) {
201
+ const fs = project.getFileSystem();
202
+ for (const path of filePaths) {
203
+ if (path.split(/[\\/]/).includes('node_modules')) {
204
+ continue;
205
+ }
206
+ const specifiers = fileSpecifiers(fs, path);
207
+ if (specifiers !== undefined) {
208
+ yield { path, specifiers };
209
+ }
210
+ }
211
+ }
212
+ /**
213
+ * Like {@link findUnresolvedLibraryImports}, for files that are not (all)
214
+ * in the project: the scans hold only a batch of their scope at a time and
215
+ * none on a warm run. Each file is read and scanned for its imports without
216
+ * a parse; besides import and `export ... from` declarations this also
217
+ * counts `import x = require(...)` and dynamic `import(...)` of a library.
218
+ * Files that cannot be read are skipped; the specifiers of a file are
219
+ * remembered per process until its mtime or size changes.
220
+ *
221
+ * @param project - Gives compiler options, module resolution host and file
222
+ * system of the tsconfig; its source files are not read.
223
+ * @param tsConfigPath - As in {@link findUnresolvedLibraryImports}.
224
+ * @param filePaths - Absolute paths of the files to check.
225
+ */
226
+ export function findUnresolvedLibraryImportsInFiles(project, tsConfigPath, filePaths) {
227
+ return countUnresolved(project, tsConfigPath, filesOnDisk(project, filePaths)).found;
228
+ }
229
+ /** Files read between two turns of the event loop in {@link checkScanScope}. */
230
+ const FILES_PER_TURN = 50;
231
+ /**
232
+ * Library imports of a scan scope that do not resolve, checked before the
233
+ * scan reads its cache: the packages go into the cache version, so entries
234
+ * written while node_modules was missing or incomplete are not served once
235
+ * it is complete (and the other way round). Runs on the calling thread and
236
+ * yields to the event loop every {@link FILES_PER_TURN} files; repeated
237
+ * calls only stat unchanged files (see {@link findUnresolvedLibraryImportsInFiles}).
238
+ *
239
+ * @param tsConfigPath - tsconfig of the scan; gives compiler options and
240
+ * the `package.json` with the declared packages.
241
+ * @param filePaths - Absolute paths of the scan scope.
242
+ */
243
+ export async function checkScanScope(tsConfigPath, filePaths) {
244
+ const project = new Project({ tsConfigFilePath: tsConfigPath, skipAddingFilesFromTsConfig: true });
245
+ const files = [];
246
+ let read = 0;
247
+ for (const file of filesOnDisk(project, filePaths)) {
248
+ files.push(file);
249
+ if (++read % FILES_PER_TURN === 0) {
250
+ await new Promise((done) => setImmediate(done));
251
+ }
252
+ }
253
+ const { found, packages } = countUnresolved(project, tsConfigPath, files);
254
+ return { unresolved: found, packages };
150
255
  }
151
256
  //# sourceMappingURL=library-imports.js.map
@@ -21,6 +21,28 @@ export declare const WARNINGS_OUTPUT_SCHEMA: {
21
21
  readonly description: "Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.";
22
22
  };
23
23
  };
24
+ /** `unresolvedLibraryImports` entry of an output schema. */
25
+ export declare const UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA: {
26
+ readonly unresolvedLibraryImports: {
27
+ readonly type: "object";
28
+ readonly description: "Library imports of the scanned files that do not resolve (node_modules missing or incomplete); rules that need library types can report less. Absent when all resolve.";
29
+ readonly properties: {
30
+ readonly imports: {
31
+ readonly type: "integer";
32
+ };
33
+ readonly packages: {
34
+ readonly type: "integer";
35
+ };
36
+ readonly examples: {
37
+ readonly type: "array";
38
+ readonly items: {
39
+ readonly type: "string";
40
+ };
41
+ };
42
+ };
43
+ readonly required: readonly ["imports", "packages", "examples"];
44
+ };
45
+ };
24
46
  /**
25
47
  * Adds `warnings` to a result and one `Warning:` line per entry to its
26
48
  * summary; returns the result unchanged when there are none.
@@ -38,13 +60,13 @@ export declare function withWarnings<T extends {
38
60
  export declare const CONFIG_WARNINGS_OUTPUT_SCHEMA: {
39
61
  readonly configWarnings: {
40
62
  readonly type: "array";
41
- readonly description: "Warnings about the project configuration (.angular-modernizer.json) the call loaded: deprecated keys without effect, layers / layersSource drift, a failed layersSource import. Absent when there are none.";
63
+ readonly description: "Warnings about the project configuration (.angular-modernizer.json) the call loaded: deprecated keys without effect, layers / layersSource drift, a failed layersSource import; stale-build when a package dist/ was rebuilt after the server started (reconnect the MCP server). Absent when there are none.";
42
64
  readonly items: {
43
65
  readonly type: "object";
44
66
  readonly properties: {
45
67
  readonly code: {
46
68
  readonly type: "string";
47
- readonly enum: readonly ["deprecated-key", "layers-drift", "layers-source-failed"];
69
+ readonly enum: readonly ["deprecated-key", "layers-drift", "layers-source-failed", "stale-build"];
48
70
  };
49
71
  readonly message: {
50
72
  readonly type: "string";
@@ -18,6 +18,19 @@ export const WARNINGS_OUTPUT_SCHEMA = {
18
18
  description: 'Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.',
19
19
  },
20
20
  };
21
+ /** `unresolvedLibraryImports` entry of an output schema. */
22
+ export const UNRESOLVED_LIBRARY_IMPORTS_OUTPUT_SCHEMA = {
23
+ unresolvedLibraryImports: {
24
+ type: 'object',
25
+ description: 'Library imports of the scanned files that do not resolve (node_modules missing or incomplete); rules that need library types can report less. Absent when all resolve.',
26
+ properties: {
27
+ imports: { type: 'integer' },
28
+ packages: { type: 'integer' },
29
+ examples: { type: 'array', items: { type: 'string' } },
30
+ },
31
+ required: ['imports', 'packages', 'examples'],
32
+ },
33
+ };
21
34
  /**
22
35
  * Adds `warnings` to a result and one `Warning:` line per entry to its
23
36
  * summary; returns the result unchanged when there are none.
@@ -37,11 +50,11 @@ export function withWarnings(result, warnings) {
37
50
  export const CONFIG_WARNINGS_OUTPUT_SCHEMA = {
38
51
  configWarnings: {
39
52
  type: 'array',
40
- description: 'Warnings about the project configuration (.angular-modernizer.json) the call loaded: deprecated keys without effect, layers / layersSource drift, a failed layersSource import. Absent when there are none.',
53
+ description: 'Warnings about the project configuration (.angular-modernizer.json) the call loaded: deprecated keys without effect, layers / layersSource drift, a failed layersSource import; stale-build when a package dist/ was rebuilt after the server started (reconnect the MCP server). Absent when there are none.',
41
54
  items: {
42
55
  type: 'object',
43
56
  properties: {
44
- code: { type: 'string', enum: ['deprecated-key', 'layers-drift', 'layers-source-failed'] },
57
+ code: { type: 'string', enum: ['deprecated-key', 'layers-drift', 'layers-source-failed', 'stale-build'] },
45
58
  message: { type: 'string' },
46
59
  key: { type: 'string', description: 'The config key the warning is about.' },
47
60
  },
@@ -23,7 +23,7 @@ export const REFRESH_PARTS = ['caches', 'backups', 'refs', 'feedback'];
23
23
  const PART_SCOPE = {
24
24
  caches: {
25
25
  stores: ['scan-cache', 'legacy-cache'],
26
- reasons: ['orphan', 'expired', 'unreadable', 'legacy-layout', 'legacy-store'],
26
+ reasons: ['orphan', 'outdated-layout', 'expired', 'unreadable', 'legacy-layout', 'legacy-store'],
27
27
  },
28
28
  backups: {
29
29
  stores: ['backups'],