@angular-modernizer/adapter-mcp 1.2.0 → 2.1.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 (138) hide show
  1. package/CHANGELOG.md +688 -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 +10 -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 +55 -4
  27. package/dist/tools/analyze-project.js +104 -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/compare-health.d.ts +40 -4
  32. package/dist/tools/compare-health.js +22 -5
  33. package/dist/tools/extract-libraries.js +42 -27
  34. package/dist/tools/find-angular-symbol.js +3 -2
  35. package/dist/tools/find-component-hosts.js +3 -2
  36. package/dist/tools/find-usages.js +21 -12
  37. package/dist/tools/get-call-graph.js +15 -2
  38. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  39. package/dist/tools/get-operation-progress-tool.js +2 -2
  40. package/dist/tools/get-operation-progress.d.ts +4 -1
  41. package/dist/tools/get-operation-progress.js +6 -2
  42. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  43. package/dist/tools/helpers/analysis-output.js +25 -1
  44. package/dist/tools/helpers/build-cache.d.ts +27 -0
  45. package/dist/tools/helpers/build-cache.js +86 -0
  46. package/dist/tools/helpers/class-filter.d.ts +18 -0
  47. package/dist/tools/helpers/class-filter.js +30 -0
  48. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  49. package/dist/tools/helpers/cli-arguments.js +35 -0
  50. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  51. package/dist/tools/helpers/feedback-catalog.js +196 -0
  52. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  53. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  54. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  55. package/dist/tools/helpers/file-type-check.js +56 -0
  56. package/dist/tools/helpers/health-delta.d.ts +6 -0
  57. package/dist/tools/helpers/health-delta.js +4 -1
  58. package/dist/tools/helpers/library-import-warning.d.ts +33 -0
  59. package/dist/tools/helpers/library-import-warning.js +38 -0
  60. package/dist/tools/helpers/library-imports.d.ts +38 -14
  61. package/dist/tools/helpers/library-imports.js +128 -23
  62. package/dist/tools/helpers/output-contract.d.ts +64 -0
  63. package/dist/tools/helpers/output-contract.js +67 -0
  64. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  65. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  66. package/dist/tools/helpers/project-cache.d.ts +5 -4
  67. package/dist/tools/helpers/project-cache.js +21 -16
  68. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  69. package/dist/tools/helpers/project-decorators.js +13 -6
  70. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  71. package/dist/tools/helpers/refresh-apply.js +460 -0
  72. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  73. package/dist/tools/helpers/refresh-inventory.js +631 -0
  74. package/dist/tools/helpers/rule-runner.js +3 -1
  75. package/dist/tools/helpers/scan-cache.d.ts +117 -5
  76. package/dist/tools/helpers/scan-cache.js +179 -6
  77. package/dist/tools/helpers/scan-engine.d.ts +43 -6
  78. package/dist/tools/helpers/scan-engine.js +141 -22
  79. package/dist/tools/helpers/scan-plan.js +16 -2
  80. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  81. package/dist/tools/helpers/source-map-loader.js +226 -0
  82. package/dist/tools/helpers/template-check.d.ts +76 -0
  83. package/dist/tools/helpers/template-check.js +158 -0
  84. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  85. package/dist/tools/helpers/tool-cache.js +9 -3
  86. package/dist/tools/helpers/tool-context.d.ts +18 -0
  87. package/dist/tools/helpers/tool-context.js +29 -0
  88. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  89. package/dist/tools/helpers/transform-safety.js +357 -4
  90. package/dist/tools/inspect-form-group.js +5 -0
  91. package/dist/tools/inspect-i18n.d.ts +1 -1
  92. package/dist/tools/inspect-template.js +8 -2
  93. package/dist/tools/learn-patterns.d.ts +43 -28
  94. package/dist/tools/learn-patterns.js +83 -161
  95. package/dist/tools/list-imports.d.ts +1 -1
  96. package/dist/tools/orchestrate-migration.d.ts +19 -1
  97. package/dist/tools/orchestrate-migration.js +52 -10
  98. package/dist/tools/parse-stack-trace.d.ts +48 -1
  99. package/dist/tools/parse-stack-trace.js +108 -9
  100. package/dist/tools/plan-migration.js +22 -10
  101. package/dist/tools/refresh-state.d.ts +378 -0
  102. package/dist/tools/refresh-state.js +370 -0
  103. package/dist/tools/resolve-type.js +10 -3
  104. package/dist/tools/review-feedback.d.ts +42 -7
  105. package/dist/tools/review-feedback.js +24 -17
  106. package/dist/tools/rollback-changes.d.ts +5 -0
  107. package/dist/tools/rollback-changes.js +7 -2
  108. package/dist/tools/run-angular-cli.js +36 -22
  109. package/dist/tools/run-build.d.ts +33 -28
  110. package/dist/tools/run-build.js +136 -438
  111. package/dist/tools/run-schematic.d.ts +8 -2
  112. package/dist/tools/run-schematic.js +80 -50
  113. package/dist/tools/scan-all.d.ts +37 -15
  114. package/dist/tools/scan-all.js +76 -115
  115. package/dist/tools/scan-angular.d.ts +33 -14
  116. package/dist/tools/scan-angular.js +77 -94
  117. package/dist/tools/scan-architecture.d.ts +37 -12
  118. package/dist/tools/scan-architecture.js +220 -139
  119. package/dist/tools/scan-solid.d.ts +33 -14
  120. package/dist/tools/scan-solid.js +80 -91
  121. package/dist/tools/search-codebase.d.ts +6 -1
  122. package/dist/tools/search-codebase.js +13 -7
  123. package/dist/tools/suggest-improvements.d.ts +34 -3
  124. package/dist/tools/suggest-improvements.js +34 -9
  125. package/dist/tools/trace-output-flow.js +3 -2
  126. package/dist/tools/transform-code-batch.d.ts +9 -9
  127. package/dist/tools/transform-code.d.ts +161 -12
  128. package/dist/tools/transform-code.js +715 -206
  129. package/dist/tools/validate-before-transform.js +2 -1
  130. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  131. package/dist/tools/validate-project-compatibility.js +33 -225
  132. package/dist/tools/validate-transformation.d.ts +40 -26
  133. package/dist/tools/validate-transformation.js +115 -294
  134. package/dist/tools/verify-citations.js +8 -2
  135. package/dist/types.d.ts +9 -9
  136. package/dist/utils/format-tool-response.d.ts +3 -1
  137. package/dist/utils/format-tool-response.js +8 -3
  138. package/package.json +14 -13
