@angular-modernizer/adapter-mcp 1.1.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 (144) hide show
  1. package/CHANGELOG.md +662 -0
  2. package/README.md +86 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +10 -1
  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 +9 -6
  21. package/dist/tools/analyze-build-impact.js +14 -7
  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 +35 -6
  27. package/dist/tools/analyze-project.js +141 -36
  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.d.ts +2 -2
  33. package/dist/tools/find-angular-symbol.js +6 -5
  34. package/dist/tools/find-component-hosts.d.ts +2 -2
  35. package/dist/tools/find-component-hosts.js +6 -5
  36. package/dist/tools/find-usages.d.ts +2 -2
  37. package/dist/tools/find-usages.js +24 -15
  38. package/dist/tools/get-bootstrap-execution.d.ts +2 -2
  39. package/dist/tools/get-bootstrap-execution.js +3 -3
  40. package/dist/tools/get-call-graph.d.ts +2 -2
  41. package/dist/tools/get-call-graph.js +18 -5
  42. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  43. package/dist/tools/get-operation-progress-tool.js +2 -2
  44. package/dist/tools/get-operation-progress.d.ts +4 -1
  45. package/dist/tools/get-operation-progress.js +6 -2
  46. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  47. package/dist/tools/helpers/analysis-output.js +22 -1
  48. package/dist/tools/helpers/build-cache.d.ts +27 -0
  49. package/dist/tools/helpers/build-cache.js +86 -0
  50. package/dist/tools/helpers/class-filter.d.ts +18 -0
  51. package/dist/tools/helpers/class-filter.js +30 -0
  52. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  53. package/dist/tools/helpers/cli-arguments.js +35 -0
  54. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  55. package/dist/tools/helpers/feedback-catalog.js +196 -0
  56. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  57. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  58. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  59. package/dist/tools/helpers/file-type-check.js +56 -0
  60. package/dist/tools/helpers/output-contract.d.ts +42 -0
  61. package/dist/tools/helpers/output-contract.js +54 -0
  62. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  63. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  64. package/dist/tools/helpers/project-cache.d.ts +78 -6
  65. package/dist/tools/helpers/project-cache.js +205 -15
  66. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  67. package/dist/tools/helpers/project-decorators.js +13 -6
  68. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  69. package/dist/tools/helpers/refresh-apply.js +460 -0
  70. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  71. package/dist/tools/helpers/refresh-inventory.js +610 -0
  72. package/dist/tools/helpers/rule-runner.js +3 -1
  73. package/dist/tools/helpers/scan-cache.d.ts +74 -5
  74. package/dist/tools/helpers/scan-cache.js +134 -6
  75. package/dist/tools/helpers/scan-engine.d.ts +30 -6
  76. package/dist/tools/helpers/scan-engine.js +131 -22
  77. package/dist/tools/helpers/scan-plan.d.ts +1 -1
  78. package/dist/tools/helpers/scan-plan.js +16 -2
  79. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  80. package/dist/tools/helpers/source-map-loader.js +226 -0
  81. package/dist/tools/helpers/template-check.d.ts +76 -0
  82. package/dist/tools/helpers/template-check.js +158 -0
  83. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  84. package/dist/tools/helpers/tool-cache.js +9 -3
  85. package/dist/tools/helpers/tool-context.d.ts +18 -0
  86. package/dist/tools/helpers/tool-context.js +29 -0
  87. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  88. package/dist/tools/helpers/transform-safety.js +357 -4
  89. package/dist/tools/inspect-form-group.d.ts +2 -2
  90. package/dist/tools/inspect-form-group.js +8 -3
  91. package/dist/tools/inspect-i18n.d.ts +2 -2
  92. package/dist/tools/inspect-i18n.js +3 -3
  93. package/dist/tools/inspect-template.d.ts +2 -2
  94. package/dist/tools/inspect-template.js +11 -5
  95. package/dist/tools/learn-patterns.d.ts +43 -28
  96. package/dist/tools/learn-patterns.js +83 -161
  97. package/dist/tools/list-imports.d.ts +2 -2
  98. package/dist/tools/list-imports.js +3 -3
  99. package/dist/tools/orchestrate-migration.d.ts +19 -1
  100. package/dist/tools/orchestrate-migration.js +52 -10
  101. package/dist/tools/parse-stack-trace.d.ts +48 -1
  102. package/dist/tools/parse-stack-trace.js +108 -9
  103. package/dist/tools/plan-migration.d.ts +2 -2
  104. package/dist/tools/plan-migration.js +25 -12
  105. package/dist/tools/refresh-state.d.ts +378 -0
  106. package/dist/tools/refresh-state.js +370 -0
  107. package/dist/tools/resolve-type.d.ts +2 -2
  108. package/dist/tools/resolve-type.js +13 -6
  109. package/dist/tools/review-feedback.d.ts +42 -7
  110. package/dist/tools/review-feedback.js +24 -17
  111. package/dist/tools/rollback-changes.d.ts +5 -0
  112. package/dist/tools/rollback-changes.js +7 -2
  113. package/dist/tools/run-angular-cli.js +36 -22
  114. package/dist/tools/run-build.d.ts +33 -28
  115. package/dist/tools/run-build.js +136 -438
  116. package/dist/tools/run-schematic.d.ts +8 -2
  117. package/dist/tools/run-schematic.js +80 -50
  118. package/dist/tools/scan-all.d.ts +31 -15
  119. package/dist/tools/scan-all.js +75 -109
  120. package/dist/tools/scan-angular.d.ts +27 -14
  121. package/dist/tools/scan-angular.js +70 -92
  122. package/dist/tools/scan-architecture.d.ts +29 -12
  123. package/dist/tools/scan-architecture.js +205 -135
  124. package/dist/tools/scan-solid.d.ts +27 -14
  125. package/dist/tools/scan-solid.js +73 -89
  126. package/dist/tools/search-codebase.d.ts +8 -3
  127. package/dist/tools/search-codebase.js +16 -10
  128. package/dist/tools/suggest-improvements.d.ts +34 -3
  129. package/dist/tools/suggest-improvements.js +34 -9
  130. package/dist/tools/trace-output-flow.d.ts +2 -2
  131. package/dist/tools/trace-output-flow.js +6 -5
  132. package/dist/tools/transform-code-batch.d.ts +9 -9
  133. package/dist/tools/transform-code.d.ts +161 -12
  134. package/dist/tools/transform-code.js +782 -197
  135. package/dist/tools/validate-before-transform.js +2 -1
  136. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  137. package/dist/tools/validate-project-compatibility.js +33 -225
  138. package/dist/tools/validate-transformation.d.ts +40 -26
  139. package/dist/tools/validate-transformation.js +115 -294
  140. package/dist/tools/verify-citations.js +8 -2
  141. package/dist/types.d.ts +9 -9
  142. package/dist/utils/format-tool-response.d.ts +3 -1
  143. package/dist/utils/format-tool-response.js +8 -3
  144. package/package.json +14 -13
