@openrewrite/rewrite 8.66.0 → 8.66.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 (75) hide show
  1. package/dist/javascript/comparator.d.ts +67 -4
  2. package/dist/javascript/comparator.d.ts.map +1 -1
  3. package/dist/javascript/comparator.js +523 -2794
  4. package/dist/javascript/comparator.js.map +1 -1
  5. package/dist/javascript/format.d.ts.map +1 -1
  6. package/dist/javascript/format.js +4 -3
  7. package/dist/javascript/format.js.map +1 -1
  8. package/dist/javascript/index.d.ts +1 -1
  9. package/dist/javascript/index.d.ts.map +1 -1
  10. package/dist/javascript/index.js +1 -1
  11. package/dist/javascript/index.js.map +1 -1
  12. package/dist/javascript/parser.d.ts.map +1 -1
  13. package/dist/javascript/parser.js +18 -16
  14. package/dist/javascript/parser.js.map +1 -1
  15. package/dist/javascript/templating/capture.d.ts +226 -0
  16. package/dist/javascript/templating/capture.d.ts.map +1 -0
  17. package/dist/javascript/templating/capture.js +371 -0
  18. package/dist/javascript/templating/capture.js.map +1 -0
  19. package/dist/javascript/templating/comparator.d.ts +61 -0
  20. package/dist/javascript/templating/comparator.d.ts.map +1 -0
  21. package/dist/javascript/templating/comparator.js +393 -0
  22. package/dist/javascript/templating/comparator.js.map +1 -0
  23. package/dist/javascript/templating/engine.d.ts +75 -0
  24. package/dist/javascript/templating/engine.d.ts.map +1 -0
  25. package/dist/javascript/templating/engine.js +228 -0
  26. package/dist/javascript/templating/engine.js.map +1 -0
  27. package/dist/javascript/templating/index.d.ts +6 -0
  28. package/dist/javascript/templating/index.d.ts.map +1 -0
  29. package/dist/javascript/templating/index.js +42 -0
  30. package/dist/javascript/templating/index.js.map +1 -0
  31. package/dist/javascript/templating/pattern.d.ts +171 -0
  32. package/dist/javascript/templating/pattern.d.ts.map +1 -0
  33. package/dist/javascript/templating/pattern.js +681 -0
  34. package/dist/javascript/templating/pattern.js.map +1 -0
  35. package/dist/javascript/templating/placeholder-replacement.d.ts +58 -0
  36. package/dist/javascript/templating/placeholder-replacement.d.ts.map +1 -0
  37. package/dist/javascript/templating/placeholder-replacement.js +365 -0
  38. package/dist/javascript/templating/placeholder-replacement.js.map +1 -0
  39. package/dist/javascript/templating/rewrite.d.ts +39 -0
  40. package/dist/javascript/templating/rewrite.d.ts.map +1 -0
  41. package/dist/javascript/templating/rewrite.js +81 -0
  42. package/dist/javascript/templating/rewrite.js.map +1 -0
  43. package/dist/javascript/templating/template.d.ts +204 -0
  44. package/dist/javascript/templating/template.d.ts.map +1 -0
  45. package/dist/javascript/templating/template.js +293 -0
  46. package/dist/javascript/templating/template.js.map +1 -0
  47. package/dist/javascript/templating/types.d.ts +263 -0
  48. package/dist/javascript/templating/types.d.ts.map +1 -0
  49. package/dist/javascript/templating/types.js +3 -0
  50. package/dist/javascript/templating/types.js.map +1 -0
  51. package/dist/javascript/templating/utils.d.ts +118 -0
  52. package/dist/javascript/templating/utils.d.ts.map +1 -0
  53. package/dist/javascript/templating/utils.js +253 -0
  54. package/dist/javascript/templating/utils.js.map +1 -0
  55. package/dist/version.txt +1 -1
  56. package/package.json +2 -1
  57. package/src/javascript/comparator.ts +554 -3323
  58. package/src/javascript/format.ts +3 -2
  59. package/src/javascript/index.ts +1 -1
  60. package/src/javascript/parser.ts +19 -17
  61. package/src/javascript/templating/capture.ts +503 -0
  62. package/src/javascript/templating/comparator.ts +430 -0
  63. package/src/javascript/templating/engine.ts +252 -0
  64. package/src/javascript/templating/index.ts +60 -0
  65. package/src/javascript/templating/pattern.ts +727 -0
  66. package/src/javascript/templating/placeholder-replacement.ts +372 -0
  67. package/src/javascript/templating/rewrite.ts +95 -0
  68. package/src/javascript/templating/template.ts +326 -0
  69. package/src/javascript/templating/types.ts +300 -0
  70. package/src/javascript/templating/utils.ts +284 -0
  71. package/dist/javascript/templating.d.ts +0 -265
  72. package/dist/javascript/templating.d.ts.map +0 -1
  73. package/dist/javascript/templating.js +0 -1027
  74. package/dist/javascript/templating.js.map +0 -1
  75. package/src/javascript/templating.ts +0 -1226