@@ -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
@@ -10,6 +10,7 @@
10
10
  * result into an output validation error. `required` lists only fields every
11
11
  * variant of the result carries (`summaryOnly` drops the lists).
12
12
  */
13
+ import { type ConfigWarning } from '@angular-modernizer/core';
13
14
  /** `warnings` entry of an output schema. */
14
15
  export declare const WARNINGS_OUTPUT_SCHEMA: {
15
16
  readonly warnings: {
@@ -20,6 +21,28 @@ export declare const WARNINGS_OUTPUT_SCHEMA: {
20
21
  readonly description: "Conditions that can make the result incomplete, e.g. library imports that do not resolve because node_modules is missing.";
21
22
  };
22
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
+ };
23
46
  /**
24
47
  * Adds `warnings` to a result and one `Warning:` line per entry to its
25
48
  * summary; returns the result unchanged when there are none.
@@ -29,4 +52,45 @@ export declare function withWarnings<T extends {
29
52
  }>(result: T, warnings: readonly string[]): T & {
30
53
  warnings?: string[];
31
54
  };
55
+ /**
56
+ * `configWarnings` entry of an output schema. sdk-server adds it to every
57
+ * registered output schema (`withConfigWarningsSchema`); its own field because
58
+ * `warnings` means something different per tool.
59
+ */
60
+ export declare const CONFIG_WARNINGS_OUTPUT_SCHEMA: {
61
+ readonly configWarnings: {
62
+ readonly type: "array";
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. Absent when there are none.";
64
+ readonly items: {
65
+ readonly type: "object";
66
+ readonly properties: {
67
+ readonly code: {
68
+ readonly type: "string";
69
+ readonly enum: readonly ["deprecated-key", "layers-drift", "layers-source-failed"];
70
+ };
71
+ readonly message: {
72
+ readonly type: "string";
73
+ };
74
+ readonly key: {
75
+ readonly type: "string";
76
+ readonly description: "The config key the warning is about.";
77
+ };
78
+ };
79
+ readonly required: readonly ["code", "message"];
80
+ };
81
+ };
82
+ };
83
+ /** An output schema with `configWarnings` added to its properties. */
84
+ export declare function withConfigWarningsSchema(schema: object): Record<string, unknown>;
85
+ /**
86
+ * Adds `configWarnings` to a tool result and one `Config:` line to its
87
+ * summary; returns the result unchanged when there are none or when the result
88
+ * is no object.
89
+ */
90
+ export declare function withConfigWarnings(result: unknown, warnings: readonly ConfigWarning[]): unknown;
91
+ /**
92
+ * The summary line of config warnings: their count and the first message;
93
+ * `inField` points to `configWarnings`, which an error answer does not carry.
94
+ */
95
+ export declare function configWarningsLine(warnings: readonly ConfigWarning[], inField: boolean): string;
32
96
  //# sourceMappingURL=output-contract.d.ts.map
@@ -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.
@@ -29,4 +42,58 @@ export function withWarnings(result, warnings) {
29
42
  const lines = warnings.map((w) => `Warning: ${w}`).join('\n');
30
43
  return { ...result, summary: `${result.summary}\n${lines}`, warnings: [...warnings] };
31
44
  }
45
+ /**
46
+ * `configWarnings` entry of an output schema. sdk-server adds it to every
47
+ * registered output schema (`withConfigWarningsSchema`); its own field because
48
+ * `warnings` means something different per tool.
49
+ */
50
+ export const CONFIG_WARNINGS_OUTPUT_SCHEMA = {
51
+ configWarnings: {
52
+ type: 'array',
53
+ 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.',
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ code: { type: 'string', enum: ['deprecated-key', 'layers-drift', 'layers-source-failed'] },
58
+ message: { type: 'string' },
59
+ key: { type: 'string', description: 'The config key the warning is about.' },
60
+ },
61
+ required: ['code', 'message'],
62
+ },
63
+ },
64
+ };
65
+ /** An output schema with `configWarnings` added to its properties. */
66
+ export function withConfigWarningsSchema(schema) {
67
+ const own = schema;
68
+ return {
69
+ ...schema,
70
+ properties: { ...own.properties, ...CONFIG_WARNINGS_OUTPUT_SCHEMA },
71
+ };
72
+ }
73
+ /**
74
+ * Adds `configWarnings` to a tool result and one `Config:` line to its
75
+ * summary; returns the result unchanged when there are none or when the result
76
+ * is no object.
77
+ */
78
+ export function withConfigWarnings(result, warnings) {
79
+ if (warnings.length === 0 || typeof result !== 'object' || result === null || Array.isArray(result)) {
80
+ return result;
81
+ }
82
+ const record = result;
83
+ const summary = record['summary'];
84
+ const line = configWarningsLine(warnings, true);
85
+ return {
86
+ ...record,
87
+ ...(typeof summary === 'string' ? { summary: `${summary}\n${line}` } : {}),
88
+ configWarnings: warnings.map((w) => ({ ...w })),
89
+ };
90
+ }
91
+ /**
92
+ * The summary line of config warnings: their count and the first message;
93
+ * `inField` points to `configWarnings`, which an error answer does not carry.
94
+ */
95
+ export function configWarningsLine(warnings, inField) {
96
+ const where = inField ? ', see configWarnings' : '';
97
+ return `Config: ${warnings.length} warning(s)${where}: ${warnings[0]?.message ?? ''}`;
98
+ }
32
99
  //# sourceMappingURL=output-contract.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Anonymization of learn-patterns examples: file paths and code.