@@ -1,37 +1,32 @@
1
- import { spawn, execSync } from 'node:child_process';
2
- import { existsSync, readFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { loadConfig, processGroupOptions, terminateOnAbort, terminateProcessTree, } from '@angular-modernizer/core';
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { appendBuildArguments, loadConfig, noColorEnv, processGroupOptions, projectBinPath, resolveBuildCommand, stripAnsi, terminateOnAbort, terminateProcessTree, } from '@angular-modernizer/core';
5
4
  import { INCOMPATIBILITY_ISSUES_SCHEMA } from './helpers/build-schemas.js';
5
+ import { clearBuildCaches } from './helpers/build-cache.js';
6
6
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
7
7
  import { outputTail, seconds } from './helpers/process-output.js';
8
8
  /** Build warnings spelled out in the summary; the rest is in `warnings`. */
9
9
  const SUMMARY_BUILD_WARNINGS = 5;
10
- /** Text summary: outcome, build mode, warnings, blockers and the tail of the output on failure. */
10
+ /** Default build timeout when neither the call nor the config sets one. */
11
+ const DEFAULT_TIMEOUT_MS = 300000;
12
+ /** Where the deprecation notices send the caller for scope information. */
13
+ const SCOPE_HINT = 'run-build always runs the project build command; analyze-build-impact lists the affected files';
14
+ /** Text summary: outcome, warnings and the tail of the output on failure. */
11
15
  function describeBuild(result) {
12
16
  const ending = result.timedOut === true
13
17
  ? `timed out after ${seconds(result.executionTime)}`
14
18
  : `exited ${result.exitCode} after ${seconds(result.executionTime)}`;
15
- const lines = [
16
- `Build ${result.success ? 'passed' : 'failed'} (${result.buildSystem}): \`${result.fullCommand}\` ${ending}.`,
17
- ];
18
- const inc = result.incremental;
19
- if (inc !== undefined) {
20
- lines.push(inc.enabled
21
- ? `Incremental (${inc.scope ?? 'unknown scope'}): ${inc.filesBuilt ?? 0} file(s) built, ` +
22
- `${inc.filesSkipped ?? 0} skipped${inc.speedup === undefined ? '' : `; ${inc.speedup}`}.`
23
- : `Full build${inc.fallbackReason === undefined ? '' : `: ${inc.fallbackReason}`}.`);
24
- }
25
- const blockers = (result.incompatibilityIssues ?? []).filter((i) => i.detected && i.severity === 'blocker');
26
- if (blockers.length > 0) {
27
- lines.push(`Blockers for incremental builds: ${blockers.map((b) => b.type).join(', ')}.`);
28
- }
19
+ const lines = result.fullCommand === ''
20
+ ? [`Build failed: ${result.errors}`]
21
+ : [
22
+ `Build ${result.success ? 'passed' : 'failed'} (${result.buildSystem}): \`${result.fullCommand}\` ${ending}.`,
23
+ ];
29
24
  const warnings = result.warnings ?? [];
30
25
  if (warnings.length > 0) {
31
- lines.push(`${warnings.length} build warning(s):`);
26
+ lines.push(`${warnings.length} warning(s):`);
32
27
  lines.push(...warnings.slice(0, SUMMARY_BUILD_WARNINGS).map((w) => `- ${w}`));
33
28
  }
34
- if (!result.success) {
29
+ if (!result.success && result.fullCommand !== '') {
35
30
  const tail = outputTail(result.errors) ?? outputTail(result.output);
36
31
  if (tail !== undefined) {
37
32
  lines.push(`Last output:\n${tail}`);
@@ -39,10 +34,31 @@ function describeBuild(result) {
39
34
  }
40
35
  return lines.join('\n');
41
36
  }
37
+ /** Deprecation notices for the parameters that no longer have an effect. */
38
+ function deprecationWarnings(params) {
39
+ const deprecated = [];
40
+ if (params.incrementalMode !== undefined) {
41
+ deprecated.push('incrementalMode');
42
+ }
43
+ if (params.forceFullBuild !== undefined) {
44
+ deprecated.push('forceFullBuild');
45
+ }
46
+ if (params.changedFiles !== undefined) {
47
+ deprecated.push('changedFiles');
48
+ }
49
+ if (params.cacheStrategy === 'skip') {
50
+ deprecated.push("cacheStrategy 'skip'");
51
+ }
52
+ return deprecated.map((name) => `${name} is deprecated and has no effect: ${SCOPE_HINT}.`);
53
+ }
54
+ /** Build system reported for a command source. */
55
+ function buildSystemOf(source) {
56
+ return source === 'package-script' ? 'npm' : source;
57
+ }
42
58
  /**
43
59
  * MCP tool for executing build systems and validating code transformations.
44
- * Supports Angular CLI, Nx, Webpack, Vite, and auto-detection.
45
- * Includes incremental build mode for efficient validation.
60
+ * Runs the project's build command: `build.command` of the project config,
61
+ * else the detected build system, else the `build` script of package.json.
46
62
  */
47
63
  export class RunBuildTool {
48
64
  name = 'run-build';
@@ -53,8 +69,8 @@ export class RunBuildTool {
53
69
  idempotentHint: true,
54
70
  openWorldHint: false,
55
71
  };
56
- description = 'Execute build systems to validate code transformations. Supports incremental mode for 2-4x faster builds by validating only changed files and their dependencies. Automatically detects incompatibilities and falls back to full build when needed. ' +
57
- 'The result has the full build output; summary is a short text with the outcome, the build mode and, on failure, the last output lines.';
72
+ description = "Run the project's build to validate code transformations: build.command of .angular-modernizer.json, else the detected build system (Angular CLI, Nx, Vite, Webpack), else the build script of package.json, with the project's node_modules/.bin on PATH and the Angular build cache on. Every call is a full build; analyze-build-impact lists the files a change affects. " +
73
+ 'The result has the full build output; summary is a short text with the outcome and, on failure, the last output lines.';
58
74
  /**
59
75
  * JSON Schema of the tool arguments.
60
76
  * @hidden
@@ -69,27 +85,29 @@ export class RunBuildTool {
69
85
  },
70
86
  buildSystem: {
71
87
  type: 'string',
72
- description: 'Build system to use',
88
+ description: "Build system to use; 'auto-detect' runs the project's build command (build.command first)",
73
89
  enum: ['auto-detect', 'angular-cli', 'nx', 'webpack', 'vite'],
74
90
  default: 'auto-detect',
75
91
  },
76
92
  incrementalMode: {
77
93
  type: 'boolean',
78
- description: 'Enable incremental build mode (default: true). Auto-detects changed files and validates only affected code for 2-4x faster builds.',
94
+ description: 'Deprecated, no effect: every call runs the full build command. Use analyze-build-impact for the affected files.',
95
+ deprecated: true,
79
96
  },
80
97
  changedFiles: {
81
98
  type: 'array',
82
99
  items: { type: 'string' },
83
- description: 'List of changed files to validate (optional, auto-detected from git if not provided)',
100
+ description: 'Deprecated, no effect: use analyze-build-impact for the affected files.',
101
+ deprecated: true,
84
102
  },
85
103
  forceFullBuild: {
86
104
  type: 'boolean',
87
- description: 'Force full build even if incremental is available',
88
- default: false,
105
+ description: 'Deprecated, no effect: every call is a full build.',
106
+ deprecated: true,
89
107
  },
90
108
  cacheStrategy: {
91
109
  type: 'string',
92
- description: 'Cache strategy for incremental builds',
110
+ description: "'clear' removes .angular/cache (and .nx/cache in an Nx workspace) inside the project before the build, never under node_modules; 'skip' is deprecated and has no effect",
93
111
  enum: ['use', 'clear', 'skip'],
94
112
  default: 'use',
95
113
  },
@@ -98,7 +116,7 @@ export class RunBuildTool {
98
116
  properties: {
99
117
  configuration: {
100
118
  type: 'string',
101
- description: 'Build configuration',
119
+ description: 'Build configuration, passed as --configuration',
102
120
  },
103
121
  watch: {
104
122
  type: 'boolean',
@@ -107,8 +125,7 @@ export class RunBuildTool {
107
125
  },
108
126
  timeout: {
109
127
  type: 'number',
110
- description: 'Command timeout in ms',
111
- default: 300000, // 5 minutes
128
+ description: 'Command timeout in ms (default: build.timeout of the project config, else 300000); the build is stopped then',
112
129
  },
113
130
  args: {
114
131
  type: 'array',
@@ -129,6 +146,7 @@ export class RunBuildTool {
129
146
  properties: {
130
147
  success: { type: 'boolean' },
131
148
  buildSystem: { type: 'string' },
149
+ commandSource: { type: 'string' },
132
150
  command: { type: 'string' },
133
151
  fullCommand: { type: 'string' },
134
152
  exitCode: { type: 'integer' },
@@ -140,10 +158,11 @@ export class RunBuildTool {
140
158
  warnings: {
141
159
  type: 'array',
142
160
  items: { type: 'string' },
143
- description: 'Warnings the build printed.',
161
+ description: 'Warnings the build printed, cache warnings and deprecation notices.',
144
162
  },
145
163
  incremental: {
146
164
  type: 'object',
165
+ description: 'Deprecated, no longer set.',
147
166
  properties: {
148
167
  enabled: { type: 'boolean' },
149
168
  scope: { type: 'string' },
@@ -180,371 +199,80 @@ export class RunBuildTool {
180
199
  throw new Error('rootPath is required');
181
200
  }
182
201
  const rootPath = params.rootPath;
202
+ if (!existsSync(rootPath)) {
203
+ throw new Error(`rootPath does not exist: ${rootPath}`);
204
+ }
183
205
  // Load config from .angular-modernizer.json and merge with params
184
206
  const fullConfig = loadConfig(rootPath);
185
207
  const config = fullConfig.tools?.['run-build'] ?? {};
186
208
  const mergedParams = { ...config, ...params };
187
- const buildSystem = mergedParams.buildSystem ?? 'auto-detect';
188
- const options = mergedParams.options ?? {};
189
- const timeout = options.timeout ?? 300000; // 5 minutes default
190
- // Incremental mode handling
191
- const forceFullBuild = mergedParams.forceFullBuild ?? false;
192
- let incrementalMode = mergedParams.incrementalMode;
193
- try {
194
- // Detect build system if auto-detect
195
- const systemInfo = buildSystem === 'auto-detect'
196
- ? this.detectBuildSystem(rootPath)
197
- : {
198
- system: buildSystem,
199
- confidence: 1,
200
- configFiles: [],
201
- buildCommand: this.getDefaultBuildCommand(buildSystem),
202
- };
203
- // Only support incremental mode for Angular CLI
204
- const supportsIncremental = systemInfo.system === 'angular-cli';
205
- // Auto-detect incremental mode if not specified
206
- if (incrementalMode === undefined &&
207
- supportsIncremental &&
208
- !forceFullBuild) {
209
- const changedFiles = await this.detectChangedFiles(rootPath);
210
- incrementalMode = changedFiles.length > 0 && changedFiles.length < 50;
211
- }
212
- // Determine if we should attempt incremental build
213
- const attemptIncremental = supportsIncremental && incrementalMode === true && !forceFullBuild;
214
- let incrementalMetadata;
215
- let incompatibilityIssues;
216
- // Attempt incremental build if enabled
217
- if (attemptIncremental) {
218
- try {
219
- return await this.executeIncrementalBuild(rootPath, params, systemInfo, options, timeout, signal);
220
- }
221
- catch (error) {
222
- // A cancelled build stops; any other error falls back to a full build
223
- if (signal?.aborted === true) {
224
- throw error;
225
- }
226
- incrementalMetadata = {
227
- enabled: false,
228
- fallbackReason: error instanceof Error
229
- ? error.message
230
- : 'Incremental build failed',
231
- };
232
- }
233
- }
234
- // Execute full build (either requested or fallback)
235
- const buildArgs = this.buildCommandArgs(systemInfo.buildCommand, options);
236
- const startTime = Date.now();
237
- const result = await this.executeBuildCommand(buildArgs, {
238
- cwd: rootPath,
239
- timeout,
240
- signal,
241
- });
242
- const executionTime = Date.now() - startTime;
243
- const { warnings, artifacts } = this.parseBuildOutput(result.stdout);
244
- // Add incremental metadata if we tried incremental mode
245
- if (incrementalMode !== undefined) {
246
- incrementalMetadata = incrementalMetadata ?? {
247
- enabled: false,
248
- fallbackReason: forceFullBuild
249
- ? 'Full build forced by user'
250
- : !supportsIncremental
251
- ? 'Build system does not support incremental builds'
252
- : 'Incremental mode disabled',
253
- };
254
- }
255
- return {
256
- success: result.exitCode === 0,
257
- buildSystem: systemInfo.system,
258
- command: buildArgs[0] ?? 'unknown',
259
- fullCommand: buildArgs.join(' '),
260
- exitCode: result.exitCode,
261
- output: result.stdout,
262
- errors: result.stderr,
263
- executionTime,
264
- artifacts,
265
- warnings,
266
- incremental: incrementalMetadata,
267
- incompatibilityIssues,
268
- };
269
- }
270
- catch (error) {
271
- if (error instanceof Error && error.message.includes('timeout')) {
272
- return {
273
- success: false,
274
- buildSystem: buildSystem === 'auto-detect' ? 'unknown' : buildSystem,
275
- command: 'timeout',
276
- fullCommand: 'build command timed out',
277
- exitCode: -1,
278
- output: '',
279
- errors: 'Command timed out',
280
- executionTime: timeout,
281
- timedOut: true,
282
- };
283
- }
284
- throw new Error(`Build execution failed: ${error instanceof Error ? error.message : String(error)}`);
285
- }
286
- }
287
- /**
288
- * Detects changed files using git status
289
- */
290
- async detectChangedFiles(rootPath) {
291
- try {
292
- const output = execSync('git status --porcelain', {
293
- cwd: rootPath,
294
- encoding: 'utf-8',
295
- stdio: ['pipe', 'pipe', 'ignore'],
296
- });
297
- const lines = output.split('\n').filter((line) => line.trim());
298
- const changedFiles = [];
299
- for (const line of lines) {
300
- // Parse git status format: "XY filename"
301
- const match = /^\s*[MADRCU?!]{1,2}\s+(.+)$/.exec(line);
302
- if (match?.[1]) {
303
- changedFiles.push(match[1]);
304
- }
305
- }
306
- return changedFiles;
307
- }
308
- catch (error) {
309
- // Git not available or not a git repository
310
- // Log the reason for debugging but don't fail the build
311
- if (error instanceof Error) {
312
- // Silently fall back - this is expected in non-git projects
313
- // or when git is not installed
314
- }
315
- return [];
316
- }
317
- }
318
- /**
319
- * Executes an incremental build using IncompatibilityDetector and IncrementalBuildValidator
320
- */
321
- async executeIncrementalBuild(rootPath, params, systemInfo, options, timeout, signal) {
322
- // Dynamic import to avoid circular dependencies
323
- const { Project } = await import('ts-morph');
324
- const { IncompatibilityDetector, IncrementalBuildValidator, IncrementalAnalyzer, } = await import('@angular-modernizer/core');
325
- // Initialize ts-morph project
326
- const project = new Project({
327
- tsConfigFilePath: join(rootPath, 'tsconfig.json'),
328
- skipAddingFilesFromTsConfig: false,
329
- });
330
- // Check compatibility
331
- const detector = new IncompatibilityDetector(project, rootPath);
332
- const incompatibilityIssues = await detector.checkProjectCompatibility();
333
- // Check for blockers
334
- const blockers = incompatibilityIssues.filter((issue) => issue.severity === 'blocker' && issue.detected);
335
- if (blockers.length > 0) {
336
- // Fallback to full build - return as if incremental was disabled
337
- const fallbackReason = `Incompatible: ${blockers.map((b) => b.type).join(', ')}`;
338
- const buildArgs = this.buildCommandArgs(systemInfo.buildCommand, options);
339
- const startTime = Date.now();
340
- const result = await this.executeBuildCommand(buildArgs, {
341
- cwd: rootPath,
342
- timeout,
343
- signal,
344
- });
345
- const executionTime = Date.now() - startTime;
346
- const { warnings, artifacts } = this.parseBuildOutput(result.stdout);
347
- return {
348
- success: result.exitCode === 0,
349
- buildSystem: systemInfo.system,
350
- command: buildArgs[0] ?? 'unknown',
351
- fullCommand: buildArgs.join(' '),
352
- exitCode: result.exitCode,
353
- output: result.stdout,
354
- errors: result.stderr,
355
- executionTime,
356
- artifacts,
357
- warnings,
358
- incremental: {
359
- enabled: false,
360
- fallbackReason,
361
- },
362
- incompatibilityIssues,
363
- };
364
- }
365
- // Get changed files
366
- const changedFiles = params.changedFiles ?? (await this.detectChangedFiles(rootPath));
367
- if (changedFiles.length === 0) {
368
- // No changes detected, return success without building
209
+ const options = {
210
+ configuration: config.configuration,
211
+ watch: config.watch,
212
+ timeout: config.timeout,
213
+ ...params.options,
214
+ };
215
+ const timeout = options.timeout ?? fullConfig.build.timeout ?? DEFAULT_TIMEOUT_MS;
216
+ const warnings = deprecationWarnings(mergedParams);
217
+ const resolved = this.resolveCommand(rootPath, mergedParams.buildSystem ?? 'auto-detect');
218
+ if (resolved === undefined) {
369
219
  return {
370
- success: true,
371
- buildSystem: systemInfo.system,
372
- command: 'ng build',
373
- fullCommand: 'ng build --configuration development (skipped - no changes)',
374
- exitCode: 0,
375
- output: 'No changes detected, skipping build',
376
- errors: '',
220
+ success: false,
221
+ buildSystem: 'none',
222
+ command: '',
223
+ fullCommand: '',
224
+ exitCode: -1,
225
+ output: '',
226
+ errors: 'No build command: set build.command in .angular-modernizer.json, or add angular.json, nx.json, a Vite or Webpack config, or a build script to package.json.',
377
227
  executionTime: 0,
378
- artifacts: [],
379
- warnings: [],
380
- incremental: {
381
- enabled: true,
382
- scope: 'affected-only',
383
- filesBuilt: 0,
384
- filesSkipped: project.getSourceFiles().length,
385
- cacheHit: true,
386
- speedup: 'Build skipped (no changes)',
387
- },
388
- incompatibilityIssues: incompatibilityIssues.filter((i) => i.detected),
228
+ warnings,
389
229
  };
390
230
  }
391
- // Create incremental analyzer
392
- const { CacheManager, RealFileSystemAdapter } = await import('@angular-modernizer/core');
393
- const fileSystem = new RealFileSystemAdapter();
394
- const cacheManager = new CacheManager(fileSystem);
395
- const incrementalAnalyzer = new IncrementalAnalyzer(project, cacheManager);
396
- // Handle cache strategy
397
- const cacheStrategy = params.cacheStrategy ?? 'use';
398
- if (cacheStrategy === 'clear') {
399
- // Clear Angular cache before build
400
- const { execSync: execSyncImport } = await import('node:child_process');
401
- try {
402
- execSyncImport('rm -rf .angular/cache', {
403
- cwd: rootPath,
404
- stdio: 'ignore',
405
- });
406
- }
407
- catch {
408
- // Ignore cache clear errors
409
- }
231
+ // Caches inside the project only, never under node_modules
232
+ if (mergedParams.cacheStrategy === 'clear') {
233
+ warnings.push(...clearBuildCaches(rootPath).warnings);
410
234
  }
411
- // Create validator
412
- const validator = new IncrementalBuildValidator(incrementalAnalyzer, project);
413
- // Run validation
414
- const buildConfig = (options?.configuration ?? 'development');
415
- const validationResult = await validator.validate(rootPath, {
416
- buildConfig,
417
- baseBranch: 'HEAD',
418
- forceFiles: params.changedFiles,
419
- includeDependents: true,
235
+ const fullCommand = appendBuildArguments(resolved.command, [
236
+ ...(options.configuration === undefined
237
+ ? []
238
+ : ['--configuration', options.configuration]),
239
+ ...(options.watch === true ? ['--watch'] : []),
240
+ ...(options.args ?? []),
241
+ ]);
242
+ const startTime = Date.now();
243
+ const result = await this.executeBuildCommand(fullCommand, {
244
+ cwd: rootPath,
245
+ timeout,
420
246
  signal,
421
247
  });
422
- // Calculate speedup with better messaging
423
- const fullBuildEstimate = validationResult.scope.estimatedBuildTime * 1000;
424
- const actualTime = validationResult.metrics.totalTime;
425
- let speedup;
426
- if (fullBuildEstimate > 0 && actualTime > 0) {
427
- const speedupFactor = fullBuildEstimate / actualTime;
428
- const estimatedMinutes = Math.floor(fullBuildEstimate / 60000);
429
- const estimatedSeconds = Math.round((fullBuildEstimate % 60000) / 1000);
430
- const actualSeconds = Math.round(actualTime / 1000);
431
- if (speedupFactor >= 2) {
432
- // Significant speedup
433
- const timeStr = estimatedMinutes > 0
434
- ? `${estimatedMinutes}m ${estimatedSeconds}s`
435
- : `${estimatedSeconds}s`;
436
- speedup = `${speedupFactor.toFixed(1)}x faster (${actualSeconds}s vs ~${timeStr} full build)`;
437
- }
438
- else {
439
- // Modest speedup
440
- speedup = `${speedupFactor.toFixed(1)}x faster (${actualSeconds}s vs ${estimatedSeconds}s full build)`;
441
- }
442
- }
443
- else {
444
- speedup = `Completed in ${Math.round(actualTime / 1000)}s`;
445
- }
446
- // Parse artifacts from stdout if available
447
- const { artifacts } = this.parseBuildOutput(validationResult.stdout);
248
+ const executionTime = Date.now() - startTime;
249
+ const parsed = this.parseBuildOutput(result.stdout);
448
250
  return {
449
- success: validationResult.success,
450
- buildSystem: systemInfo.system,
451
- command: 'ng build',
452
- fullCommand: validationResult.buildCommand,
453
- exitCode: validationResult.exitCode,
454
- output: validationResult.stdout,
455
- errors: validationResult.stderr,
456
- executionTime: validationResult.metrics.totalTime,
457
- artifacts,
458
- warnings: validationResult.warnings.map((w) => w.message),
459
- incremental: {
460
- enabled: true,
461
- scope: validationResult.scope.strategy,
462
- filesBuilt: validationResult.affectedFiles.length,
463
- filesSkipped: project.getSourceFiles().length -
464
- validationResult.affectedFiles.length,
465
- cacheHit: validationResult.cacheStatus.exists,
466
- speedup,
467
- },
468
- incompatibilityIssues: incompatibilityIssues.filter((i) => i.detected),
251
+ success: result.exitCode === 0 && !result.timedOut,
252
+ buildSystem: buildSystemOf(resolved.source),
253
+ commandSource: resolved.source,
254
+ command: resolved.command.split(/\s+/)[0] ?? '',
255
+ fullCommand,
256
+ exitCode: result.exitCode,
257
+ output: result.stdout,
258
+ errors: result.stderr,
259
+ executionTime,
260
+ ...(result.timedOut ? { timedOut: true } : {}),
261
+ artifacts: parsed.artifacts,
262
+ warnings: [...warnings, ...parsed.warnings],
469
263
  };
470
264
  }
471
265
  /**
472
- * Detect the build system used in the project.
266
+ * The command to run: the project's build command for `auto-detect`, the
267
+ * default command of an explicitly named build system otherwise.
473
268
  */
474
- detectBuildSystem(rootPath) {
475
- const configFiles = [];
476
- // Check for Angular CLI
477
- if (existsSync(join(rootPath, 'angular.json'))) {
478
- configFiles.push('angular.json');
479
- return {
480
- system: 'angular-cli',
481
- confidence: 1,
482
- configFiles,
483
- buildCommand: ['npx', 'ng', 'build'],
484
- };
485
- }
486
- // Check for Nx
487
- if (existsSync(join(rootPath, 'nx.json')) ||
488
- existsSync(join(rootPath, 'project.json'))) {
489
- configFiles.push('nx.json');
490
- return {
491
- system: 'nx',
492
- confidence: 0.9,
493
- configFiles,
494
- buildCommand: ['npx', 'nx', 'build'],
495
- };
496
- }
497
- // Check for Vite
498
- if (existsSync(join(rootPath, 'vite.config.ts')) ||
499
- existsSync(join(rootPath, 'vite.config.js'))) {
500
- configFiles.push('vite.config.ts');
501
- return {
502
- system: 'vite',
503
- confidence: 0.8,
504
- configFiles,
505
- buildCommand: ['npx', 'vite', 'build'],
506
- };
507
- }
508
- // Check for Webpack
509
- if (existsSync(join(rootPath, 'webpack.config.js')) ||
510
- existsSync(join(rootPath, 'webpack.config.ts'))) {
511
- configFiles.push('webpack.config.js');
512
- return {
513
- system: 'webpack',
514
- confidence: 0.7,
515
- configFiles,
516
- buildCommand: ['npx', 'webpack', '--mode=production'],
517
- };
518
- }
519
- // Check package.json for build scripts
520
- try {
521
- // Disable no-unsafe-assignment: JSON.parse() returns 'any' but package.json structure is validated below
522
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
523
- const packageJson = JSON.parse(readFileSync(join(rootPath, 'package.json'), 'utf-8'));
524
- // Disable no-unsafe-member-access/no-unsafe-assignment: Optional chaining safely handles missing scripts property,
525
- // and we validate existence of 'build' script on line 328 before using it
526
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
527
- const scripts = packageJson.scripts ?? {};
528
- // Disable no-unsafe-member-access: scripts.build access is safe because we're only checking existence
529
- // (truthy check), not using the value's type. If build exists, we return a valid build configuration.
530
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
531
- if (scripts.build) {
532
- return {
533
- system: 'npm',
534
- confidence: 0.6,
535
- configFiles: ['package.json'],
536
- buildCommand: ['npm', 'run', 'build'],
537
- };
538
- }
539
- }
540
- catch {
541
- // Ignore package.json parsing errors
269
+ resolveCommand(rootPath, buildSystem) {
270
+ if (buildSystem === 'auto-detect') {
271
+ return resolveBuildCommand(rootPath);
542
272
  }
543
273
  return {
544
- system: 'unknown',
545
- confidence: 0,
546
- configFiles: [],
547
- buildCommand: ['echo', 'No build system detected'],
274
+ command: this.getDefaultBuildCommand(buildSystem),
275
+ source: 'argument',
548
276
  };
549
277
  }
550
278
  /**
@@ -553,60 +281,39 @@ export class RunBuildTool {
553
281
  getDefaultBuildCommand(system) {
554
282
  switch (system) {
555
283
  case 'angular-cli':
556
- return ['npx', 'ng', 'build'];
284
+ return 'npx ng build';
557
285
  case 'nx':
558
- return ['npx', 'nx', 'build'];
286
+ return 'npx nx build';
559
287
  case 'vite':
560
- return ['npx', 'vite', 'build'];
288
+ return 'npx vite build';
561
289
  case 'webpack':
562
- return ['npx', 'webpack', '--mode=production'];
290
+ return 'npx webpack --mode=production';
563
291
  default:
564
- return ['echo', 'Unknown build system'];
292
+ return 'npm run build';
565
293
  }
566
294
  }
567
295
  /**
568
- * Build command arguments with options.
569
- */
570
- buildCommandArgs(baseCommand, options = {}) {
571
- const args = [...baseCommand];
572
- if (options.configuration) {
573
- args.push('--configuration', options.configuration);
574
- }
575
- if (options.watch) {
576
- args.push('--watch');
577
- }
578
- if (options.args) {
579
- args.push(...options.args);
580
- }
581
- return args;
582
- }
583
- /**
584
- * Execute a build command.
296
+ * Execute a build command line in a shell. A timeout stops the process tree
297
+ * and resolves with `timedOut`; a cancel stops it and rejects.
585
298
  */
586
299
  async executeBuildCommand(command, options) {
587
- if (command.length === 0) {
588
- throw new Error('No command provided');
589
- }
590
300
  return new Promise((resolve, reject) => {
591
- const cmd = command[0];
592
- const args = command.slice(1);
593
- if (!cmd) {
594
- reject(new Error('No command provided'));
595
- return;
596
- }
597
- const buildProcess = spawn(cmd, args, {
301
+ // No CI=true: it switches the Angular build cache off. Color off instead:
302
+ // output and errors are returned as text, the output location is parsed.
303
+ const buildProcess = spawn(command, {
598
304
  cwd: options.cwd,
599
305
  stdio: ['pipe', 'pipe', 'pipe'],
600
306
  shell: true,
601
- env: { ...process.env, CI: 'true' },
307
+ env: noColorEnv({ ...process.env, PATH: projectBinPath(options.cwd) }),
602
308
  ...processGroupOptions(),
603
309
  });
604
310
  let stdout = '';
605
311
  let stderr = '';
606
- // Set up timeout; the build runs under a shell, so the whole process tree goes
312
+ let timedOut = false;
313
+ // The build runs under a shell, so the whole process tree goes
607
314
  const timeoutId = setTimeout(() => {
315
+ timedOut = true;
608
316
  terminateProcessTree(buildProcess);
609
- reject(new Error(`Build command timed out after ${options.timeout}ms`));
610
317
  }, options.timeout);
611
318
  const stopOnAbort = terminateOnAbort(buildProcess, options.signal);
612
319
  const cleanup = () => {
@@ -626,9 +333,10 @@ export class RunBuildTool {
626
333
  return;
627
334
  }
628
335
  resolve({
629
- exitCode: code ?? 0,
630
- stdout,
631
- stderr,
336
+ exitCode: code ?? -1,
337
+ stdout: stripAnsi(stdout),
338
+ stderr: stripAnsi(stderr),
339
+ timedOut,
632
340
  });
633
341
  });
634
342
  buildProcess.on('error', (error) => {
@@ -641,25 +349,15 @@ export class RunBuildTool {
641
349
  * Parse build output for warnings and artifacts.
642
350
  */
643
351
  parseBuildOutput(output) {
644
- const warnings = [];
645
- const artifacts = [];
646
- // Parse warnings - generic pattern that works for most build systems
647
- const genericWarnings = output.match(/Warning:.*$/gm) ?? [];
648
- warnings.push(...genericWarnings);
649
- // Try to detect output artifacts
650
- if (output.includes('dist/') ||
651
- output.includes('build/') ||
652
- output.includes('out/')) {
653
- if (output.includes('dist/')) {
654
- artifacts.push('dist/');
655
- }
656
- if (output.includes('build/')) {
657
- artifacts.push('build/');
658
- }
659
- if (output.includes('out/')) {
660
- artifacts.push('out/');
661
- }
352
+ const warnings = output.match(/Warning:.*$/gm) ?? [];
353
+ // Angular CLI names the folder it wrote; other tools only mention it
354
+ const locations = [...output.matchAll(/Output location:\s*(\S.*?)\s*$/gm)]
355
+ .map((match) => match[1])
356
+ .filter((location) => location !== undefined);
357
+ if (locations.length > 0) {
358
+ return { warnings, artifacts: locations };
662
359
  }
360
+ const artifacts = ['dist/', 'build/', 'out/'].filter((folder) => output.includes(folder));
663
361
  return { warnings, artifacts };
664
362
  }
665
363
  }