@@ -1,1226 +0,0 @@
1
- /*
2
- * Copyright 2025 the original author or authors.
3
- * <p>
4
- * Licensed under the Moderne Source Available License (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- * <p>
8
- * https://docs.moderne.io/licensing/moderne-source-available-license
9
- * <p>
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import {JS} from '.';
17
- import {JavaScriptParser} from './parser';
18
- import {JavaScriptVisitor} from './visitor';
19
- import {Cursor, isTree, Tree} from '..';
20
- import {emptySpace, J} from '../java';
21
- import {produce} from "immer";
22
- import {JavaScriptSemanticComparatorVisitor} from "./comparator";
23
- import {DependencyWorkspace} from './dependency-workspace';
24
- import {emptyMarkers, Marker} from '../markers';
25
- import {randomId} from '../uuid';
26
-
27
- /**
28
- * Cache for compiled templates and patterns.
29
- * Stores parsed ASTs to avoid expensive re-parsing and dependency resolution.
30
- */
31
- class TemplateCache {
32
- private cache = new Map<string, JS.CompilationUnit>();
33
-
34
- /**
35
- * Generates a cache key from template string, captures, and options.
36
- */
37
- private generateKey(
38
- templateString: string,
39
- captures: Capture[],
40
- imports: string[],
41
- dependencies: Record<string, string>
42
- ): string {
43
- // Use the actual template string (with placeholders) as the primary key
44
- const templateKey = templateString;
45
-
46
- // Capture names
47
- const capturesKey = captures.map(c => c.name).join(',');
48
-
49
- // Imports
50
- const importsKey = imports.join(';');
51
-
52
- // Dependencies
53
- const depsKey = JSON.stringify(dependencies || {});
54
-
55
- return `${templateKey}::${capturesKey}::${importsKey}::${depsKey}`;
56
- }
57
-
58
- /**
59
- * Gets a cached compilation unit or creates and caches a new one.
60
- */
61
- async getOrParse(
62
- templateString: string,
63
- captures: Capture[],
64
- imports: string[],
65
- dependencies: Record<string, string>
66
- ): Promise<JS.CompilationUnit> {
67
- const key = this.generateKey(templateString, captures, imports, dependencies);
68
-
69
- let cu = this.cache.get(key);
70
- if (cu) {
71
- return cu;
72
- }
73
-
74
- // Create workspace if dependencies are provided
75
- // DependencyWorkspace has its own cache, so multiple templates with
76
- // the same dependencies will automatically share the same workspace
77
- let workspaceDir: string | undefined;
78
- if (dependencies && Object.keys(dependencies).length > 0) {
79
- workspaceDir = await DependencyWorkspace.getOrCreateWorkspace(dependencies);
80
- }
81
-
82
- // Prepend imports for type attribution context
83
- const fullTemplateString = imports.length > 0
84
- ? imports.join('\n') + '\n' + templateString
85
- : templateString;
86
-
87
- // Parse and cache (workspace only needed during parsing)
88
- const parser = new JavaScriptParser({relativeTo: workspaceDir});
89
- const parseGenerator = parser.parse({text: fullTemplateString, sourcePath: 'template.ts'});
90
- cu = (await parseGenerator.next()).value as JS.CompilationUnit;
91
-
92
- this.cache.set(key, cu);
93
- return cu;
94
- }
95
-
96
- /**
97
- * Clears the cache.
98
- */
99
- clear(): void {
100
- this.cache.clear();
101
- }
102
- }
103
-
104
- // Global cache instance
105
- const templateCache = new TemplateCache();
106
-
107
- /**
108
- * Marker that stores capture metadata on pattern AST nodes.
109
- * This avoids the need to parse capture names from identifiers during matching.
110
- */
111
- class CaptureMarker implements Marker {
112
- readonly kind = 'org.openrewrite.javascript.CaptureMarker';
113
- readonly id = randomId();
114
-
115
- constructor(
116
- public readonly captureName: string
117
- ) {
118
- }
119
- }
120
-
121
- /**
122
- * A comparator for pattern matching that is lenient about optional properties.
123
- * Allows patterns without type annotations to match actual code with type annotations.
124
- * Uses semantic comparison to match semantically equivalent code (e.g., isDate() and util.isDate()).
125
- */
126
- class PatternMatchingComparator extends JavaScriptSemanticComparatorVisitor {
127
- constructor(private readonly matcher: { handleCapture: (pattern: J, target: J) => boolean }) {
128
- super();
129
- }
130
-
131
- /**
132
- * Creates a wildcard identifier that will match any AST node during comparison.
133
- * The identifier has a CaptureMarker which causes it to match anything without storing the result.
134
- *
135
- * @param captureName The name for the capture marker (for debugging purposes)
136
- * @returns A wildcard identifier
137
- */
138
- private createWildcardIdentifier(captureName: string): J.Identifier {
139
- return {
140
- id: randomId(),
141
- kind: J.Kind.Identifier,
142
- prefix: emptySpace,
143
- markers: {
144
- ...emptyMarkers,
145
- markers: [new CaptureMarker(captureName)]
146
- },
147
- annotations: [],
148
- simpleName: '__wildcard__',
149
- type: undefined,
150
- fieldType: undefined
151
- };
152
- }
153
-
154
- override async visit<R extends J>(j: Tree, p: J, parent?: Cursor): Promise<R | undefined> {
155
- // Check if the pattern node is a capture - this handles captures anywhere in the tree
156
- if (PlaceholderUtils.isCapture(j as J)) {
157
- const success = this.matcher.handleCapture(j as J, p);
158
- if (!success) {
159
- return this.abort(j) as R;
160
- }
161
- return j as R;
162
- }
163
-
164
- if (!this.match) {
165
- return j as R;
166
- }
167
-
168
- return super.visit(j, p, parent);
169
- }
170
-
171
- override async visitVariableDeclarations(variableDeclarations: J.VariableDeclarations, other: J): Promise<J | undefined> {
172
- if (!this.match || other.kind !== J.Kind.VariableDeclarations) {
173
- return this.abort(variableDeclarations);
174
- }
175
-
176
- const otherVariableDeclarations = other as J.VariableDeclarations;
177
-
178
- // LENIENT: If pattern lacks typeExpression but target has one, add a wildcard capture to pattern
179
- // This allows the pattern to match without requiring us to modify the target (which would corrupt captures)
180
- if (!variableDeclarations.typeExpression && otherVariableDeclarations.typeExpression) {
181
- variableDeclarations = produce(variableDeclarations, draft => {
182
- draft.typeExpression = this.createWildcardIdentifier('__wildcard_type__') as J.Identifier;
183
- });
184
- }
185
-
186
- // Delegate to super implementation
187
- return super.visitVariableDeclarations(variableDeclarations, otherVariableDeclarations);
188
- }
189
-
190
- override async visitMethodDeclaration(methodDeclaration: J.MethodDeclaration, other: J): Promise<J | undefined> {
191
- if (!this.match || other.kind !== J.Kind.MethodDeclaration) {
192
- return this.abort(methodDeclaration);
193
- }
194
-
195
- const otherMethodDeclaration = other as J.MethodDeclaration;
196
-
197
- // LENIENT: If pattern lacks returnTypeExpression but target has one, add a wildcard capture to pattern
198
- // This allows the pattern to match without requiring us to modify the target (which would corrupt captures)
199
- if (!methodDeclaration.returnTypeExpression && otherMethodDeclaration.returnTypeExpression) {
200
- methodDeclaration = produce(methodDeclaration, draft => {
201
- draft.returnTypeExpression = this.createWildcardIdentifier('__wildcard_return_type__') as J.Identifier;
202
- });
203
- }
204
-
205
- // Delegate to super implementation
206
- return super.visitMethodDeclaration(methodDeclaration, otherMethodDeclaration);
207
- }
208
-
209
- protected hasSameKind(j: J, other: J): boolean {
210
- return super.hasSameKind(j, other) ||
211
- (j.kind == J.Kind.Identifier && PlaceholderUtils.isCapture(j as J.Identifier));
212
- }
213
-
214
- override async visitIdentifier(identifier: J.Identifier, other: J): Promise<J | undefined> {
215
- if (PlaceholderUtils.isCapture(identifier)) {
216
- const success = this.matcher.handleCapture(identifier, other);
217
- return success ? identifier : this.abort(identifier);
218
- }
219
- return super.visitIdentifier(identifier, other);
220
- }
221
- }
222
-
223
- /**
224
- * Capture specification for pattern matching.
225
- * Represents a placeholder in a template pattern that can capture a part of the AST.
226
- */
227
- export interface Capture {
228
- /**
229
- * The name of the capture, used to retrieve the captured node later.
230
- */
231
- name: string;
232
- }
233
-
234
- class CaptureImpl implements Capture {
235
- constructor(
236
- public readonly name: string
237
- ) {
238
- }
239
- }
240
-
241
- /**
242
- * Creates a capture specification for use in template patterns.
243
- *
244
- * @param name Optional name for the capture. If not provided, an auto-generated name is used.
245
- * @returns A Capture object
246
- *
247
- * @example
248
- * // Named inline captures
249
- * const pattern = pattern`${capture('left')} + ${capture('right')}`;
250
- *
251
- * // Unnamed captures
252
- * const {left, right} = {left: capture(), right: capture()};
253
- * const pattern = pattern`${left} + ${right}`;
254
- *
255
- * // Repeated patterns using the same capture
256
- * const expr = capture('expr');
257
- * const redundantOr = pattern`${expr} || ${expr}`;
258
- */
259
- export function capture(name?: string): Capture {
260
- if (name) {
261
- return new CaptureImpl(name);
262
- }
263
- return new CaptureImpl(`unnamed_${capture.nextUnnamedId++}`);
264
- }
265
-
266
- // Static counter for generating unique IDs for unnamed captures
267
- capture.nextUnnamedId = 1;
268
-
269
- /**
270
- * Concise alias for `capture`. Works well for inline captures in patterns and templates.
271
- *
272
- * @param name Optional name for the capture. If not provided, an auto-generated name is used.
273
- * @returns A Capture object
274
- *
275
- * @example
276
- * // Inline captures with _ alias
277
- * pattern`isDate(${_('dateArg')})`
278
- * template`${_('dateArg')} instanceof Date`
279
- */
280
- export const _ = capture;
281
-
282
- /**
283
- * Configuration options for patterns.
284
- */
285
- export interface PatternOptions {
286
- /**
287
- * Import statements to provide type attribution context.
288
- * These are prepended to the pattern when parsing to ensure proper type information.
289
- */
290
- imports?: string[];
291
-
292
- /**
293
- * NPM dependencies required for import resolution and type attribution.
294
- * Maps package names to version specifiers (e.g., { 'util': '^1.0.0' }).
295
- * The template engine will create a package.json with these dependencies.
296
- */
297
- dependencies?: Record<string, string>;
298
- }
299
-
300
- /**
301
- * Represents a pattern that can be matched against AST nodes.
302
- */
303
- export class Pattern {
304
- private _options: PatternOptions = {};
305
-
306
- /**
307
- * Gets the configuration options for this pattern.
308
- * @readonly
309
- */
310
- get options(): Readonly<PatternOptions> {
311
- return this._options;
312
- }
313
-
314
- /**
315
- * Creates a new pattern from template parts and captures.
316
- *
317
- * @param templateParts The string parts of the template
318
- * @param captures The captures between the string parts
319
- */
320
- constructor(
321
- public readonly templateParts: TemplateStringsArray,
322
- public readonly captures: Capture[]
323
- ) {
324
- }
325
-
326
- /**
327
- * Configures this pattern with additional options.
328
- *
329
- * @param options Configuration options
330
- * @returns This pattern for method chaining
331
- *
332
- * @example
333
- * pattern`isDate(${capture('date')})`
334
- * .configure({
335
- * imports: ['import { isDate } from "util"'],
336
- * dependencies: { 'util': '^1.0.0' }
337
- * })
338
- */
339
- configure(options: PatternOptions): Pattern {
340
- this._options = { ...this._options, ...options };
341
- return this;
342
- }
343
-
344
- /**
345
- * Creates a matcher for this pattern against a specific AST node.
346
- *
347
- * @param ast The AST node to match against
348
- * @returns A Matcher object
349
- */
350
- async match(ast: J): Promise<MatchResult | undefined> {
351
- const matcher = new Matcher(this, ast);
352
- const success = await matcher.matches();
353
- return success ? new MatchResult(matcher.getAll()) : undefined;
354
- }
355
- }
356
-
357
- export class MatchResult implements Pick<Map<string, J>, "get"> {
358
- constructor(
359
- private readonly bindings: Map<string, J> = new Map()
360
- ) {
361
- }
362
-
363
- get(capture: Capture | string): J | undefined {
364
- const name = typeof capture === "string" ? capture : capture.name;
365
- return this.bindings.get(name);
366
- }
367
- }
368
-
369
- /**
370
- * Matcher for checking if a pattern matches an AST node and extracting captured nodes.
371
- */
372
- class Matcher {
373
- private readonly bindings = new Map<string, J>();
374
- private patternAst?: J;
375
-
376
- /**
377
- * Creates a new matcher for a pattern against an AST node.
378
- *
379
- * @param pattern The pattern to match
380
- * @param ast The AST node to match against
381
- */
382
- constructor(
383
- private readonly pattern: Pattern,
384
- private readonly ast: J
385
- ) {
386
- }
387
-
388
- /**
389
- * Checks if the pattern matches the AST node.
390
- *
391
- * @returns true if the pattern matches, false otherwise
392
- */
393
- async matches(): Promise<boolean> {
394
- if (!this.patternAst) {
395
- const templateProcessor = new TemplateProcessor(
396
- this.pattern.templateParts,
397
- this.pattern.captures,
398
- this.pattern.options.imports || [],
399
- this.pattern.options.dependencies || {}
400
- );
401
- this.patternAst = await templateProcessor.toAstPattern();
402
- }
403
-
404
- return this.matchNode(this.patternAst, this.ast);
405
- }
406
-
407
- /**
408
- * Gets all captured nodes.
409
- *
410
- * @returns A map of capture names to captured nodes
411
- */
412
- getAll(): Map<string, J> {
413
- return new Map(this.bindings);
414
- }
415
-
416
- /**
417
- * Matches a pattern node against a target node.
418
- *
419
- * @param pattern The pattern node
420
- * @param target The target node
421
- * @returns true if the pattern matches the target, false otherwise
422
- */
423
- private async matchNode(pattern: J, target: J): Promise<boolean> {
424
- // Check if pattern is a capture placeholder
425
- if (PlaceholderUtils.isCapture(pattern)) {
426
- return this.handleCapture(pattern, target);
427
- }
428
-
429
- // Check if nodes have the same kind
430
- if (pattern.kind !== target.kind) {
431
- return false;
432
- }
433
-
434
- // Use the pattern matching comparator which is lenient about optional properties
435
- const comparator = new PatternMatchingComparator({
436
- handleCapture: (p, t) => this.handleCapture(p, t)
437
- });
438
- return await comparator.compare(pattern, target);
439
- }
440
-
441
- /**
442
- * Handles a capture placeholder.
443
- *
444
- * @param pattern The pattern node
445
- * @param target The target node
446
- * @returns true if the capture is successful, false otherwise
447
- */
448
- private handleCapture(pattern: J, target: J): boolean {
449
- const captureName = PlaceholderUtils.getCaptureName(pattern);
450
-
451
- if (!captureName) {
452
- return false;
453
- }
454
-
455
- // Store the binding
456
- this.bindings.set(captureName, target);
457
- return true;
458
- }
459
- }
460
-
461
- /**
462
- * Tagged template function for creating patterns.
463
- *
464
- * @param strings The string parts of the template
465
- * @param captures The captures between the string parts
466
- * @returns A Pattern object
467
- *
468
- * @example
469
- * // Using the same capture multiple times for repeated patterns
470
- * const expr = capture('expr');
471
- * const redundantOr = pattern`${expr} || ${expr}`;
472
- */
473
- export function pattern(strings: TemplateStringsArray, ...captures: (Capture | string)[]): Pattern {
474
- const capturesByName = captures.reduce((map, c) => {
475
- const capture = typeof c === "string" ? new CaptureImpl(c) : c;
476
- return map.set(capture.name, capture);
477
- }, new Map<string, Capture>());
478
- return new Pattern(strings, captures.map(c => capturesByName.get(typeof c === "string" ? c : c.name)!));
479
- }
480
-
481
- type JavaCoordinates = {
482
- tree?: Tree;
483
- loc?: JavaCoordinates.Location;
484
- mode?: JavaCoordinates.Mode;
485
- };
486
-
487
- namespace JavaCoordinates {
488
- // FIXME need to come up with the equivalent of `Space.Location` support
489
- export type Location = 'EXPRESSION_PREFIX' | 'STATEMENT_PREFIX' | 'BLOCK_END';
490
-
491
- export enum Mode {
492
- Before,
493
- After,
494
- Replace,
495
- }
496
- }
497
-
498
- /**
499
- * Valid parameter types for template literals.
500
- * - Capture: For pattern matching and reuse
501
- * - Tree: AST nodes to be inserted directly
502
- * - Primitives: Values to be converted to literals
503
- */
504
- export type TemplateParameter = Capture | Tree | string | number | boolean;
505
-
506
- /**
507
- * Configuration options for templates.
508
- */
509
- export interface TemplateOptions {
510
- /**
511
- * Import statements to provide type attribution context.
512
- * These are prepended to the template when parsing to ensure proper type information.
513
- */
514
- imports?: string[];
515
-
516
- /**
517
- * NPM dependencies required for import resolution and type attribution.
518
- * Maps package names to version specifiers (e.g., { 'util': '^1.0.0' }).
519
- * The template engine will create a package.json with these dependencies.
520
- */
521
- dependencies?: Record<string, string>;
522
- }
523
-
524
- /**
525
- * Template for creating AST nodes.
526
- *
527
- * This class provides the public API for template generation.
528
- * The actual templating logic is handled by the internal TemplateEngine.
529
- *
530
- * @example
531
- * // Generate a literal AST node
532
- * const result = template`2`.apply(cursor, coordinates);
533
- *
534
- * @example
535
- * // Generate an AST node with a parameter
536
- * const result = template`${capture()}`.apply(cursor, coordinates);
537
- */
538
- export class Template {
539
- private options: TemplateOptions = {};
540
-
541
- /**
542
- * Creates a new template.
543
- *
544
- * @param templateParts The string parts of the template
545
- * @param parameters The parameters between the string parts
546
- */
547
- constructor(
548
- private readonly templateParts: TemplateStringsArray,
549
- private readonly parameters: Parameter[]
550
- ) {
551
- }
552
-
553
- /**
554
- * Configures this template with additional options.
555
- *
556
- * @param options Configuration options
557
- * @returns This template for method chaining
558
- *
559
- * @example
560
- * template`isDate(${capture('date')})`
561
- * .configure({
562
- * imports: ['import { isDate } from "util"'],
563
- * dependencies: { 'util': '^1.0.0' }
564
- * })
565
- */
566
- configure(options: TemplateOptions): Template {
567
- this.options = { ...this.options, ...options };
568
- return this;
569
- }
570
-
571
- /**
572
- * Applies this template and returns the resulting tree.
573
- *
574
- * @param cursor The cursor pointing to the current location in the AST
575
- * @param tree Input tree
576
- * @param values values for parameters in template
577
- * @returns A Promise resolving to the generated AST node
578
- */
579
- async apply(cursor: Cursor, tree: J, values?: Pick<Map<string, J>, 'get'>): Promise<J | undefined> {
580
- return TemplateEngine.applyTemplate(
581
- this.templateParts,
582
- this.parameters,
583
- cursor,
584
- {
585
- tree,
586
- mode: JavaCoordinates.Mode.Replace
587
- },
588
- values,
589
- this.options.imports || [],
590
- this.options.dependencies || {}
591
- );
592
- }
593
- }
594
-
595
- export function template(strings: TemplateStringsArray, ...parameters: TemplateParameter[]): Template {
596
- // Convert parameters to Parameter objects (no longer need to check for mutable tree property)
597
- const processedParameters = parameters.map(param => {
598
- // Just wrap each parameter value in a Parameter object
599
- return {value: param};
600
- });
601
-
602
- return new Template(strings, processedParameters);
603
- }
604
-
605
- /**
606
- * Parameter specification for template generation.
607
- * Represents a placeholder in a template that will be replaced with a parameter value.
608
- */
609
- interface Parameter {
610
- /**
611
- * The value to substitute into the template.
612
- */
613
- value: any;
614
- }
615
-
616
- /**
617
- * Internal template engine - handles the core templating logic.
618
- * Not exported, so only visible within this module.
619
- */
620
- class TemplateEngine {
621
- /**
622
- * Applies a template with optional match results from pattern matching.
623
- *
624
- * @param templateParts The string parts of the template
625
- * @param parameters The parameters between the string parts
626
- * @param cursor The cursor pointing to the current location in the AST
627
- * @param coordinates The coordinates specifying where and how to insert the generated AST
628
- * @param values Map of capture names to values to replace the parameters with
629
- * @param imports Import statements to prepend for type attribution
630
- * @param dependencies NPM dependencies for type attribution
631
- * @returns A Promise resolving to the generated AST node
632
- */
633
- static async applyTemplate(
634
- templateParts: TemplateStringsArray,
635
- parameters: Parameter[],
636
- cursor: Cursor,
637
- coordinates: JavaCoordinates,
638
- values: Pick<Map<string, J>, 'get'> = new Map(),
639
- imports: string[] = [],
640
- dependencies: Record<string, string> = {}
641
- ): Promise<J | undefined> {
642
- // Build the template string with parameter placeholders
643
- const templateString = TemplateEngine.buildTemplateString(templateParts, parameters);
644
-
645
- // If the template string is empty, return undefined
646
- if (!templateString.trim()) {
647
- return undefined;
648
- }
649
-
650
- // Use cache to get or parse the compilation unit
651
- // For templates, we don't have captures, so use empty array
652
- const cu = await templateCache.getOrParse(
653
- templateString,
654
- [], // templates don't have captures in the cache key
655
- imports,
656
- dependencies
657
- );
658
-
659
- // Check if there are any statements
660
- if (!cu.statements || cu.statements.length === 0) {
661
- return undefined;
662
- }
663
-
664
- // Skip import statements to get to the actual template code
665
- const templateStatementIndex = imports.length;
666
- if (templateStatementIndex >= cu.statements.length) {
667
- return undefined;
668
- }
669
-
670
- // Extract the relevant part of the AST
671
- const firstStatement = cu.statements[templateStatementIndex].element;
672
- let extracted = firstStatement.kind === JS.Kind.ExpressionStatement ?
673
- (firstStatement as JS.ExpressionStatement).expression :
674
- firstStatement;
675
-
676
- // Create a copy to avoid sharing cached AST instances
677
- const ast = produce(extracted, draft => {});
678
-
679
- // Create substitutions map for placeholders
680
- const substitutions = new Map<string, Parameter>();
681
- for (let i = 0; i < parameters.length; i++) {
682
- const placeholder = `${PlaceholderUtils.PLACEHOLDER_PREFIX}${i}__`;
683
- substitutions.set(placeholder, parameters[i]);
684
- }
685
-
686
- // Unsubstitute placeholders with actual parameter values and match results
687
- const visitor = new PlaceholderReplacementVisitor(substitutions, values);
688
- const unsubstitutedAst = (await visitor.visit(ast, null))!;
689
-
690
- // Apply the template to the current AST
691
- return new TemplateApplier(cursor, coordinates, unsubstitutedAst, parameters).apply();
692
- }
693
-
694
- /**
695
- * Builds a template string with parameter placeholders.
696
- *
697
- * @param templateParts The string parts of the template
698
- * @param parameters The parameters between the string parts
699
- * @returns The template string
700
- */
701
- private static buildTemplateString(
702
- templateParts: TemplateStringsArray,
703
- parameters: Parameter[]
704
- ): string {
705
- let result = '';
706
- for (let i = 0; i < templateParts.length; i++) {
707
- result += templateParts[i];
708
- if (i < parameters.length) {
709
- const param = parameters[i].value;
710
- // Use a placeholder for Captures and Tree nodes
711
- // Inline everything else (strings, numbers, booleans) directly
712
- if (param instanceof CaptureImpl || isTree(param)) {
713
- const placeholder = `${PlaceholderUtils.PLACEHOLDER_PREFIX}${i}__`;
714
- result += placeholder;
715
- } else {
716
- result += param;
717
- }
718
- }
719
- }
720
- return result;
721
- }
722
- }
723
-
724
- /**
725
- * Utility class for managing placeholder naming and parsing.
726
- * Centralizes all logic related to capture placeholders.
727
- */
728
- class PlaceholderUtils {
729
- static readonly CAPTURE_PREFIX = '__capture_';
730
- static readonly PLACEHOLDER_PREFIX = '__PLACEHOLDER_';
731
-
732
- /**
733
- * Checks if a node is a capture placeholder.
734
- *
735
- * @param node The node to check
736
- * @returns true if the node is a capture placeholder, false otherwise
737
- */
738
- static isCapture(node: J): boolean {
739
- // Check for CaptureMarker first (efficient)
740
- for (const marker of node.markers.markers) {
741
- if (marker instanceof CaptureMarker) {
742
- return true;
743
- }
744
- }
745
- return false;
746
- }
747
-
748
- /**
749
- * Gets the capture name from a node with a CaptureMarker.
750
- *
751
- * @param node The node to extract capture name from
752
- * @returns The capture name, or null if not a capture
753
- */
754
- static getCaptureName(node: J): string | undefined {
755
- // Check for CaptureMarker
756
- for (const marker of node.markers.markers) {
757
- if (marker instanceof CaptureMarker) {
758
- return marker.captureName;
759
- }
760
- }
761
-
762
- return undefined;
763
- }
764
-
765
- /**
766
- * Parses a capture placeholder to extract name and type constraint.
767
- *
768
- * @param identifier The identifier string to parse
769
- * @returns Object with name and optional type constraint, or null if not a valid capture
770
- */
771
- static parseCapture(identifier: string): { name: string; typeConstraint?: string } | null {
772
- if (!identifier.startsWith(this.CAPTURE_PREFIX)) {
773
- return null;
774
- }
775
-
776
- // Handle unnamed captures: "__capture_unnamed_N__"
777
- if (identifier.startsWith(`${this.CAPTURE_PREFIX}unnamed_`)) {
778
- const match = identifier.match(/__capture_(unnamed_\d+)__/);
779
- return match ? {name: match[1]} : null;
780
- }
781
-
782
- // Handle named captures: "__capture_name__" or "__capture_name_type__"
783
- const match = identifier.match(/__capture_([^_]+)(?:_([^_]+))?__/);
784
- if (!match) {
785
- return null;
786
- }
787
-
788
- return {
789
- name: match[1],
790
- typeConstraint: match[2]
791
- };
792
- }
793
-
794
- /**
795
- * Creates a capture placeholder string.
796
- *
797
- * @param name The capture name
798
- * @param typeConstraint Optional type constraint
799
- * @returns The formatted placeholder string
800
- */
801
- static createCapture(name: string, typeConstraint?: string): string {
802
- return typeConstraint
803
- ? `${this.CAPTURE_PREFIX}${name}_${typeConstraint}__`
804
- : `${this.CAPTURE_PREFIX}${name}__`;
805
- }
806
- }
807
-
808
- /**
809
- * Visitor that replaces placeholder nodes with actual parameter values.
810
- */
811
- class PlaceholderReplacementVisitor extends JavaScriptVisitor<any> {
812
- constructor(
813
- private readonly substitutions: Map<string, Parameter>,
814
- private readonly values: Pick<Map<string, J>, 'get'> = new Map()
815
- ) {
816
- super();
817
- }
818
-
819
- async visit<R extends J>(tree: J, p: any, parent?: Cursor): Promise<R | undefined> {
820
- // Check if this node is a placeholder
821
- if (this.isPlaceholder(tree)) {
822
- const replacement = this.replacePlaceholder(tree);
823
- if (replacement !== tree) {
824
- return replacement as R;
825
- }
826
- }
827
-
828
- // Continue with normal traversal
829
- return super.visit(tree, p, parent);
830
- }
831
-
832
- /**
833
- * Checks if a node is a placeholder.
834
- *
835
- * @param node The node to check
836
- * @returns True if the node is a placeholder
837
- */
838
- private isPlaceholder(node: J): boolean {
839
- if (node.kind === J.Kind.Identifier) {
840
- const identifier = node as J.Identifier;
841
- return identifier.simpleName.startsWith(PlaceholderUtils.PLACEHOLDER_PREFIX);
842
- } else if (node.kind === J.Kind.Literal) {
843
- const literal = node as J.Literal;
844
- return literal.valueSource?.startsWith(PlaceholderUtils.PLACEHOLDER_PREFIX) || false;
845
- }
846
- return false;
847
- }
848
-
849
- /**
850
- * Replaces a placeholder node with the actual parameter value.
851
- *
852
- * @param placeholder The placeholder node
853
- * @returns The replacement node or the original if not a placeholder
854
- */
855
- private replacePlaceholder(placeholder: J): J {
856
- const placeholderText = this.getPlaceholderText(placeholder);
857
-
858
- if (!placeholderText || !placeholderText.startsWith(PlaceholderUtils.PLACEHOLDER_PREFIX)) {
859
- return placeholder;
860
- }
861
-
862
- // Find the corresponding parameter
863
- const param = this.substitutions.get(placeholderText);
864
- if (!param || param.value === undefined) {
865
- return placeholder;
866
- }
867
-
868
- // If the parameter value is a Capture, look up the matched result
869
- if (param.value instanceof CaptureImpl) {
870
- const matchedNode = this.values.get(param.value.name);
871
- if (matchedNode) {
872
- return produce(matchedNode, draft => {
873
- draft.markers = placeholder.markers;
874
- draft.prefix = placeholder.prefix;
875
- });
876
- }
877
- // If no match found, return placeholder unchanged
878
- return placeholder;
879
- }
880
-
881
- // If the parameter value is an AST node, use it directly
882
- if (isTree(param.value)) {
883
- // Return the AST node, preserving the original prefix
884
- return produce(param.value as J, draft => {
885
- draft.markers = placeholder.markers;
886
- draft.prefix = placeholder.prefix;
887
- });
888
- }
889
-
890
- return placeholder;
891
- }
892
-
893
- /**
894
- * Gets the placeholder text from a node.
895
- *
896
- * @param node The node to get placeholder text from
897
- * @returns The placeholder text or null
898
- */
899
- private getPlaceholderText(node: J): string | null {
900
- if (node.kind === J.Kind.Identifier) {
901
- return (node as J.Identifier).simpleName;
902
- } else if (node.kind === J.Kind.Literal) {
903
- return (node as J.Literal).valueSource || null;
904
- }
905
- return null;
906
- }
907
- }
908
-
909
- /**
910
- * Helper class for applying a template to an AST.
911
- */
912
- class TemplateApplier {
913
- constructor(
914
- private readonly cursor: Cursor,
915
- private readonly coordinates: JavaCoordinates,
916
- private readonly ast: J,
917
- private readonly parameters: Parameter[] = []
918
- ) {
919
- }
920
-
921
- /**
922
- * Applies the template to the current AST.
923
- *
924
- * @returns A Promise resolving to the modified AST
925
- */
926
- async apply(): Promise<J | undefined> {
927
- const {loc} = this.coordinates;
928
-
929
- // Apply the template based on the location and mode
930
- switch (loc || 'EXPRESSION_PREFIX') {
931
- case 'EXPRESSION_PREFIX':
932
- return this.applyToExpression();
933
- case 'STATEMENT_PREFIX':
934
- return this.applyToStatement();
935
- case 'BLOCK_END':
936
- return this.applyToBlock();
937
- default:
938
- throw new Error(`Unsupported location: ${loc}`);
939
- }
940
- }
941
-
942
- /**
943
- * Applies the template to an expression.
944
- *
945
- * @returns A Promise resolving to the modified AST
946
- */
947
- private async applyToExpression(): Promise<J | undefined> {
948
- const {tree} = this.coordinates;
949
-
950
- // Create a copy of the AST with the prefix from the target
951
- return tree ? produce(this.ast, draft => {
952
- draft.prefix = (tree as J).prefix;
953
- }) : this.ast;
954
- }
955
-
956
- /**
957
- * Applies the template to a statement.
958
- *
959
- * @returns A Promise resolving to the modified AST
960
- */
961
- private async applyToStatement(): Promise<J | undefined> {
962
- const {tree} = this.coordinates;
963
-
964
- // Create a copy of the AST with the prefix from the target
965
- return produce(this.ast, draft => {
966
- draft.prefix = (tree as J).prefix;
967
- });
968
- }
969
-
970
- /**
971
- * Applies the template to a block.
972
- *
973
- * @returns A Promise resolving to the modified AST
974
- */
975
- private async applyToBlock(): Promise<J | undefined> {
976
- const {tree} = this.coordinates;
977
-
978
- // Create a copy of the AST with the prefix from the target
979
- return produce(this.ast, draft => {
980
- draft.prefix = (tree as J).prefix;
981
- });
982
- }
983
- }
984
-
985
- /**
986
- * Processor for template strings.
987
- * Converts a template string with captures into an AST pattern.
988
- */
989
- class TemplateProcessor {
990
- /**
991
- * Creates a new template processor.
992
- *
993
- * @param templateParts The string parts of the template
994
- * @param captures The captures between the string parts
995
- * @param imports Import statements to prepend for type attribution
996
- * @param dependencies NPM dependencies for type attribution
997
- */
998
- constructor(
999
- private readonly templateParts: TemplateStringsArray,
1000
- private readonly captures: Capture[],
1001
- private readonly imports: string[] = [],
1002
- private readonly dependencies: Record<string, string> = {}
1003
- ) {
1004
- }
1005
-
1006
- /**
1007
- * Converts the template to an AST pattern.
1008
- *
1009
- * @returns A Promise resolving to the AST pattern
1010
- */
1011
- async toAstPattern(): Promise<J> {
1012
- // Combine template parts and placeholders
1013
- const templateString = this.buildTemplateString();
1014
-
1015
- // Use cache to get or parse the compilation unit
1016
- const cu = await templateCache.getOrParse(
1017
- templateString,
1018
- this.captures,
1019
- this.imports,
1020
- this.dependencies
1021
- );
1022
-
1023
- // Extract the relevant part of the AST
1024
- return this.extractPatternFromAst(cu);
1025
- }
1026
-
1027
- /**
1028
- * Builds a template string with placeholders for captures.
1029
- *
1030
- * @returns The template string
1031
- */
1032
- private buildTemplateString(): string {
1033
- let result = '';
1034
- for (let i = 0; i < this.templateParts.length; i++) {
1035
- result += this.templateParts[i];
1036
- if (i < this.captures.length) {
1037
- const capture = this.captures[i];
1038
- result += PlaceholderUtils.createCapture(capture.name);
1039
- }
1040
- }
1041
- return result;
1042
- }
1043
-
1044
- /**
1045
- * Extracts the pattern from the parsed AST.
1046
- *
1047
- * @param cu The compilation unit
1048
- * @returns The extracted pattern
1049
- */
1050
- private extractPatternFromAst(cu: JS.CompilationUnit): J {
1051
- // Skip import statements to get to the actual pattern code
1052
- const patternStatementIndex = this.imports.length;
1053
-
1054
- // Extract the relevant part of the AST based on the template content
1055
- const firstStatement = cu.statements[patternStatementIndex].element;
1056
-
1057
- let extracted: J;
1058
- // If the first statement is an expression statement, extract the expression
1059
- if (firstStatement.kind === JS.Kind.ExpressionStatement) {
1060
- extracted = (firstStatement as JS.ExpressionStatement).expression;
1061
- } else {
1062
- // Otherwise, return the statement itself
1063
- extracted = firstStatement;
1064
- }
1065
-
1066
- // Attach CaptureMarkers to capture identifiers
1067
- return this.attachCaptureMarkers(extracted);
1068
- }
1069
-
1070
- /**
1071
- * Attaches CaptureMarkers to capture identifiers in the AST.
1072
- * This allows efficient capture detection without string parsing.
1073
- *
1074
- * @param ast The AST to process
1075
- * @returns The AST with CaptureMarkers attached
1076
- */
1077
- private attachCaptureMarkers(ast: J): J {
1078
- const visited = new Set<any>();
1079
- return produce(ast, draft => {
1080
- this.visitAndAttachMarkers(draft, visited);
1081
- });
1082
- }
1083
-
1084
- /**
1085
- * Recursively visits AST nodes and attaches CaptureMarkers to capture identifiers.
1086
- *
1087
- * @param node The node to visit
1088
- * @param visited Set of already visited nodes to avoid cycles
1089
- */
1090
- private visitAndAttachMarkers(node: any, visited: Set<any>): void {
1091
- if (!node || typeof node !== 'object' || visited.has(node)) {
1092
- return;
1093
- }
1094
-
1095
- // Mark as visited to avoid cycles
1096
- visited.add(node);
1097
-
1098
- // If this is an identifier that looks like a capture, attach a marker
1099
- if (node.kind === J.Kind.Identifier && node.simpleName?.startsWith(PlaceholderUtils.CAPTURE_PREFIX)) {
1100
- const captureInfo = PlaceholderUtils.parseCapture(node.simpleName);
1101
- if (captureInfo) {
1102
- // Initialize markers if needed
1103
- if (!node.markers) {
1104
- node.markers = { kind: 'org.openrewrite.marker.Markers', id: randomId(), markers: [] };
1105
- }
1106
- if (!node.markers.markers) {
1107
- node.markers.markers = [];
1108
- }
1109
-
1110
- // Add CaptureMarker
1111
- node.markers.markers.push(new CaptureMarker(captureInfo.name));
1112
- }
1113
- }
1114
-
1115
- // Recursively visit all properties
1116
- for (const key in node) {
1117
- if (node.hasOwnProperty(key)) {
1118
- const value = node[key];
1119
- if (Array.isArray(value)) {
1120
- value.forEach(item => this.visitAndAttachMarkers(item, visited));
1121
- } else if (typeof value === 'object' && value !== null) {
1122
- this.visitAndAttachMarkers(value, visited);
1123
- }
1124
- }
1125
- }
1126
- }
1127
- }
1128
-
1129
- /**
1130
- * Represents a replacement rule that can match a pattern and apply a template.
1131
- */
1132
- export interface RewriteRule {
1133
- /**
1134
- * Attempts to apply this rewrite rule to the given AST node.
1135
- *
1136
- * @param cursor The cursor context at the current position in the AST
1137
- * @param node The AST node to try matching and transforming
1138
- * @returns The transformed node if a pattern matched, or `undefined` if no pattern matched.
1139
- * When using in a visitor, always use the `|| node` pattern to return the original
1140
- * node when there's no match: `return await rule.tryOn(this.cursor, node) || node;`
1141
- */
1142
- tryOn(cursor: Cursor, node: J): Promise<J | undefined>;
1143
- }
1144
-
1145
- /**
1146
- * Configuration for a replacement rule.
1147
- */
1148
- export interface RewriteConfig {
1149
- before: Pattern | Pattern[];
1150
- after: Template;
1151
- }
1152
-
1153
- /**
1154
- * Implementation of a replacement rule.
1155
- */
1156
- class RewriteRuleImpl implements RewriteRule {
1157
- constructor(
1158
- private readonly before: Pattern[],
1159
- private readonly after: Template
1160
- ) {
1161
- }
1162
-
1163
- async tryOn(cursor: Cursor, node: J): Promise<J | undefined> {
1164
- for (const pattern of this.before) {
1165
- const match = await pattern.match(node);
1166
- if (match) {
1167
- const result = await this.after.apply(cursor, node, match);
1168
- if (result) {
1169
- return result;
1170
- }
1171
- }
1172
- }
1173
-
1174
- // Return undefined if no patterns match
1175
- return undefined;
1176
- }
1177
- }
1178
-
1179
- /**
1180
- * Creates a replacement rule using a capture context and configuration.
1181
- *
1182
- * @param builderFn Function that takes a capture context and returns before/after configuration
1183
- * @returns A replacement rule that can be applied to AST nodes
1184
- *
1185
- * @example
1186
- * // Single pattern
1187
- * const swapOperands = rewrite(() => ({
1188
- * before: pattern`${"left"} + ${"right"}`,
1189
- * after: template`${"right"} + ${"left"}`
1190
- * }));
1191
- *
1192
- * @example
1193
- * // Multiple patterns
1194
- * const normalizeComparisons = rewrite(() => ({
1195
- * before: [
1196
- * pattern`${"left"} == ${"right"}`,
1197
- * pattern`${"left"} === ${"right"}`
1198
- * ],
1199
- * after: template`${"left"} === ${"right"}`
1200
- * }));
1201
- *
1202
- * @example
1203
- * // Using in a visitor - IMPORTANT: use `|| node` to handle undefined when no match
1204
- * class MyVisitor extends JavaScriptVisitor<any> {
1205
- * override async visitBinary(binary: J.Binary, p: any): Promise<J | undefined> {
1206
- * const rule = rewrite(() => ({
1207
- * before: pattern`${capture('a')} + ${capture('b')}`,
1208
- * after: template`${capture('b')} + ${capture('a')}`
1209
- * }));
1210
- * // tryOn() returns undefined if no pattern matches, so always use || node
1211
- * return await rule.tryOn(this.cursor, binary) || binary;
1212
- * }
1213
- * }
1214
- */
1215
- export function rewrite(
1216
- builderFn: () => RewriteConfig
1217
- ): RewriteRule {
1218
- const config = builderFn();
1219
-
1220
- // Ensure we have valid before and after properties
1221
- if (!config.before || !config.after) {
1222
- throw new Error('Builder function must return an object with before and after properties');
1223
- }
1224
-
1225
- return new RewriteRuleImpl(Array.isArray(config.before) ? config.before : [config.before], config.after);
1226
- }