3
+ *
4
+ * `strict` hashes file paths and renames every identifier, string literal
5
+ * and template text in code deterministically (same name, same alias in
6
+ * every example and run) and drops comments; framework names stay.
7
+ * `moderate` makes file paths project-relative and keeps the code.
8
+ * `minimal` keeps both as they are.
9
+ */
10
+ /** Anonymization level of learn-patterns. */
11
+ export type AnonymizationLevel = 'strict' | 'moderate' | 'minimal';
12
+ /**
13
+ * File path of an example: hashed (`strict`), project-relative (`moderate`)
14
+ * or unchanged (`minimal`).
15
+ */
16
+ export declare function anonymizeFilePath(filePath: string, projectRoot: string, level: AnonymizationLevel): string;
17
+ /**
18
+ * Code of an example. `strict` renames identifiers, string literals and
19
+ * template text and drops comments; the other levels keep the code.
20
+ */
21
+ export declare function anonymizeCode(code: string, level: AnonymizationLevel): string;
22
+ /**
23
+ * Metadata of an example. `strict` anonymizes string values like code
24
+ * (class and property names get the same alias as in the code).
25
+ */
26
+ export declare function anonymizeMetadata(metadata: Record<string, unknown>, level: AnonymizationLevel): Record<string, unknown>;
27
+ //# sourceMappingURL=pattern-anonymizer.d.ts.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Anonymization of learn-patterns examples: file paths and code.
3
+ *
4
+ * `strict` hashes file paths and renames every identifier, string literal
5
+ * and template text in code deterministically (same name, same alias in
6
+ * every example and run) and drops comments; framework names stay.
7
+ * `moderate` makes file paths project-relative and keeps the code.
8
+ * `minimal` keeps both as they are.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { extname, relative, resolve, sep } from 'node:path';
12
+ import { ts } from 'ts-morph';
13
+ /** Angular, RxJS, TypeScript and JavaScript names that stay readable. */
14
+ const PRESERVED_IDENTIFIERS = new Set([
15
+ // Angular decorators, metadata keys and APIs
16
+ 'Component', 'Injectable', 'Directive', 'Pipe', 'NgModule', 'Input', 'Output', 'HostListener',
17
+ 'HostBinding', 'ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren', 'Inject', 'Optional',
18
+ 'Self', 'SkipSelf', 'Host', 'selector', 'template', 'templateUrl', 'styles', 'styleUrl', 'styleUrls',
19
+ 'standalone', 'imports', 'exports', 'declarations', 'providers', 'bootstrap', 'providedIn',
20
+ 'changeDetection', 'ChangeDetectionStrategy', 'OnPush', 'Default', 'ChangeDetectorRef', 'EventEmitter',
21
+ 'inject', 'signal', 'computed', 'effect', 'input', 'output', 'model', 'OnInit', 'OnDestroy', 'OnChanges',
22
+ 'AfterViewInit', 'AfterContentInit', 'DoCheck', 'ngOnInit', 'ngOnDestroy', 'ngOnChanges', 'ngAfterViewInit',
23
+ 'ngAfterContentInit', 'ngDoCheck', 'SimpleChanges', 'ElementRef', 'Injector', 'InjectionToken',
24
+ 'HttpClient', 'Router', 'ActivatedRoute', 'FormBuilder', 'FormGroup', 'FormControl', 'Validators',
25
+ 'CommonModule', 'RouterModule', 'BrowserModule', 'Service',
26
+ // RxJS
27
+ 'Observable', 'Subject', 'BehaviorSubject', 'ReplaySubject', 'AsyncSubject', 'Subscription', 'of', 'from',
28
+ 'subscribe', 'unsubscribe', 'pipe', 'next', 'error', 'complete', 'map', 'filter', 'switchMap', 'mergeMap',
29
+ 'concatMap', 'exhaustMap', 'takeUntil', 'take', 'tap', 'catchError', 'debounceTime', 'distinctUntilChanged',
30
+ 'combineLatest', 'forkJoin', 'firstValueFrom', 'lastValueFrom', 'takeUntilDestroyed', 'asObservable',
31
+ // TypeScript and JavaScript
32
+ 'undefined', 'NaN', 'Infinity', 'console', 'log', 'warn', 'Promise', 'Array', 'Object', 'String', 'Number',
33
+ 'Boolean', 'Date', 'Math', 'JSON', 'Error', 'Map', 'Set', 'Record', 'Partial', 'Readonly', 'Pick', 'Omit',
34
+ 'length', 'push', 'reduce', 'forEach', 'find', 'some', 'every', 'includes', 'indexOf', 'slice', 'concat',
35
+ 'join', 'keys', 'values', 'entries', 'then', 'catch', 'finally', 'get', 'has', 'add', 'delete', 'clear',
36
+ 'size', 'toString', 'emit',
37
+ ]);
38
+ /** String values that stay readable (DI scopes). */
39
+ const PRESERVED_STRINGS = new Set(['root', 'any', 'platform']);
40
+ /** Module specifiers of framework packages stay readable. */
41
+ function isFrameworkModule(value) {
42
+ return value.startsWith('@angular/') || value === 'rxjs' || value.startsWith('rxjs/') || value === 'tslib';
43
+ }
44
+ function hash(value, length) {
45
+ return createHash('sha256').update(value).digest('hex').slice(0, length);
46
+ }
47
+ /** Deterministic alias of an identifier, keeping the case of its first letter. */
48
+ function identifierAlias(name) {
49
+ const isPrivate = name.startsWith('#');
50
+ const bare = isPrivate ? name.slice(1) : name;
51
+ const first = bare.charAt(0);
52
+ const prefix = first !== first.toLowerCase() ? 'Name' : 'name';
53
+ return `${isPrivate ? '#' : ''}${prefix}_${hash(bare, 8)}`;
54
+ }
55
+ function stringAlias(value) {
56
+ return `str_${hash(value, 8)}`;
57
+ }
58
+ /**
59
+ * File path of an example: hashed (`strict`), project-relative (`moderate`)
60
+ * or unchanged (`minimal`).
61
+ */
62
+ export function anonymizeFilePath(filePath, projectRoot, level) {
63
+ if (level === 'minimal') {
64
+ return filePath;
65
+ }
66
+ const projectRelative = relative(resolve(projectRoot), resolve(filePath)).split(sep).join('/');
67
+ if (level === 'moderate') {
68
+ return projectRelative;
69
+ }
70
+ return `file-${hash(projectRelative, 12)}${extname(filePath)}`;
71
+ }
72
+ function commentRanges(sourceFile, code) {
73
+ const seen = new Map();
74
+ const collect = (ranges) => {
75
+ for (const range of ranges ?? []) {
76
+ seen.set(range.pos, range);
77
+ }
78
+ };
79
+ const visit = (node) => {
80
+ collect(ts.getLeadingCommentRanges(code, node.pos));
81
+ collect(ts.getTrailingCommentRanges(code, node.end));
82
+ for (const child of node.getChildren(sourceFile)) {
83
+ visit(child);
84
+ }
85
+ };
86
+ visit(sourceFile);
87
+ return [...seen.values()];
88
+ }
89
+ function templateEdit(node, sourceFile) {
90
+ const start = node.getStart(sourceFile);
91
+ const opening = node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral ? '`' : '}';
92
+ const closing = node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.TemplateMiddle ? '${' : '`';
93
+ return { start, end: node.end, text: `${opening}${stringAlias(node.text)}${closing}` };
94
+ }
95
+ function literalEdit(node, sourceFile) {
96
+ if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) {
97
+ const name = node.text;
98
+ if (PRESERVED_IDENTIFIERS.has(name)) {
99
+ return undefined;
100
+ }
101
+ return { start: node.getStart(sourceFile), end: node.end, text: identifierAlias(name) };
102
+ }
103
+ if (ts.isStringLiteral(node)) {
104
+ if (PRESERVED_STRINGS.has(node.text) || isFrameworkModule(node.text)) {
105
+ return undefined;
106
+ }
107
+ const start = node.getStart(sourceFile);
108
+ const quote = sourceFile.text.charAt(start);
109
+ return { start, end: node.end, text: `${quote}${stringAlias(node.text)}${quote}` };
110
+ }
111
+ if (ts.isNoSubstitutionTemplateLiteral(node) ||
112
+ ts.isTemplateHead(node) ||
113
+ ts.isTemplateMiddle(node) ||
114
+ ts.isTemplateTail(node)) {
115
+ return templateEdit(node, sourceFile);
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Code of an example. `strict` renames identifiers, string literals and
121
+ * template text and drops comments; the other levels keep the code.
122
+ */
123
+ export function anonymizeCode(code, level) {
124
+ if (level !== 'strict' || code === '') {
125
+ return code;
126
+ }
127
+ const sourceFile = ts.createSourceFile('example.ts', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
128
+ const comments = commentRanges(sourceFile, code);
129
+ const inComment = (pos) => comments.some((c) => pos >= c.pos && pos < c.end);
130
+ const edits = comments.map((c) => ({ start: c.pos, end: c.end, text: '' }));
131
+ const visit = (node) => {
132
+ if (ts.isJSDoc(node)) {
133
+ return;
134
+ }
135
+ const edit = literalEdit(node, sourceFile);
136
+ if (edit !== undefined && !inComment(edit.start)) {
137
+ edits.push(edit);
138
+ return;
139
+ }
140
+ ts.forEachChild(node, visit);
141
+ };
142
+ visit(sourceFile);
143
+ let result = code;
144
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
145
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
146
+ }
147
+ return result;
148
+ }
149
+ /**
150
+ * Metadata of an example. `strict` anonymizes string values like code
151
+ * (class and property names get the same alias as in the code).
152
+ */
153
+ export function anonymizeMetadata(metadata, level) {
154
+ if (level !== 'strict') {
155
+ return metadata;
156
+ }
157
+ return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, typeof value === 'string' ? anonymizeCode(value, level) : value]));
158
+ }
159
+ //# sourceMappingURL=pattern-anonymizer.js.map
@@ -195,10 +195,11 @@ export declare class ProjectCache {
195
195
  /** Eviction count and the most recent eviction. */
196
196
  get evictions(): EvictionStats;
197
197
  /**
198
- * Warnings about the loaded project for `tsConfigPath`: today the library
199
- * imports that do not resolve (missing or incomplete node_modules). Checked
200
- * once per load, on the first call, and kept until the project is reloaded;
201
- * empty when the project is not cached.
198
+ * Warnings about the loaded project for `tsConfigPath`: program files that
199
+ * could not be read and were left out, and the library imports that do not
200
+ * resolve (missing or incomplete node_modules). Checked once per load, on
201
+ * the first call, and kept until the project is reloaded; empty when the
202
+ * project is not cached.
202
203
  */
203
204
  warnings(tsConfigPath: string): string[];
204
205
  /** Cached projects, least recently used first. */
@@ -1,5 +1,6 @@
1
1
  import { statSync } from 'node:fs';
2
2
  import { Project, ts } from 'ts-morph';
3
+ import { addReadableSourceFiles, unreadableFilesWarning, } from '@angular-modernizer/core';
3
4
  import { findUnresolvedLibraryImports, libraryImportWarning, } from './library-imports.js';
4
5
  /** Thrown by `acquire()` when its signal aborts. */
5
6
  export class ProjectLoadCancelledError extends Error {
@@ -140,7 +141,7 @@ export class ProjectCache {
140
141
  // would stack two large programs before the check below evicts one.
141
142
  this.evictOverHeap(tsConfigPath);
142
143
  const heapBefore = this.memory.usage().heapUsed;
143
- project = this.store(tsConfigPath, mtimeMs, heapBefore, runToEnd(this.loadSteps(tsConfigPath)));
144
+ project = this.store(tsConfigPath, mtimeMs, heapBefore, runToEnd(this.loadSteps(tsConfigPath))).project;
144
145
  }
145
146
  this.evictOverCount();
146
147
  this.evictOverHeap(tsConfigPath);
@@ -195,10 +196,11 @@ export class ProjectCache {
195
196
  : { count: this.evictionCount, last: this.lastEviction };
196
197
  }
197
198
  /**
198
- * Warnings about the loaded project for `tsConfigPath`: today the library
199
- * imports that do not resolve (missing or incomplete node_modules). Checked
200
- * once per load, on the first call, and kept until the project is reloaded;
201
- * empty when the project is not cached.
199
+ * Warnings about the loaded project for `tsConfigPath`: program files that
200
+ * could not be read and were left out, and the library imports that do not
201
+ * resolve (missing or incomplete node_modules). Checked once per load, on
202
+ * the first call, and kept until the project is reloaded; empty when the
203
+ * project is not cached.
202
204
  */
203
205
  warnings(tsConfigPath) {
204
206
  const entry = this.entries.get(tsConfigPath);
@@ -207,7 +209,7 @@ export class ProjectCache {
207
209
  }
208
210
  if (entry.warnings === undefined) {
209
211
  const warning = libraryImportWarning(findUnresolvedLibraryImports(entry.project, tsConfigPath));
210
- entry.warnings = warning === undefined ? [] : [warning];
212
+ entry.warnings = [unreadableFilesWarning(entry.unreadableFiles), warning].filter((w) => w !== undefined);
211
213
  }
212
214
  return [...entry.warnings];
213
215
  }
@@ -284,17 +286,18 @@ export class ProjectCache {
284
286
  */
285
287
  *loadSteps(tsConfigPath) {
286
288
  if (this.createProject !== undefined) {
287
- return this.createProject(tsConfigPath);
289
+ return { project: this.createProject(tsConfigPath), unreadableFiles: [] };
288
290
  }
289
291
  const { project, files } = this.openProject(tsConfigPath);
292
+ // A file that cannot be read (EACCES) is left out and reported, as the
293
+ // scans skip it; it still counts for the load progress
294
+ const unreadableFiles = [];
290
295
  for (let start = 0; start < files.length; start += this.batchSize) {
291
- for (const filePath of files.slice(start, start + this.batchSize)) {
292
- project.addSourceFileAtPath(filePath);
293
- }
296
+ unreadableFiles.push(...addReadableSourceFiles(project, files.slice(start, start + this.batchSize)));
294
297
  yield [Math.min(start + this.batchSize, files.length), files.length];
295
298
  }
296
299
  project.resolveSourceFileDependencies();
297
- return project;
300
+ return { project, unreadableFiles };
298
301
  }
299
302
  startLoad(tsConfigPath, mtimeMs) {
300
303
  const state = { waiters: new Set(), cancelled: false };
@@ -325,14 +328,14 @@ export class ProjectCache {
325
328
  this.stopIfCancelled(tsConfigPath, job);
326
329
  step = steps.next();
327
330
  }
328
- const project = step.value;
331
+ const loaded = step.value;
329
332
  await nextTurn();
330
333
  this.stopIfCancelled(tsConfigPath, job);
331
- project.getProgram().compilerObject.getTypeChecker();
334
+ loaded.project.getProgram().compilerObject.getTypeChecker();
332
335
  const cached = this.entries.get(tsConfigPath);
333
336
  const result = cached?.mtimeMs === mtimeMs
334
337
  ? cached.project
335
- : this.store(tsConfigPath, mtimeMs, heapBefore, project);
338
+ : this.store(tsConfigPath, mtimeMs, heapBefore, loaded).project;
336
339
  this.evictOverCount();
337
340
  this.evictOverHeap(tsConfigPath);
338
341
  return result;
@@ -371,10 +374,12 @@ export class ProjectCache {
371
374
  .finally(() => signal.removeEventListener('abort', onAbort));
372
375
  });
373
376
  }
374
- store(tsConfigPath, mtimeMs, heapBefore, project) {
377
+ store(tsConfigPath, mtimeMs, heapBefore, loaded) {
378
+ const { project, unreadableFiles } = loaded;
375
379
  const now = new Date();
376
380
  this.entries.set(tsConfigPath, {
377
381
  project,
382
+ unreadableFiles,
378
383
  mtimeMs,
379
384
  loadedAt: now,
380
385
  lastUsedAt: now,
@@ -382,7 +387,7 @@ export class ProjectCache {
382
387
  fileMtimes: this.recordMtimes(project),
383
388
  refreshedFiles: 0,
384
389
  });
385
- return project;
390
+ return loaded;
386
391
  }
387
392
  evictOverCount() {
388
393
  for (const key of this.entries.keys()) {