@angular-modernizer/adapter-mcp 0.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 (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +917 -0
  3. package/dist/cli.d.ts +8 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +129 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/core/project-analyzer.d.ts +59 -0
  8. package/dist/core/project-analyzer.d.ts.map +1 -0
  9. package/dist/core/project-analyzer.js +116 -0
  10. package/dist/core/project-analyzer.js.map +1 -0
  11. package/dist/index.d.ts +46 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +51 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mcp-watcher.d.ts +119 -0
  16. package/dist/mcp-watcher.d.ts.map +1 -0
  17. package/dist/mcp-watcher.js +380 -0
  18. package/dist/mcp-watcher.js.map +1 -0
  19. package/dist/server/json-rpc-handler.d.ts +57 -0
  20. package/dist/server/json-rpc-handler.d.ts.map +1 -0
  21. package/dist/server/json-rpc-handler.js +222 -0
  22. package/dist/server/json-rpc-handler.js.map +1 -0
  23. package/dist/server/mcp-server.d.ts +62 -0
  24. package/dist/server/mcp-server.d.ts.map +1 -0
  25. package/dist/server/mcp-server.js +184 -0
  26. package/dist/server/mcp-server.js.map +1 -0
  27. package/dist/server/tool-registry.d.ts +73 -0
  28. package/dist/server/tool-registry.d.ts.map +1 -0
  29. package/dist/server/tool-registry.js +102 -0
  30. package/dist/server/tool-registry.js.map +1 -0
  31. package/dist/streaming/progress-store.d.ts +120 -0
  32. package/dist/streaming/progress-store.d.ts.map +1 -0
  33. package/dist/streaming/progress-store.js +238 -0
  34. package/dist/streaming/progress-store.js.map +1 -0
  35. package/dist/tools/analyze-build-impact.d.ts +127 -0
  36. package/dist/tools/analyze-build-impact.d.ts.map +1 -0
  37. package/dist/tools/analyze-build-impact.js +194 -0
  38. package/dist/tools/analyze-build-impact.js.map +1 -0
  39. package/dist/tools/analyze-core-to-shared.d.ts +163 -0
  40. package/dist/tools/analyze-core-to-shared.d.ts.map +1 -0
  41. package/dist/tools/analyze-core-to-shared.js +436 -0
  42. package/dist/tools/analyze-core-to-shared.js.map +1 -0
  43. package/dist/tools/analyze-parser-performance.d.ts +105 -0
  44. package/dist/tools/analyze-parser-performance.d.ts.map +1 -0
  45. package/dist/tools/analyze-parser-performance.js +313 -0
  46. package/dist/tools/analyze-parser-performance.js.map +1 -0
  47. package/dist/tools/analyze-project.d.ts +277 -0
  48. package/dist/tools/analyze-project.d.ts.map +1 -0
  49. package/dist/tools/analyze-project.js +946 -0
  50. package/dist/tools/analyze-project.js.map +1 -0
  51. package/dist/tools/check-incremental-compatibility.d.ts +109 -0
  52. package/dist/tools/check-incremental-compatibility.d.ts.map +1 -0
  53. package/dist/tools/check-incremental-compatibility.js +302 -0
  54. package/dist/tools/check-incremental-compatibility.js.map +1 -0
  55. package/dist/tools/collect-feedback.d.ts +117 -0
  56. package/dist/tools/collect-feedback.d.ts.map +1 -0
  57. package/dist/tools/collect-feedback.js +773 -0
  58. package/dist/tools/collect-feedback.js.map +1 -0
  59. package/dist/tools/extract-libraries.d.ts +121 -0
  60. package/dist/tools/extract-libraries.d.ts.map +1 -0
  61. package/dist/tools/extract-libraries.js +223 -0
  62. package/dist/tools/extract-libraries.js.map +1 -0
  63. package/dist/tools/find-angular-symbol.d.ts +55 -0
  64. package/dist/tools/find-angular-symbol.d.ts.map +1 -0
  65. package/dist/tools/find-angular-symbol.js +104 -0
  66. package/dist/tools/find-angular-symbol.js.map +1 -0
  67. package/dist/tools/find-usages.d.ts +65 -0
  68. package/dist/tools/find-usages.d.ts.map +1 -0
  69. package/dist/tools/find-usages.js +108 -0
  70. package/dist/tools/find-usages.js.map +1 -0
  71. package/dist/tools/get-call-graph.d.ts +61 -0
  72. package/dist/tools/get-call-graph.d.ts.map +1 -0
  73. package/dist/tools/get-call-graph.js +119 -0
  74. package/dist/tools/get-call-graph.js.map +1 -0
  75. package/dist/tools/get-operation-progress-tool.d.ts +29 -0
  76. package/dist/tools/get-operation-progress-tool.d.ts.map +1 -0
  77. package/dist/tools/get-operation-progress-tool.js +36 -0
  78. package/dist/tools/get-operation-progress-tool.js.map +1 -0
  79. package/dist/tools/get-operation-progress.d.ts +51 -0
  80. package/dist/tools/get-operation-progress.d.ts.map +1 -0
  81. package/dist/tools/get-operation-progress.js +93 -0
  82. package/dist/tools/get-operation-progress.js.map +1 -0
  83. package/dist/tools/helpers/feedback-analyzer.d.ts +43 -0
  84. package/dist/tools/helpers/feedback-analyzer.d.ts.map +1 -0
  85. package/dist/tools/helpers/feedback-analyzer.js +196 -0
  86. package/dist/tools/helpers/feedback-analyzer.js.map +1 -0
  87. package/dist/tools/helpers/find-ts-config.d.ts +10 -0
  88. package/dist/tools/helpers/find-ts-config.d.ts.map +1 -0
  89. package/dist/tools/helpers/find-ts-config.js +32 -0
  90. package/dist/tools/helpers/find-ts-config.js.map +1 -0
  91. package/dist/tools/helpers/platform-root-resolver.d.ts +33 -0
  92. package/dist/tools/helpers/platform-root-resolver.d.ts.map +1 -0
  93. package/dist/tools/helpers/platform-root-resolver.js +60 -0
  94. package/dist/tools/helpers/platform-root-resolver.js.map +1 -0
  95. package/dist/tools/helpers/rule-matcher.d.ts +84 -0
  96. package/dist/tools/helpers/rule-matcher.d.ts.map +1 -0
  97. package/dist/tools/helpers/rule-matcher.js +212 -0
  98. package/dist/tools/helpers/rule-matcher.js.map +1 -0
  99. package/dist/tools/helpers/suggestion-generator.d.ts +66 -0
  100. package/dist/tools/helpers/suggestion-generator.d.ts.map +1 -0
  101. package/dist/tools/helpers/suggestion-generator.js +248 -0
  102. package/dist/tools/helpers/suggestion-generator.js.map +1 -0
  103. package/dist/tools/learn-patterns.d.ts +368 -0
  104. package/dist/tools/learn-patterns.d.ts.map +1 -0
  105. package/dist/tools/learn-patterns.js +1089 -0
  106. package/dist/tools/learn-patterns.js.map +1 -0
  107. package/dist/tools/orchestrate-migration.d.ts +187 -0
  108. package/dist/tools/orchestrate-migration.d.ts.map +1 -0
  109. package/dist/tools/orchestrate-migration.js +235 -0
  110. package/dist/tools/orchestrate-migration.js.map +1 -0
  111. package/dist/tools/parse-stack-trace.d.ts +63 -0
  112. package/dist/tools/parse-stack-trace.d.ts.map +1 -0
  113. package/dist/tools/parse-stack-trace.js +92 -0
  114. package/dist/tools/parse-stack-trace.js.map +1 -0
  115. package/dist/tools/plan-migration.d.ts +388 -0
  116. package/dist/tools/plan-migration.d.ts.map +1 -0
  117. package/dist/tools/plan-migration.js +826 -0
  118. package/dist/tools/plan-migration.js.map +1 -0
  119. package/dist/tools/resolve-type.d.ts +54 -0
  120. package/dist/tools/resolve-type.d.ts.map +1 -0
  121. package/dist/tools/resolve-type.js +101 -0
  122. package/dist/tools/resolve-type.js.map +1 -0
  123. package/dist/tools/review-feedback.d.ts +124 -0
  124. package/dist/tools/review-feedback.d.ts.map +1 -0
  125. package/dist/tools/review-feedback.js +276 -0
  126. package/dist/tools/review-feedback.js.map +1 -0
  127. package/dist/tools/rollback-changes.d.ts +42 -0
  128. package/dist/tools/rollback-changes.d.ts.map +1 -0
  129. package/dist/tools/rollback-changes.js +95 -0
  130. package/dist/tools/rollback-changes.js.map +1 -0
  131. package/dist/tools/run-angular-cli.d.ts +102 -0
  132. package/dist/tools/run-angular-cli.d.ts.map +1 -0
  133. package/dist/tools/run-angular-cli.js +152 -0
  134. package/dist/tools/run-angular-cli.js.map +1 -0
  135. package/dist/tools/run-build.d.ts +201 -0
  136. package/dist/tools/run-build.d.ts.map +1 -0
  137. package/dist/tools/run-build.js +554 -0
  138. package/dist/tools/run-build.js.map +1 -0
  139. package/dist/tools/run-schematic.d.ts +173 -0
  140. package/dist/tools/run-schematic.d.ts.map +1 -0
  141. package/dist/tools/run-schematic.js +410 -0
  142. package/dist/tools/run-schematic.js.map +1 -0
  143. package/dist/tools/scan-all.d.ts +160 -0
  144. package/dist/tools/scan-all.d.ts.map +1 -0
  145. package/dist/tools/scan-all.js +486 -0
  146. package/dist/tools/scan-all.js.map +1 -0
  147. package/dist/tools/scan-angular.d.ts +132 -0
  148. package/dist/tools/scan-angular.d.ts.map +1 -0
  149. package/dist/tools/scan-angular.js +411 -0
  150. package/dist/tools/scan-angular.js.map +1 -0
  151. package/dist/tools/scan-architecture.d.ts +351 -0
  152. package/dist/tools/scan-architecture.d.ts.map +1 -0
  153. package/dist/tools/scan-architecture.js +1290 -0
  154. package/dist/tools/scan-architecture.js.map +1 -0
  155. package/dist/tools/scan-solid.d.ts +132 -0
  156. package/dist/tools/scan-solid.d.ts.map +1 -0
  157. package/dist/tools/scan-solid.js +435 -0
  158. package/dist/tools/scan-solid.js.map +1 -0
  159. package/dist/tools/search-codebase.d.ts +64 -0
  160. package/dist/tools/search-codebase.d.ts.map +1 -0
  161. package/dist/tools/search-codebase.js +109 -0
  162. package/dist/tools/search-codebase.js.map +1 -0
  163. package/dist/tools/shared/scan-types.d.ts +200 -0
  164. package/dist/tools/shared/scan-types.d.ts.map +1 -0
  165. package/dist/tools/shared/scan-types.js +7 -0
  166. package/dist/tools/shared/scan-types.js.map +1 -0
  167. package/dist/tools/suggest-improvements.d.ts +96 -0
  168. package/dist/tools/suggest-improvements.d.ts.map +1 -0
  169. package/dist/tools/suggest-improvements.js +182 -0
  170. package/dist/tools/suggest-improvements.js.map +1 -0
  171. package/dist/tools/transform-code-batch.d.ts +57 -0
  172. package/dist/tools/transform-code-batch.d.ts.map +1 -0
  173. package/dist/tools/transform-code-batch.js +107 -0
  174. package/dist/tools/transform-code-batch.js.map +1 -0
  175. package/dist/tools/transform-code.d.ts +352 -0
  176. package/dist/tools/transform-code.d.ts.map +1 -0
  177. package/dist/tools/transform-code.js +1171 -0
  178. package/dist/tools/transform-code.js.map +1 -0
  179. package/dist/tools/validate-before-transform.d.ts +54 -0
  180. package/dist/tools/validate-before-transform.d.ts.map +1 -0
  181. package/dist/tools/validate-before-transform.js +141 -0
  182. package/dist/tools/validate-before-transform.js.map +1 -0
  183. package/dist/tools/validate-project-compatibility.d.ts +119 -0
  184. package/dist/tools/validate-project-compatibility.d.ts.map +1 -0
  185. package/dist/tools/validate-project-compatibility.js +243 -0
  186. package/dist/tools/validate-project-compatibility.js.map +1 -0
  187. package/dist/tools/validate-transformation.d.ts +105 -0
  188. package/dist/tools/validate-transformation.d.ts.map +1 -0
  189. package/dist/tools/validate-transformation.js +391 -0
  190. package/dist/tools/validate-transformation.js.map +1 -0
  191. package/dist/types.d.ts +153 -0
  192. package/dist/types.d.ts.map +1 -0
  193. package/dist/types.js +38 -0
  194. package/dist/types.js.map +1 -0
  195. package/dist/utils/format-tool-response.d.ts +72 -0
  196. package/dist/utils/format-tool-response.d.ts.map +1 -0
  197. package/dist/utils/format-tool-response.js +149 -0
  198. package/dist/utils/format-tool-response.js.map +1 -0
  199. package/package.json +70 -0
@@ -0,0 +1,1171 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Transform Code Tool
3
+ *
4
+ * MCP tool for performing surgical code transformations to fix
5
+ * architectural issues, including standalone component migration.
6
+ */
7
+ import { findTsConfig } from './helpers/find-ts-config.js';
8
+ import { Kernel, FluentKernel, BackupManager, RollbackManager, PreTransformValidator, PostTransformValidator, StreamingKernelWrapper, loadConfig, } from '@angular-modernizer/core';
9
+ import { AngularPlugin } from '@angular-modernizer/plugin-angular';
10
+ import { readFileSync } from 'node:fs';
11
+ import { resolve } from 'node:path';
12
+ import { randomUUID } from 'node:crypto';
13
+ import { executeBatchTransformation, } from './transform-code-batch.js';
14
+ import { ProgressStore } from '../streaming/progress-store.js';
15
+ import { getAvailableRules, findSimilarRules } from './helpers/rule-matcher.js';
16
+ import { cpus } from 'node:os';
17
+ /**
18
+ * MCP tool for code transformations.
19
+ */
20
+ export class TransformCodeTool {
21
+ name = 'transform-code';
22
+ description = 'Apply surgical code transformations to fix architectural issues';
23
+ inputSchema = {
24
+ type: 'object',
25
+ properties: {
26
+ filePath: {
27
+ type: 'string',
28
+ description: 'Path to the file to transform (single file mode)',
29
+ },
30
+ files: {
31
+ type: 'array',
32
+ items: { type: 'string' },
33
+ description: 'Paths to multiple files to transform (batch mode)',
34
+ },
35
+ transformation: {
36
+ type: 'string',
37
+ description: 'Type of transformation to apply',
38
+ enum: [
39
+ 'constructor-to-inject',
40
+ 'interface-extraction',
41
+ 'standalone-migration',
42
+ 'dependency-injection-migration',
43
+ 'facade-pattern',
44
+ 'form-modernization',
45
+ 'constructor-injection-transform',
46
+ 'component-inputs-interface-extraction',
47
+ 'service-injection-cleanup',
48
+ 'container-presentational',
49
+ 'core-shared-modules',
50
+ 'inheritance-to-composition',
51
+ 'promise-service-to-observable',
52
+ 'promise-component-to-reactive',
53
+ 'promise-cleanup',
54
+ 'sequential-await-to-forkjoin',
55
+ 'missing-output-transform',
56
+ 'subscription-transform',
57
+ 'library-extraction',
58
+ ],
59
+ },
60
+ options: {
61
+ type: 'object',
62
+ description: 'Transformation-specific options',
63
+ },
64
+ validateBeforeTransform: {
65
+ type: 'boolean',
66
+ description: 'Whether to validate before transformation (default: true)',
67
+ default: true,
68
+ },
69
+ createBackup: {
70
+ type: 'boolean',
71
+ description: 'Whether to create a backup before transformation (default: true)',
72
+ default: true,
73
+ },
74
+ validateTransformation: {
75
+ type: 'boolean',
76
+ description: 'Whether to validate transformation results (default: true)',
77
+ default: true,
78
+ },
79
+ autoRollback: {
80
+ type: 'boolean',
81
+ description: 'Whether to automatically rollback on validation failure (default: true)',
82
+ default: true,
83
+ },
84
+ backupDir: {
85
+ type: 'string',
86
+ description: 'Custom backup directory (optional)',
87
+ },
88
+ rollbackStrategy: {
89
+ type: 'string',
90
+ description: 'Rollback strategy for batch operations',
91
+ enum: ['all-or-nothing', 'selective', 'none'],
92
+ default: 'all-or-nothing',
93
+ },
94
+ orchestration: {
95
+ type: 'object',
96
+ description: 'Orchestration options for parallel and incremental transformations. Note: parallel defaults to false for safety.',
97
+ properties: {
98
+ parallel: {
99
+ type: 'boolean',
100
+ description: 'Enable parallel transformation processing (batch mode only). Defaults to FALSE for safety.',
101
+ default: false,
102
+ },
103
+ useWorkerThreads: {
104
+ type: 'boolean',
105
+ description: 'Use worker threads for parallel transformations (Phase 6d). Requires tsConfigPath and workerScriptPath.',
106
+ },
107
+ autoSelectMode: {
108
+ type: 'boolean',
109
+ description: 'Enable intelligent auto-selection of Promise vs Worker mode based on project complexity. Defaults to true when parallel is enabled.',
110
+ },
111
+ maxWorkers: {
112
+ type: 'number',
113
+ description: 'Maximum number of parallel workers. Default: auto-selected based on CPU cores and memory.',
114
+ },
115
+ enableProgress: {
116
+ type: 'boolean',
117
+ description: 'Enable real-time progress reporting.',
118
+ default: false,
119
+ },
120
+ timeout: {
121
+ type: 'number',
122
+ description: 'Timeout in milliseconds for parallel operations. Default: 30000.',
123
+ },
124
+ resourceLimits: {
125
+ type: 'object',
126
+ description: 'Resource limits for large-scale operations.',
127
+ properties: {
128
+ maxMemory: {
129
+ type: 'number',
130
+ description: 'Maximum memory usage in bytes. Triggers throttling when exceeded.',
131
+ },
132
+ maxWorkers: {
133
+ type: 'number',
134
+ description: 'Maximum concurrent workers regardless of system capacity.',
135
+ },
136
+ },
137
+ },
138
+ pluginIds: {
139
+ type: 'array',
140
+ items: { type: 'string' },
141
+ description: 'Plugin IDs to load for worker thread transformations.',
142
+ default: ['@angular-modernizer/plugin-angular'],
143
+ },
144
+ },
145
+ },
146
+ streaming: {
147
+ type: 'boolean',
148
+ description: 'Enable streaming mode - returns operationId immediately for polling progress. When true, transformation runs in background and progress can be queried via get-operation-progress tool.',
149
+ default: true,
150
+ },
151
+ diffFormat: {
152
+ type: 'string',
153
+ enum: ['unified', 'structured', 'both'],
154
+ description: 'Format for diff output in streaming mode. "structured" (default) provides AI-parseable diffs with semantic annotations including Angular file type detection, syntax type annotations, and transformation intent. "unified" provides traditional unified diffs. "both" includes both formats simultaneously.',
155
+ default: 'structured',
156
+ },
157
+ apiStyle: {
158
+ type: 'string',
159
+ enum: ['imperative', 'fluent'],
160
+ description: 'API style to use for transformation execution. "fluent" (default) uses the chainable FluentKernel API with pipeline stages. "imperative" uses traditional Kernel API.',
161
+ default: 'fluent',
162
+ },
163
+ buildCheck: {
164
+ type: 'boolean',
165
+ description: 'Enable build validation after transformation (fluent API only). Validates that the transformation did not break the build.',
166
+ default: false,
167
+ },
168
+ validateBuild: {
169
+ type: 'boolean',
170
+ description: 'Whether to validate the build after transformation (default: true). Runs the project build to ensure code compiles after transformation.',
171
+ default: true,
172
+ },
173
+ rollbackOnBuildFailure: {
174
+ type: 'boolean',
175
+ description: 'Whether to automatically rollback on build failure (default: true). When enabled, restores backups if build validation fails.',
176
+ default: true,
177
+ },
178
+ buildTimeout: {
179
+ type: 'number',
180
+ description: 'Build validation timeout in milliseconds (default: 300000 = 5 minutes).',
181
+ default: 300000,
182
+ },
183
+ projectRoot: {
184
+ type: 'string',
185
+ description: 'Project root path for build validation. If not provided, will be auto-detected from filePath.',
186
+ },
187
+ },
188
+ required: ['transformation'],
189
+ };
190
+ async execute(args) {
191
+ const params = args;
192
+ // Validate that either filePath or files is provided
193
+ if (!params.filePath && (!params.files || params.files.length === 0)) {
194
+ throw new Error('Either filePath (for single file) or files (for batch) must be provided');
195
+ }
196
+ if (params.filePath && params.files && params.files.length > 0) {
197
+ throw new Error('Cannot specify both filePath and files - choose either single file or batch mode');
198
+ }
199
+ // Check if streaming mode is enabled (default: true)
200
+ const streaming = params.streaming ?? true;
201
+ if (streaming) {
202
+ // Streaming mode - start operation in background and return operationId
203
+ return this.executeStreaming(params);
204
+ }
205
+ // Use orchestration object directly
206
+ // Note: parallel defaults to false for transformations for safety
207
+ const orchestration = {
208
+ parallel: false, // Safety default for transformations
209
+ ...params.orchestration,
210
+ };
211
+ // Detect batch mode
212
+ const isBatchMode = Boolean(params.files && params.files.length > 0);
213
+ // Phase 4: Auto-enable parallel processing for >100 files (unless explicitly disabled)
214
+ if (isBatchMode && params.files && params.files.length > 100) {
215
+ // Only auto-enable if user hasn't explicitly set parallel flag
216
+ if (params.orchestration?.parallel === undefined) {
217
+ orchestration.parallel = true;
218
+ orchestration.autoSelectMode = orchestration.autoSelectMode ?? true;
219
+ orchestration.maxWorkers =
220
+ orchestration.maxWorkers ?? Math.min(4, cpus().length);
221
+ }
222
+ }
223
+ if (isBatchMode) {
224
+ // Batch mode - delegate to batch transformation handler
225
+ return this.executeBatch(params, orchestration);
226
+ }
227
+ // Original single-file mode logic
228
+ const filePath = params.filePath;
229
+ const transformation = params.transformation;
230
+ if (!filePath || typeof filePath !== 'string') {
231
+ throw new Error('filePath is required and must be a string');
232
+ }
233
+ // Load config from .angular-modernizer.json and merge with params
234
+ const projectRoot = params.projectRoot ?? this.findProjectRoot(filePath);
235
+ const fullConfig = loadConfig(projectRoot);
236
+ const config = fullConfig.tools?.['transform-code'] ?? {};
237
+ const mergedParams = { ...config, ...params };
238
+ const options = mergedParams.options ?? {};
239
+ const validateBeforeTransform = mergedParams.validateBeforeTransform ?? true;
240
+ const createBackup = mergedParams.createBackup ?? true;
241
+ const validateTransformation = mergedParams.validateTransformation ?? true;
242
+ const autoRollback = mergedParams.autoRollback ?? true;
243
+ const backupDir = mergedParams.backupDir;
244
+ const apiStyle = mergedParams.apiStyle ?? 'fluent';
245
+ const buildCheck = mergedParams.buildCheck ?? false;
246
+ const validateBuild = mergedParams.validateBuild ?? true;
247
+ const rollbackOnBuildFailure = mergedParams.rollbackOnBuildFailure ?? true;
248
+ const buildTimeout = mergedParams.buildTimeout ?? 300000;
249
+ if (typeof transformation !== 'string') {
250
+ throw new TypeError('transformation is required and must be a string');
251
+ }
252
+ // Validate that the transformation type exists in the schema
253
+ this.validateTransformationType(transformation);
254
+ // Use fluent API if requested
255
+ if (apiStyle === 'fluent') {
256
+ return this.executeWithFluentApi(filePath, transformation, options, {
257
+ validateBeforeTransform,
258
+ createBackup,
259
+ validateTransformation,
260
+ autoRollback,
261
+ backupDir,
262
+ buildCheck,
263
+ validateBuild,
264
+ rollbackOnBuildFailure,
265
+ buildTimeout,
266
+ projectRoot,
267
+ });
268
+ }
269
+ let preValidationResult;
270
+ let backupResult;
271
+ let validationResult;
272
+ let rollbackResult;
273
+ try {
274
+ // Step 0: Pre-validate if requested
275
+ if (validateBeforeTransform) {
276
+ const tsConfigPath = findTsConfig(projectRoot);
277
+ if (!tsConfigPath) {
278
+ throw new Error('Could not find tsconfig.json in the project root');
279
+ }
280
+ // Create a temporary kernel for pre-validation with caching
281
+ const tempKernel = new Kernel({
282
+ tsConfigPath,
283
+ plugins: [new AngularPlugin()],
284
+ cacheConfig: {
285
+ enabled: true,
286
+ cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
287
+ maxSize: 100 * 1024 * 1024, // 100MB
288
+ maxAge: 24 * 60 * 60 * 1000, // 24 hours
289
+ compression: true,
290
+ },
291
+ });
292
+ await tempKernel.initialize();
293
+ const project = tempKernel.getProject();
294
+ const sourceFile = project.addSourceFileAtPath(filePath);
295
+ // Create pre-validator and config
296
+ const preValidator = new PreTransformValidator();
297
+ const preValidationConfig = {
298
+ validateSyntax: true,
299
+ validateDependencies: true,
300
+ validateTypes: true,
301
+ validateSchema: true,
302
+ schema: this.getSchemaForTransformation(transformation),
303
+ };
304
+ const result = await preValidator.validate(sourceFile, project, preValidationConfig);
305
+ preValidationResult = {
306
+ valid: result.valid,
307
+ issues: result.issues.map((issue) => ({
308
+ type: issue.type,
309
+ severity: issue.severity,
310
+ message: issue.message,
311
+ filePath: issue.filePath,
312
+ line: issue.line,
313
+ column: issue.column,
314
+ })),
315
+ };
316
+ // If pre-validation fails, stop here (no backup needed)
317
+ if (!result.valid) {
318
+ throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
319
+ `Cannot safely transform file. Please fix these issues first:\n` +
320
+ result.issues
321
+ .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
322
+ .join('\n'));
323
+ }
324
+ }
325
+ // Step 1: Create backup if requested
326
+ if (createBackup) {
327
+ const backupManager = new BackupManager(backupDir);
328
+ backupResult = await backupManager.backup(filePath);
329
+ if (!backupResult.success) {
330
+ throw new Error('Failed to create backup before transformation');
331
+ }
332
+ }
333
+ // Step 2: Perform transformation
334
+ const tsConfigPath = findTsConfig(projectRoot);
335
+ if (!tsConfigPath) {
336
+ throw new Error('Could not find tsconfig.json in the project root');
337
+ }
338
+ // Create transformation coordinator
339
+ // Initialize kernel with transformation capabilities and caching
340
+ const kernel = new Kernel({
341
+ tsConfigPath,
342
+ plugins: [new AngularPlugin()],
343
+ cacheConfig: {
344
+ enabled: true,
345
+ cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
346
+ maxSize: 100 * 1024 * 1024, // 100MB
347
+ maxAge: 24 * 60 * 60 * 1000, // 24 hours
348
+ compression: true,
349
+ },
350
+ });
351
+ await kernel.initialize();
352
+ // Get the source file
353
+ const project = kernel.getProject();
354
+ const sourceFile = project.addSourceFileAtPath(filePath);
355
+ // Capture line count before transformation
356
+ const linesBefore = sourceFile.getFullText().split('\n').length;
357
+ // Perform the transformation
358
+ const transformConfig = {
359
+ dryRun: false,
360
+ autoSave: true,
361
+ pluginConfig: {
362
+ '@angular-modernizer/plugin-standalone': {
363
+ transformationType: transformation === 'standalone-migration'
364
+ ? transformation
365
+ : undefined,
366
+ ...options,
367
+ },
368
+ '@angular-modernizer/plugin-angular': {
369
+ transformationType: [
370
+ 'constructor-to-inject',
371
+ 'interface-extraction',
372
+ 'dependency-injection-migration',
373
+ 'facade-pattern',
374
+ 'form-modernization',
375
+ 'constructor-injection-transform',
376
+ 'component-inputs-interface-extraction',
377
+ 'service-injection-cleanup',
378
+ 'container-presentational',
379
+ 'core-shared-modules',
380
+ 'inheritance-to-composition',
381
+ 'promise-service-to-observable',
382
+ 'promise-component-to-reactive',
383
+ 'promise-cleanup',
384
+ 'sequential-await-to-forkjoin',
385
+ 'missing-output-transform',
386
+ 'subscription-transform',
387
+ 'library-extraction',
388
+ ].includes(transformation)
389
+ ? transformation
390
+ : undefined,
391
+ ...options,
392
+ },
393
+ },
394
+ };
395
+ const result = (await kernel.transformFile(sourceFile, transformConfig));
396
+ // Save the file if autoSave is enabled
397
+ if (!transformConfig.dryRun && transformConfig.autoSave) {
398
+ await sourceFile.save();
399
+ }
400
+ // Capture line count after transformation
401
+ const linesAfter = sourceFile.getFullText().split('\n').length;
402
+ // Calculate changes
403
+ const additions = Math.max(0, linesAfter - linesBefore);
404
+ const deletions = Math.max(0, linesBefore - linesAfter);
405
+ const linesChanged = result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0);
406
+ // Step 3: Validate the transformation if requested
407
+ let validation;
408
+ if (validateTransformation) {
409
+ const validator = new PostTransformValidator();
410
+ const validationConfig = {
411
+ validateBuild: validateBuild,
412
+ validateTests: false, // Tests can be slow, skip by default
413
+ validateLint: true,
414
+ buildTimeout: buildTimeout,
415
+ testTimeout: 600000,
416
+ lintTimeout: 120000,
417
+ cwd: projectRoot,
418
+ };
419
+ validationResult = await validator.validate(filePath, validationConfig);
420
+ validation = {
421
+ syntaxValid: validationResult.valid,
422
+ typeCheckPassed: validationResult.valid,
423
+ testsPass: validationResult.valid,
424
+ };
425
+ // Step 4: Auto-rollback if validation failed and auto-rollback is enabled
426
+ if (!validationResult.valid && autoRollback && createBackup) {
427
+ const rollbackConfig = {
428
+ backupDir: backupDir ?? undefined,
429
+ gitRoot: projectRoot,
430
+ };
431
+ const rollbackManager = new RollbackManager(rollbackConfig);
432
+ const rollbackAttempt = await rollbackManager.rollback([filePath]);
433
+ rollbackResult = {
434
+ performed: true,
435
+ reason: `Validation failed: ${validationResult.issues.length} issue(s) found`,
436
+ success: rollbackAttempt.success,
437
+ };
438
+ // If rollback succeeded, mark transformation as failed
439
+ if (rollbackAttempt.success) {
440
+ return {
441
+ success: false,
442
+ filePath,
443
+ transformation,
444
+ changes: {
445
+ linesChanged,
446
+ additions,
447
+ deletions,
448
+ },
449
+ preValidation: preValidationResult,
450
+ validation,
451
+ backup: backupResult
452
+ ? {
453
+ created: backupResult.success,
454
+ backupPath: backupResult.backupPath,
455
+ strategy: 'file-backup',
456
+ }
457
+ : undefined,
458
+ rollback: rollbackResult,
459
+ warnings: [
460
+ ...result.errors.map((e) => e.message),
461
+ `Transformation rolled back due to validation failures`,
462
+ ],
463
+ };
464
+ }
465
+ }
466
+ }
467
+ else {
468
+ // Use basic validation if full validation is disabled
469
+ validation = (await this.validateTransformation(filePath, transformation));
470
+ }
471
+ return {
472
+ success: result.success && (validationResult?.valid ?? true),
473
+ filePath,
474
+ transformation,
475
+ changes: {
476
+ linesChanged,
477
+ additions,
478
+ deletions,
479
+ },
480
+ preValidation: preValidationResult,
481
+ validation,
482
+ backup: backupResult
483
+ ? {
484
+ created: backupResult.success,
485
+ backupPath: backupResult.backupPath,
486
+ strategy: 'file-backup',
487
+ }
488
+ : undefined,
489
+ rollback: rollbackResult,
490
+ warnings: result.errors.map((e) => e.message),
491
+ };
492
+ }
493
+ catch (error) {
494
+ // If an error occurs and we have a backup, attempt rollback
495
+ if (createBackup && autoRollback && !rollbackResult) {
496
+ try {
497
+ const rollbackConfig = {
498
+ backupDir: backupDir ?? undefined,
499
+ gitRoot: projectRoot,
500
+ };
501
+ const rollbackManager = new RollbackManager(rollbackConfig);
502
+ const rollbackAttempt = await rollbackManager.rollback([filePath]);
503
+ rollbackResult = {
504
+ performed: true,
505
+ reason: `Transformation failed with error: ${error instanceof Error ? error.message : String(error)}`,
506
+ success: rollbackAttempt.success,
507
+ };
508
+ }
509
+ catch (rollbackError) {
510
+ // Rollback failed, include this in the error
511
+ throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}. ` +
512
+ `Rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
513
+ }
514
+ }
515
+ throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}`);
516
+ }
517
+ }
518
+ /**
519
+ * Execute transformation using fluent API.
520
+ */
521
+ async executeWithFluentApi(filePath, transformation, options, config) {
522
+ let preValidationResult;
523
+ let backupResult;
524
+ let rollbackResult;
525
+ try {
526
+ // Step 0: Pre-validate if requested
527
+ if (config.validateBeforeTransform) {
528
+ const tsConfigPath = findTsConfig(config.projectRoot);
529
+ if (!tsConfigPath) {
530
+ throw new Error('Could not find tsconfig.json in the project root');
531
+ }
532
+ const tempKernel = new Kernel({
533
+ tsConfigPath,
534
+ plugins: [new AngularPlugin()],
535
+ cacheConfig: {
536
+ enabled: true,
537
+ cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
538
+ maxSize: 100 * 1024 * 1024,
539
+ maxAge: 24 * 60 * 60 * 1000,
540
+ compression: true,
541
+ },
542
+ });
543
+ await tempKernel.initialize();
544
+ const project = tempKernel.getProject();
545
+ const sourceFile = project.addSourceFileAtPath(filePath);
546
+ const preValidator = new PreTransformValidator();
547
+ const preValidationConfig = {
548
+ validateSyntax: true,
549
+ validateDependencies: true,
550
+ validateTypes: true,
551
+ validateSchema: true,
552
+ schema: this.getSchemaForTransformation(transformation),
553
+ };
554
+ const result = await preValidator.validate(sourceFile, project, preValidationConfig);
555
+ preValidationResult = {
556
+ valid: result.valid,
557
+ issues: result.issues.map((issue) => ({
558
+ type: issue.type,
559
+ severity: issue.severity,
560
+ message: issue.message,
561
+ filePath: issue.filePath,
562
+ line: issue.line,
563
+ column: issue.column,
564
+ })),
565
+ };
566
+ if (!result.valid) {
567
+ throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
568
+ `Cannot safely transform file. Please fix these issues first:\n` +
569
+ result.issues
570
+ .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
571
+ .join('\n'));
572
+ }
573
+ }
574
+ // Step 1: Create backup if requested
575
+ if (config.createBackup) {
576
+ const backupManager = new BackupManager(config.backupDir);
577
+ backupResult = await backupManager.backup(filePath);
578
+ if (!backupResult.success) {
579
+ throw new Error('Failed to create backup before transformation');
580
+ }
581
+ }
582
+ // Step 2: Create kernel and perform transformation using FluentKernel
583
+ const tsConfigPath = findTsConfig(config.projectRoot);
584
+ if (!tsConfigPath) {
585
+ throw new Error('Could not find tsconfig.json in the project root');
586
+ }
587
+ const kernel = new Kernel({
588
+ tsConfigPath,
589
+ plugins: [new AngularPlugin()],
590
+ cacheConfig: {
591
+ enabled: true,
592
+ cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
593
+ maxSize: 100 * 1024 * 1024,
594
+ maxAge: 24 * 60 * 60 * 1000,
595
+ compression: true,
596
+ },
597
+ });
598
+ await kernel.initialize();
599
+ // Get the source file
600
+ const project = kernel.getProject();
601
+ const sourceFile = project.addSourceFileAtPath(filePath);
602
+ const linesBefore = sourceFile.getFullText().split('\n').length;
603
+ // Build fluent pipeline
604
+ let fluent = FluentKernel.create(kernel)
605
+ .transform(transformation, [filePath])
606
+ .withMetadata({ transformation, filePath, options });
607
+ // Add build check if requested
608
+ if (config.buildCheck) {
609
+ fluent = fluent.buildCheck(config.autoRollback);
610
+ }
611
+ // Execute pipeline
612
+ const pipelineResult = await fluent.execute();
613
+ // Save the file
614
+ await sourceFile.save();
615
+ // Capture line count after transformation
616
+ const linesAfter = sourceFile.getFullText().split('\n').length;
617
+ const additions = Math.max(0, linesAfter - linesBefore);
618
+ const deletions = Math.max(0, linesBefore - linesAfter);
619
+ // Extract pipeline info
620
+ const pipeline = fluent.getStages().map((stage) => stage.name);
621
+ const intermediateResults = {};
622
+ for (const stage of fluent.getStages()) {
623
+ intermediateResults[stage.name] = {
624
+ success: true,
625
+ message: `Stage ${stage.name} completed`,
626
+ };
627
+ }
628
+ // Step 3: Validate if requested
629
+ let validation;
630
+ let buildValidation;
631
+ if (config.validateTransformation) {
632
+ const validator = new PostTransformValidator();
633
+ const validationConfig = {
634
+ validateBuild: config.validateBuild,
635
+ validateTests: false,
636
+ validateLint: true,
637
+ buildTimeout: config.buildTimeout,
638
+ testTimeout: 600000,
639
+ lintTimeout: 120000,
640
+ cwd: config.projectRoot,
641
+ };
642
+ const validationResult = await validator.validate(filePath, validationConfig);
643
+ validation = {
644
+ syntaxValid: validationResult.valid,
645
+ typeCheckPassed: validationResult.valid,
646
+ testsPass: validationResult.valid,
647
+ };
648
+ buildValidation = {
649
+ passed: validationResult.valid,
650
+ success: validationResult.valid,
651
+ errors: validationResult.valid
652
+ ? undefined
653
+ : validationResult.issues.map((i) => i.message),
654
+ };
655
+ // Step 4: Auto-rollback if validation failed
656
+ if (!validationResult.valid &&
657
+ config.autoRollback &&
658
+ config.createBackup) {
659
+ const rollbackConfig = {
660
+ backupDir: config.backupDir ?? undefined,
661
+ gitRoot: config.projectRoot,
662
+ };
663
+ const rollbackManager = new RollbackManager(rollbackConfig);
664
+ const rollbackAttempt = await rollbackManager.rollback([filePath]);
665
+ rollbackResult = {
666
+ performed: true,
667
+ reason: `Validation failed: ${validationResult.issues.length} issue(s) found`,
668
+ success: rollbackAttempt.success,
669
+ };
670
+ if (rollbackAttempt.success) {
671
+ return {
672
+ success: false,
673
+ filePath,
674
+ transformation,
675
+ changes: {
676
+ linesChanged: pipelineResult.transformations.length,
677
+ additions,
678
+ deletions,
679
+ },
680
+ preValidation: preValidationResult,
681
+ validation,
682
+ backup: backupResult
683
+ ? {
684
+ created: backupResult.success,
685
+ backupPath: backupResult.backupPath,
686
+ strategy: 'file-backup',
687
+ }
688
+ : undefined,
689
+ rollback: rollbackResult,
690
+ pipeline,
691
+ intermediateResults,
692
+ buildValidation,
693
+ warnings: pipelineResult.errors.map((e) => e.message),
694
+ };
695
+ }
696
+ }
697
+ }
698
+ else {
699
+ validation = (await this.validateTransformation(filePath, transformation));
700
+ }
701
+ return {
702
+ success: pipelineResult.success,
703
+ filePath,
704
+ transformation,
705
+ changes: {
706
+ linesChanged: pipelineResult.transformations.length,
707
+ additions,
708
+ deletions,
709
+ },
710
+ preValidation: preValidationResult,
711
+ validation,
712
+ backup: backupResult
713
+ ? {
714
+ created: backupResult.success,
715
+ backupPath: backupResult.backupPath,
716
+ strategy: 'file-backup',
717
+ }
718
+ : undefined,
719
+ rollback: rollbackResult,
720
+ pipeline,
721
+ intermediateResults,
722
+ buildValidation,
723
+ warnings: pipelineResult.errors.map((e) => e.message),
724
+ };
725
+ }
726
+ catch (error) {
727
+ // If an error occurs and we have a backup, attempt rollback
728
+ if (config.createBackup && config.autoRollback && !rollbackResult) {
729
+ try {
730
+ const rollbackConfig = {
731
+ backupDir: config.backupDir ?? undefined,
732
+ gitRoot: config.projectRoot,
733
+ };
734
+ const rollbackManager = new RollbackManager(rollbackConfig);
735
+ const rollbackAttempt = await rollbackManager.rollback([filePath]);
736
+ rollbackResult = {
737
+ performed: true,
738
+ reason: `Transformation failed with error: ${error instanceof Error ? error.message : String(error)}`,
739
+ success: rollbackAttempt.success,
740
+ };
741
+ }
742
+ catch (rollbackError) {
743
+ throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}. ` +
744
+ `Rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
745
+ }
746
+ }
747
+ throw new Error(`Code transformation failed: ${error instanceof Error ? error.message : String(error)}`);
748
+ }
749
+ }
750
+ /**
751
+ * Execute streaming transformation - returns operationId immediately.
752
+ * Transformation runs in background with progress stored in ProgressStore.
753
+ */
754
+ async executeStreaming(params) {
755
+ const operationId = randomUUID();
756
+ const store = ProgressStore.getInstance();
757
+ // Create operation in store
758
+ store.createOperation(operationId, {
759
+ operationId,
760
+ type: 'transformation',
761
+ startTime: Date.now(),
762
+ });
763
+ // Start transformation in background (don't await)
764
+ this.runStreamingTransformation(operationId, params).catch((error) => {
765
+ // Mark operation as failed if error occurs
766
+ store.markFailed(operationId, error instanceof Error ? error.message : String(error));
767
+ });
768
+ // Return operationId immediately
769
+ return {
770
+ success: true,
771
+ operationId,
772
+ transformation: params.transformation ?? 'unknown',
773
+ changes: {
774
+ linesChanged: 0,
775
+ additions: 0,
776
+ deletions: 0,
777
+ },
778
+ validation: {
779
+ syntaxValid: true,
780
+ typeCheckPassed: true,
781
+ },
782
+ };
783
+ }
784
+ /**
785
+ * Run streaming transformation in background using StreamingKernelWrapper.
786
+ */
787
+ async runStreamingTransformation(operationId, params) {
788
+ const store = ProgressStore.getInstance();
789
+ const filePath = params.filePath;
790
+ const transformation = params.transformation;
791
+ if (!filePath || typeof filePath !== 'string') {
792
+ throw new Error('filePath is required and must be a string');
793
+ }
794
+ if (!transformation) {
795
+ throw new Error('transformation is required');
796
+ }
797
+ // Find project root
798
+ const projectRoot = this.findProjectRoot(filePath);
799
+ const tsConfigPath = findTsConfig(projectRoot);
800
+ if (!tsConfigPath) {
801
+ throw new Error('Could not find tsconfig.json in the project root');
802
+ }
803
+ // Create kernel
804
+ const kernel = new Kernel({
805
+ tsConfigPath,
806
+ plugins: [new AngularPlugin()],
807
+ cacheConfig: {
808
+ enabled: true,
809
+ cacheDir: resolve(projectRoot, '.angular-modernizer-cache'),
810
+ maxSize: 100 * 1024 * 1024,
811
+ maxAge: 24 * 60 * 60 * 1000,
812
+ compression: true,
813
+ },
814
+ });
815
+ await kernel.initialize();
816
+ // Create StreamingKernelWrapper with diffFormat from params (default: 'structured')
817
+ const wrapper = new StreamingKernelWrapper(kernel, {
818
+ includeDiffs: true,
819
+ diffFormat: params.diffFormat ?? 'structured',
820
+ includeMemory: true,
821
+ validateSyntax: true,
822
+ diffContext: 3,
823
+ });
824
+ // Create transform config
825
+ const transformConfig = {
826
+ dryRun: false,
827
+ autoSave: true,
828
+ pluginConfig: {
829
+ '@angular-modernizer/plugin-standalone': {
830
+ transformationType: transformation === 'standalone-migration'
831
+ ? transformation
832
+ : undefined,
833
+ ...params.options,
834
+ },
835
+ '@angular-modernizer/plugin-angular': {
836
+ transformationType: [
837
+ 'constructor-to-inject',
838
+ 'interface-extraction',
839
+ 'dependency-injection-migration',
840
+ 'facade-pattern',
841
+ 'form-modernization',
842
+ 'constructor-injection-transform',
843
+ 'component-inputs-interface-extraction',
844
+ 'service-injection-cleanup',
845
+ 'container-presentational',
846
+ 'core-shared-modules',
847
+ 'inheritance-to-composition',
848
+ 'promise-service-to-observable',
849
+ 'promise-component-to-reactive',
850
+ 'promise-cleanup',
851
+ 'sequential-await-to-forkjoin',
852
+ 'missing-output-transform',
853
+ 'subscription-transform',
854
+ 'library-extraction',
855
+ ].includes(transformation)
856
+ ? transformation
857
+ : undefined,
858
+ ...params.options,
859
+ },
860
+ },
861
+ };
862
+ // Use streaming transformation
863
+ for await (const event of wrapper.transformStreaming([], [filePath], transformConfig)) {
864
+ // Add each streaming event to the store
865
+ store.addEvent(operationId, event);
866
+ }
867
+ // Mark complete
868
+ store.markComplete(operationId);
869
+ }
870
+ /**
871
+ * Execute batch transformation (Phase 6a).
872
+ */
873
+ async executeBatch(params, orchestration) {
874
+ if (!params.files || params.files.length === 0) {
875
+ throw new Error('files array is required for batch mode');
876
+ }
877
+ if (!params.transformation) {
878
+ throw new Error('transformation is required');
879
+ }
880
+ // Load config from .angular-modernizer.json and merge with params
881
+ const firstFile = params.files[0];
882
+ if (!firstFile) {
883
+ throw new Error('files array cannot be empty');
884
+ }
885
+ const projectRoot = this.findProjectRoot(firstFile);
886
+ const fullConfig = loadConfig(projectRoot);
887
+ const config = fullConfig.tools?.['transform-code'] ?? {};
888
+ const mergedParams = { ...config, ...params };
889
+ // Use orchestration options for batch transformation (parallel defaults to false for safety)
890
+ const batchOptions = {
891
+ files: mergedParams.files,
892
+ transformation: mergedParams.transformation,
893
+ options: mergedParams.options,
894
+ parallel: orchestration.parallel ?? false,
895
+ enableProgress: orchestration.enableProgress ?? false,
896
+ signal: mergedParams.signal,
897
+ resourceLimits: orchestration.resourceLimits
898
+ ? {
899
+ maxMemory: orchestration.resourceLimits.maxMemory,
900
+ maxWorkers: orchestration.resourceLimits.maxWorkers ??
901
+ orchestration.maxWorkers,
902
+ }
903
+ : undefined,
904
+ rollbackStrategy: mergedParams.rollbackStrategy ?? 'all-or-nothing',
905
+ // Options
906
+ useWorkerThreads: orchestration.useWorkerThreads,
907
+ autoSelectMode: orchestration.autoSelectMode,
908
+ maxWorkers: orchestration.maxWorkers,
909
+ timeout: orchestration.timeout,
910
+ pluginIds: orchestration.pluginIds,
911
+ };
912
+ const result = await executeBatchTransformation(batchOptions, async (filePath) => {
913
+ return this.transformSingleFile(filePath, params, projectRoot);
914
+ });
915
+ // Convert batch result to TransformationResult format
916
+ return {
917
+ success: result.success,
918
+ files: result.files,
919
+ transformation: params.transformation,
920
+ changes: {
921
+ linesChanged: 0, // Aggregated in batch handler
922
+ additions: 0,
923
+ deletions: 0,
924
+ },
925
+ validation: {
926
+ syntaxValid: true, // Simplified for batch mode
927
+ typeCheckPassed: true,
928
+ },
929
+ orchestration: result.orchestration,
930
+ progress: result.progress,
931
+ };
932
+ }
933
+ /**
934
+ * Transform a single file (internal helper for batch mode).
935
+ */
936
+ async transformSingleFile(filePath, params, projectRoot) {
937
+ try {
938
+ const tsConfigPath = findTsConfig(projectRoot);
939
+ if (!tsConfigPath) {
940
+ return {
941
+ success: false,
942
+ error: 'Could not find tsconfig.json',
943
+ changes: { linesChanged: 0, additions: 0, deletions: 0 },
944
+ };
945
+ }
946
+ const kernel = new Kernel({
947
+ tsConfigPath,
948
+ plugins: [new AngularPlugin()],
949
+ });
950
+ await kernel.initialize();
951
+ const project = kernel.getProject();
952
+ const sourceFile = project.addSourceFileAtPath(filePath);
953
+ const linesBefore = sourceFile.getFullText().split('\n').length;
954
+ const transformConfig = {
955
+ dryRun: false,
956
+ autoSave: true,
957
+ pluginConfig: {
958
+ '@angular-modernizer/plugin-standalone': {
959
+ transformationType: params.transformation === 'standalone-migration'
960
+ ? params.transformation
961
+ : undefined,
962
+ ...params.options,
963
+ },
964
+ '@angular-modernizer/plugin-angular': {
965
+ transformationType: [
966
+ 'constructor-to-inject',
967
+ 'interface-extraction',
968
+ 'dependency-injection-migration',
969
+ 'facade-pattern',
970
+ 'form-modernization',
971
+ 'constructor-injection-transform',
972
+ 'component-inputs-interface-extraction',
973
+ 'service-injection-cleanup',
974
+ 'container-presentational',
975
+ 'core-shared-modules',
976
+ 'inheritance-to-composition',
977
+ 'promise-service-to-observable',
978
+ 'promise-component-to-reactive',
979
+ 'promise-cleanup',
980
+ 'sequential-await-to-forkjoin',
981
+ 'missing-output-transform',
982
+ 'subscription-transform',
983
+ 'library-extraction',
984
+ ].includes(params.transformation ?? '')
985
+ ? params.transformation
986
+ : undefined,
987
+ ...params.options,
988
+ },
989
+ },
990
+ };
991
+ const result = (await kernel.transformFile(sourceFile, transformConfig));
992
+ if (!transformConfig.dryRun && transformConfig.autoSave) {
993
+ await sourceFile.save();
994
+ }
995
+ const linesAfter = sourceFile.getFullText().split('\n').length;
996
+ const additions = Math.max(0, linesAfter - linesBefore);
997
+ const deletions = Math.max(0, linesBefore - linesAfter);
998
+ const linesChanged = result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0);
999
+ return {
1000
+ success: result.success,
1001
+ changes: { linesChanged, additions, deletions },
1002
+ };
1003
+ }
1004
+ catch (error) {
1005
+ return {
1006
+ success: false,
1007
+ error: error instanceof Error ? error.message : String(error),
1008
+ changes: { linesChanged: 0, additions: 0, deletions: 0 },
1009
+ };
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Find the project root from a file path.
1014
+ */
1015
+ findProjectRoot(filePath) {
1016
+ // Simple heuristic: go up until we find a tsconfig.json or package.json
1017
+ let currentDir = filePath;
1018
+ while (currentDir !== '/' && currentDir !== '.') {
1019
+ currentDir = resolve(currentDir, '..');
1020
+ const tsConfigPath = resolve(currentDir, 'tsconfig.json');
1021
+ const packageJsonPath = resolve(currentDir, 'package.json');
1022
+ try {
1023
+ readFileSync(tsConfigPath);
1024
+ return currentDir;
1025
+ }
1026
+ catch {
1027
+ // Continue
1028
+ }
1029
+ try {
1030
+ readFileSync(packageJsonPath);
1031
+ return currentDir;
1032
+ }
1033
+ catch {
1034
+ // Continue
1035
+ }
1036
+ }
1037
+ // Fallback to current directory
1038
+ return '.';
1039
+ }
1040
+ /**
1041
+ * Validate the transformation.
1042
+ */
1043
+ async validateTransformation(filePath, _transformation) {
1044
+ // Basic validation - check if file can be parsed
1045
+ const fs = await import('node:fs/promises');
1046
+ const content = await fs.readFile(filePath, 'utf-8');
1047
+ let syntaxValid = true;
1048
+ try {
1049
+ // Try to parse as TypeScript
1050
+ const ts = await import('typescript');
1051
+ ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
1052
+ // If we get here without errors, syntax is valid
1053
+ }
1054
+ catch {
1055
+ syntaxValid = false;
1056
+ }
1057
+ // For now, assume type checking passes if syntax is valid
1058
+ // In a real implementation, you'd run tsc or similar
1059
+ const typeCheckPassed = syntaxValid;
1060
+ return {
1061
+ syntaxValid,
1062
+ typeCheckPassed,
1063
+ };
1064
+ }
1065
+ /**
1066
+ * Get validation schema for a specific transformation type.
1067
+ */
1068
+ getSchemaForTransformation(transformation) {
1069
+ const schemas = {
1070
+ 'constructor-to-inject': {
1071
+ requiresClass: true,
1072
+ description: 'Requires classes with constructor parameters',
1073
+ },
1074
+ 'interface-extraction': {
1075
+ description: 'Requires type literals or inline types',
1076
+ },
1077
+ 'standalone-migration': {
1078
+ requiresDecorator: 'Component',
1079
+ description: 'Requires @Component decorator',
1080
+ },
1081
+ 'dependency-injection-migration': {
1082
+ requiresDecorator: 'Injectable',
1083
+ description: 'Requires @Injectable decorator',
1084
+ },
1085
+ 'facade-pattern': {
1086
+ requiresClass: true,
1087
+ requiresDecorator: 'Injectable',
1088
+ description: 'Requires service class with @Injectable decorator',
1089
+ },
1090
+ 'form-modernization': {
1091
+ requiresImport: 'FormsModule',
1092
+ description: 'Requires template-driven forms imports',
1093
+ },
1094
+ 'constructor-injection-transform': {
1095
+ requiresClass: true,
1096
+ description: 'Requires classes with manual service instantiation',
1097
+ },
1098
+ 'component-inputs-interface-extraction': {
1099
+ requiresDecorator: 'Component',
1100
+ description: 'Requires @Component decorator with @Input properties',
1101
+ },
1102
+ 'service-injection-cleanup': {
1103
+ requiresClass: true,
1104
+ description: 'Requires pseudo-service classes to convert',
1105
+ },
1106
+ 'container-presentational': {
1107
+ requiresDecorator: 'Component',
1108
+ description: 'Requires @Component decorator with mixed responsibilities',
1109
+ },
1110
+ 'core-shared-modules': {
1111
+ description: 'Requires module files for migration',
1112
+ },
1113
+ };
1114
+ return schemas[transformation] ?? {};
1115
+ }
1116
+ /**
1117
+ * Validate that the transformation type exists in the schema.
1118
+ * Throws descriptive error with suggestions if not found.
1119
+ *
1120
+ * @param transformation - Transformation type to validate
1121
+ * @throws Error if transformation type is not found
1122
+ */
1123
+ validateTransformationType(transformation) {
1124
+ // Get the enum values from the schema (these are what users actually pass)
1125
+ const schema = this.inputSchema;
1126
+ const transformationEnum = schema.properties?.transformation?.enum ?? [];
1127
+ // Check if the requested transformation exists in the enum
1128
+ const transformationExists = transformationEnum.includes(transformation);
1129
+ if (!transformationExists) {
1130
+ // Transformation not found - provide helpful error with suggestions
1131
+ // Get available rules for display names
1132
+ const availableRules = getAvailableRules(schema);
1133
+ // Create a list of rules using enum values as IDs for better fuzzy matching
1134
+ const enumRules = transformationEnum.map((enumValue) => {
1135
+ const rule = availableRules.find((r) => r.id.includes(enumValue) ||
1136
+ enumValue.includes(r.id.split(':')[1] ?? ''));
1137
+ return {
1138
+ id: enumValue, // Use enum value as ID for fuzzy matching
1139
+ name: rule?.name ?? enumValue,
1140
+ description: rule?.description,
1141
+ };
1142
+ });
1143
+ // Find similar rules based on enum values (use higher threshold for better suggestions)
1144
+ const similarRules = findSimilarRules(transformation, enumRules, 15);
1145
+ let errorMessage = `Transformation '${transformation}' not found.\n\n`;
1146
+ // List available transformations (use enum values, not rule IDs)
1147
+ errorMessage += 'Available transformations:\n';
1148
+ for (const enumValue of transformationEnum) {
1149
+ const rule = availableRules.find((r) => r.id.includes(enumValue) ||
1150
+ enumValue.includes(r.id.split(':')[1] ?? ''));
1151
+ const ruleName = rule?.name ?? enumValue;
1152
+ errorMessage += ` - ${enumValue} (${ruleName})\n`;
1153
+ }
1154
+ // Add suggestions if similar rules found
1155
+ if (similarRules.length > 0) {
1156
+ errorMessage += '\nDid you mean:\n';
1157
+ for (const similar of similarRules) {
1158
+ errorMessage += ` - ${similar.id} (distance: ${similar.distance})\n`;
1159
+ }
1160
+ }
1161
+ // Add helpful note about finding transformation types
1162
+ errorMessage +=
1163
+ '\nTo find available transformations, check the tool schema or documentation:\n';
1164
+ errorMessage +=
1165
+ ' - MCP tool schema: inputSchema.properties.transformation.enum\n';
1166
+ errorMessage += ' - Plugin source: packages/plugin-*/src/rules/*.ts\n';
1167
+ throw new Error(errorMessage);
1168
+ }
1169
+ }
1170
+ }
1171
+ //# sourceMappingURL=transform-code.js.map