@openrewrite/rewrite 8.97.1 → 8.97.2

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 (84) hide show
  1. package/README.md +42 -0
  2. package/dist/javascript/comparator.d.ts +16 -10
  3. package/dist/javascript/comparator.d.ts.map +1 -1
  4. package/dist/javascript/comparator.js +10 -8
  5. package/dist/javascript/comparator.js.map +1 -1
  6. package/dist/javascript/package-json-parser.d.ts +2 -0
  7. package/dist/javascript/package-json-parser.d.ts.map +1 -1
  8. package/dist/javascript/package-json-parser.js +27 -15
  9. package/dist/javascript/package-json-parser.js.map +1 -1
  10. package/dist/javascript/package-manager.d.ts +13 -4
  11. package/dist/javascript/package-manager.d.ts.map +1 -1
  12. package/dist/javascript/package-manager.js +134 -17
  13. package/dist/javascript/package-manager.js.map +1 -1
  14. package/dist/javascript/print.d.ts.map +1 -1
  15. package/dist/javascript/print.js +1 -1
  16. package/dist/javascript/print.js.map +1 -1
  17. package/dist/javascript/recipes/dependencies.d.ts +17 -0
  18. package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
  19. package/dist/javascript/recipes/dependencies.js +8 -0
  20. package/dist/javascript/recipes/dependencies.js.map +1 -1
  21. package/dist/javascript/templating/comparator.d.ts +32 -79
  22. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  23. package/dist/javascript/templating/comparator.js +35 -628
  24. package/dist/javascript/templating/comparator.js.map +1 -1
  25. package/dist/javascript/templating/debug.d.ts +143 -0
  26. package/dist/javascript/templating/debug.d.ts.map +1 -0
  27. package/dist/javascript/templating/debug.js +769 -0
  28. package/dist/javascript/templating/debug.js.map +1 -0
  29. package/dist/javascript/templating/index.d.ts +1 -1
  30. package/dist/javascript/templating/index.d.ts.map +1 -1
  31. package/dist/javascript/templating/index.js.map +1 -1
  32. package/dist/javascript/templating/pattern.d.ts +44 -35
  33. package/dist/javascript/templating/pattern.d.ts.map +1 -1
  34. package/dist/javascript/templating/pattern.js +224 -238
  35. package/dist/javascript/templating/pattern.js.map +1 -1
  36. package/dist/javascript/templating/rewrite.d.ts +4 -0
  37. package/dist/javascript/templating/rewrite.d.ts.map +1 -1
  38. package/dist/javascript/templating/rewrite.js +5 -1
  39. package/dist/javascript/templating/rewrite.js.map +1 -1
  40. package/dist/javascript/templating/types.d.ts +38 -35
  41. package/dist/javascript/templating/types.d.ts.map +1 -1
  42. package/dist/javascript/templating/utils.d.ts.map +1 -1
  43. package/dist/javascript/templating/utils.js +15 -0
  44. package/dist/javascript/templating/utils.js.map +1 -1
  45. package/dist/rewrite-javascript-version.txt +1 -1
  46. package/dist/rpc/request/install-recipes.d.ts +10 -0
  47. package/dist/rpc/request/install-recipes.d.ts.map +1 -1
  48. package/dist/rpc/request/install-recipes.js +51 -0
  49. package/dist/rpc/request/install-recipes.js.map +1 -1
  50. package/dist/rpc/request/prepare-recipe.d.ts +1 -0
  51. package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
  52. package/dist/rpc/request/prepare-recipe.js +13 -6
  53. package/dist/rpc/request/prepare-recipe.js.map +1 -1
  54. package/dist/test/rewrite-test.d.ts +1 -16
  55. package/dist/test/rewrite-test.d.ts.map +1 -1
  56. package/dist/test/rewrite-test.js +7 -58
  57. package/dist/test/rewrite-test.js.map +1 -1
  58. package/dist/util.d.ts +16 -0
  59. package/dist/util.d.ts.map +1 -1
  60. package/dist/util.js +53 -0
  61. package/dist/util.js.map +1 -1
  62. package/dist/yaml/parser.js +8 -5
  63. package/dist/yaml/parser.js.map +1 -1
  64. package/dist/yaml/print.js +9 -3
  65. package/dist/yaml/print.js.map +1 -1
  66. package/package.json +1 -1
  67. package/src/javascript/comparator.ts +66 -53
  68. package/src/javascript/package-json-parser.ts +25 -16
  69. package/src/javascript/package-manager.ts +121 -15
  70. package/src/javascript/print.ts +1 -2
  71. package/src/javascript/recipes/dependencies.ts +21 -0
  72. package/src/javascript/templating/comparator.ts +76 -766
  73. package/src/javascript/templating/debug.ts +806 -0
  74. package/src/javascript/templating/index.ts +1 -0
  75. package/src/javascript/templating/pattern.ts +267 -270
  76. package/src/javascript/templating/rewrite.ts +5 -1
  77. package/src/javascript/templating/types.ts +40 -37
  78. package/src/javascript/templating/utils.ts +0 -1
  79. package/src/rpc/request/install-recipes.ts +54 -0
  80. package/src/rpc/request/prepare-recipe.ts +18 -15
  81. package/src/test/rewrite-test.ts +2 -59
  82. package/src/util.ts +58 -0
  83. package/src/yaml/parser.ts +9 -5
  84. package/src/yaml/print.ts +9 -3
@@ -29,7 +29,8 @@ import * as fs from "fs";
29
29
  import * as fsp from "fs/promises";
30
30
  import * as path from "path";
31
31
  import * as YAML from "yaml";
32
- import {getLockFileDetectionConfig, getLockFileName, runList, runVersion} from "./package-manager";
32
+ import {getLockFileDetectionConfig, getLockFileName, PackageManagerSelectionError, runList, runVersion, selectPackageManager} from "./package-manager";
33
+ import {markupWarn} from "../markers";
33
34
  import picomatch from "picomatch";
34
35
  import {DEFAULT_DIR_EXCLUSIONS, walkDirs} from "../path-utils";
35
36
 
@@ -80,6 +81,9 @@ export class PackageJsonParser extends Parser {
80
81
  /** The NodeRuntime of each project root, by package manager and root directory, for the parser's lifetime */
81
82
  private readonly runtimes = new Map<string, NodeRuntime>();
82
83
 
84
+ private readonly selectedRoots = new Map<string, string>();
85
+ private readonly selectionFailures = new Map<string, string>();
86
+
83
87
  /** Fields to copy from package.json that contain dependency maps */
84
88
  private static readonly DEPENDENCY_FIELDS = [
85
89
  'dependencies',
@@ -173,13 +177,15 @@ export class PackageJsonParser extends Parser {
173
177
  const runtime = this.nodeRuntime(dir, marker?.packageManager);
174
178
 
175
179
  // Attach the markers to the JSON document: every one gets the NodeRuntime of its project
176
- yield {
180
+ const out: Json.Document = {
177
181
  ...jsonDoc,
178
182
  markers: {
179
183
  ...jsonDoc.markers,
180
184
  markers: [...jsonDoc.markers.markers, ...(marker ? [marker] : []), runtime]
181
185
  }
182
186
  };
187
+ const failure = this.selectionFailures.get(dir);
188
+ yield failure === undefined ? out : markupWarn(out, failure);
183
189
  }
184
190
  }
185
191
 
@@ -190,7 +196,8 @@ export class PackageJsonParser extends Parser {
190
196
  */
191
197
  private nodeRuntime(dir: string, packageManager?: PackageManager): NodeRuntime {
192
198
  const absoluteDir = path.resolve(this.relativeTo ?? '', dir);
193
- const root = packageManager === undefined ? absoluteDir : this.projectRoot(absoluteDir, packageManager);
199
+ const root = packageManager === undefined ? absoluteDir :
200
+ this.selectedRoots.get(absoluteDir) ?? this.projectRoot(absoluteDir, packageManager);
194
201
  const key = `${packageManager ?? ''}:${root}`;
195
202
  let runtime = this.runtimes.get(key);
196
203
  if (!runtime) {
@@ -222,6 +229,8 @@ export class PackageJsonParser extends Parser {
222
229
  * Creates a NodeResolutionResult marker from the package.json content and optional lock file.
223
230
  */
224
231
  private async createMarker(input: ParserInput, dir: string): Promise<NodeResolutionResult | null> {
232
+ this.selectionFailures.delete(dir);
233
+ this.selectedRoots.delete(path.resolve(this.relativeTo ?? "", dir));
225
234
  try {
226
235
  const content = parserInputRead(input);
227
236
  const packageJson = JSON.parse(content);
@@ -241,7 +250,7 @@ export class PackageJsonParser extends Parser {
241
250
  const absoluteDir = this.relativeTo && !path.isAbsolute(dir)
242
251
  ? path.resolve(this.relativeTo, dir)
243
252
  : dir;
244
- const lockResult = await this.tryReadLockFileWithWalkUp(absoluteDir, this.relativeTo);
253
+ const lockResult = await this.tryReadLockFileWithWalkUp(absoluteDir, this.relativeTo, packageJson);
245
254
  lockContent = lockResult?.content;
246
255
  packageManager = lockResult?.packageManager;
247
256
  }
@@ -285,6 +294,7 @@ export class PackageJsonParser extends Parser {
285
294
  npmrcConfigs.length > 0 ? npmrcConfigs : undefined
286
295
  );
287
296
  } catch (error) {
297
+ if (error instanceof PackageManagerSelectionError) this.selectionFailures.set(dir, error.message);
288
298
  console.warn(`Failed to create NodeResolutionResult marker: ${error}`);
289
299
  return null;
290
300
  }
@@ -464,8 +474,16 @@ export class PackageJsonParser extends Parser {
464
474
  */
465
475
  private async tryReadLockFileWithWalkUp(
466
476
  startDir: string,
467
- rootDir?: string
477
+ rootDir?: string,
478
+ manifest?: unknown
468
479
  ): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
480
+ const selected = selectPackageManager(startDir, rootDir, manifest);
481
+ if (selected) {
482
+ this.selectedRoots.set(path.resolve(startDir), selected.root);
483
+ if (selected.lockFile) return this.tryReadLockFile(selected.root, selected.packageManager);
484
+ const installed = await this.walkNodeModules(selected.root);
485
+ return {content: installed ?? {lockfileVersion: 0, packages: {}}, packageManager: selected.packageManager};
486
+ }
469
487
  // Normalize paths for comparison
470
488
  const normalizedRoot = rootDir ? path.resolve(rootDir) : undefined;
471
489
 
@@ -484,16 +502,6 @@ export class PackageJsonParser extends Parser {
484
502
  currentDir = parentDir;
485
503
  }
486
504
 
487
- // A lock file names the package manager, wherever it is on the way up. An installed
488
- // workspace member has node_modules of its own and no lock: its workspace's lock, above it,
489
- // says which package manager installed them.
490
- for (const dir of dirs) {
491
- const result = await this.tryReadLockFile(dir);
492
- if (result) {
493
- return result;
494
- }
495
- }
496
-
497
505
  // Fallback: node_modules without a lock file anywhere above (e.g., symlinked from another
498
506
  // workspace). Walk them for resolved dependency information, and assume npm.
499
507
  for (const dir of dirs) {
@@ -512,9 +520,10 @@ export class PackageJsonParser extends Parser {
512
520
  *
513
521
  * @returns Object with parsed lock file content and detected package manager, or undefined if no lock file found
514
522
  */
515
- private async tryReadLockFile(dir: string): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
523
+ private async tryReadLockFile(dir: string, selected?: PackageManager): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
516
524
  // Use shared lock file detection config (first match wins based on priority)
517
525
  for (const config of getLockFileDetectionConfig()) {
526
+ if (selected !== undefined && config.filename !== getLockFileName(selected)) continue;
518
527
  const lockPath = path.join(dir, config.filename);
519
528
  if (!fs.existsSync(lockPath)) {
520
529
  continue;
@@ -36,6 +36,8 @@ import * as os from "os";
36
36
  import {spawnSync} from "child_process";
37
37
  import {isDeepStrictEqual} from "util";
38
38
  import * as YAML from "yaml";
39
+ import * as semver from "semver";
40
+ import picomatch from "picomatch";
39
41
 
40
42
  /**
41
43
  * Configuration for each package manager.
@@ -193,30 +195,134 @@ interface InstallOptions {
193
195
  env?: Record<string, string>;
194
196
  }
195
197
 
198
+ /** A conflicting declaration must not produce a resolution graph from another manager's lock. */
199
+ export class PackageManagerSelectionError extends Error {
200
+ }
201
+
202
+ export interface PackageManagerSelection {
203
+ readonly packageManager: PackageManager;
204
+ readonly root: string;
205
+ readonly lockFile?: string;
206
+ }
207
+
208
+ function declaredPackageManager(manifest: unknown): PackageManager | undefined {
209
+ if (!manifest || typeof manifest !== "object") return undefined;
210
+ const value = (manifest as {packageManager?: unknown}).packageManager;
211
+ if (typeof value !== "string") return undefined;
212
+ const match = /^(npm|pnpm|bun|yarn)@(.+)$/.exec(value);
213
+ const version = match && semver.valid(match[2].split("+", 1)[0]);
214
+ if (!match || !version) return undefined;
215
+ switch (match[1]) {
216
+ case "npm": return PackageManager.Npm;
217
+ case "pnpm": return PackageManager.Pnpm;
218
+ case "bun": return PackageManager.Bun;
219
+ case "yarn": return semver.major(version) === 1 ? PackageManager.YarnClassic : PackageManager.YarnBerry;
220
+ default: return undefined;
221
+ }
222
+ }
223
+
224
+ function isWorkspaceMember(root: string, member: string, manifest: unknown): boolean {
225
+ let patterns: unknown = manifest && typeof manifest === "object" ?
226
+ (manifest as {workspaces?: unknown}).workspaces : undefined;
227
+ if (patterns && !Array.isArray(patterns) && typeof patterns === "object") {
228
+ patterns = (patterns as {packages?: unknown}).packages;
229
+ }
230
+ if (!Array.isArray(patterns)) {
231
+ try { patterns = YAML.parse(fs.readFileSync(path.join(root, "pnpm-workspace.yaml"), "utf8"))?.packages; }
232
+ catch { return false; }
233
+ }
234
+ if (!Array.isArray(patterns) || !patterns.every(p => typeof p === "string")) return false;
235
+ const relative = path.relative(root, member).split(path.sep).join("/");
236
+ const include = patterns.filter(p => !p.startsWith("!"));
237
+ const exclude = patterns.filter(p => p.startsWith("!")).map(p => p.slice(1));
238
+ return include.length > 0 && picomatch(include)(relative) &&
239
+ (exclude.length === 0 || !picomatch(exclude)(relative));
240
+ }
241
+
196
242
  /**
197
- * Detects the package manager used in a directory by checking for lock files.
198
- *
199
- * @param dir The directory to check
200
- * @returns The detected package manager, or undefined if none found
243
+ * Select a lock and its manager together. The nearest supported pinned declaration takes precedence over lock
244
+ * filename order, including when a workspace member inherits it. An explicit parser boundary limits the walk.
245
+ * The supplied manifest is the parser input at startDir, which may differ from the file on disk.
201
246
  */
202
- export function detectPackageManager(dir: string): PackageManager | undefined {
203
- for (const config of LOCK_FILE_DETECTION) {
204
- const lockPath = path.join(dir, config.filename);
205
- if (fs.existsSync(lockPath)) {
206
- if (typeof config.packageManager === 'function') {
207
- try {
208
- const content = fs.readFileSync(lockPath, 'utf-8');
209
- return config.packageManager(content);
210
- } catch {
211
- continue;
247
+ export function selectPackageManager(startDir: string, rootDir?: string, manifest?: unknown): PackageManagerSelection | undefined {
248
+ const dirs: string[] = [];
249
+ const stop = rootDir === undefined ? undefined : path.resolve(rootDir);
250
+ for (let dir = path.resolve(startDir); ; dir = path.dirname(dir)) {
251
+ dirs.push(dir);
252
+ if (dir === stop || path.dirname(dir) === dir) break;
253
+ }
254
+ const manifests = new Map<string, unknown>();
255
+ for (const dir of dirs) {
256
+ if (dir === dirs[0] && manifest !== undefined) manifests.set(dir, manifest);
257
+ else {
258
+ try { manifests.set(dir, JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))); }
259
+ catch { /* A lock can still identify a project without a readable manifest. */ }
260
+ }
261
+ }
262
+ let declared: {manager: PackageManager, root: string} | undefined;
263
+ for (const dir of dirs) {
264
+ const pkg = manifests.get(dir);
265
+ const manager = declaredPackageManager(pkg);
266
+ if (manager !== undefined && (dir === dirs[0] || isWorkspaceMember(dir, dirs[0], pkg))) {
267
+ declared = {manager, root: dir};
268
+ break;
269
+ }
270
+ }
271
+ if (declared) {
272
+ // A nested declaration defines its own project unless a compatible workspace actually contains it.
273
+ let boundary = dirs.indexOf(declared.root);
274
+ for (let i = boundary + 1; i < dirs.length; i++) {
275
+ const pkg = manifests.get(dirs[i]);
276
+ const manager = declaredPackageManager(pkg);
277
+ if (manager !== undefined && manager !== declared.manager) break;
278
+ if (isWorkspaceMember(dirs[i], declared.root, pkg)) boundary = i;
279
+ }
280
+ const projectDirs = dirs.slice(0, boundary + 1);
281
+ const filename = getLockFileName(declared.manager);
282
+ for (const dir of projectDirs) {
283
+ const lockFile = path.join(dir, filename);
284
+ if (!fs.existsSync(lockFile)) continue;
285
+ if (filename === "yarn.lock") {
286
+ const actual = isYarnBerryLockFile(fs.readFileSync(lockFile, "utf8")) ?
287
+ PackageManager.YarnBerry : PackageManager.YarnClassic;
288
+ if (actual !== declared.manager) {
289
+ throw new PackageManagerSelectionError(
290
+ `packageManager selects ${declared.manager}, but ${lockFile} contains ${actual}`);
212
291
  }
213
292
  }
214
- return config.packageManager;
293
+ return {packageManager: declared.manager, root: dir, lockFile};
294
+ }
295
+ const foreign = projectDirs.flatMap(dir => LOCK_FILE_DETECTION
296
+ .map(config => path.join(dir, config.filename)).filter(file => fs.existsSync(file)));
297
+ if (foreign.length) {
298
+ throw new PackageManagerSelectionError(
299
+ `packageManager selects ${declared.manager}, but ${filename} is missing; other lock files: ${foreign.join(", ")}`);
300
+ }
301
+ return {packageManager: declared.manager, root: declared.root};
302
+ }
303
+ // Without a recognized declaration, retain the existing nearest-lock/filename precedence.
304
+ for (const dir of dirs) {
305
+ for (const config of LOCK_FILE_DETECTION) {
306
+ const lockFile = path.join(dir, config.filename);
307
+ if (!fs.existsSync(lockFile)) continue;
308
+ if (typeof config.packageManager !== "function") {
309
+ return {packageManager: config.packageManager, root: dir, lockFile};
310
+ }
311
+ try {
312
+ return {packageManager: config.packageManager(fs.readFileSync(lockFile, "utf8")), root: dir, lockFile};
313
+ } catch {
314
+ return {packageManager: PackageManager.YarnClassic, root: dir, lockFile};
315
+ }
215
316
  }
216
317
  }
217
318
  return undefined;
218
319
  }
219
320
 
321
+ /** Detect the manager selected by the declaration and locks in this directory. */
322
+ export function detectPackageManager(dir: string): PackageManager | undefined {
323
+ return selectPackageManager(dir, dir)?.packageManager;
324
+ }
325
+
220
326
  /**
221
327
  * Gets the lock file detection configuration.
222
328
  * Returns the array of lock file configs in priority order.
@@ -1958,9 +1958,8 @@ export class JavaScriptPrinter extends JavaScriptVisitor<PrintOutputCapture> {
1958
1958
 
1959
1959
  p.append(before);
1960
1960
  await this.visitRightPaddedLocal(container.elements, suffixBetween, p);
1961
- await this.afterSyntaxMarkers(container.markers, p);
1962
-
1963
1961
  p.append(after === null ? "" : after);
1962
+ await this.afterSyntaxMarkers(container.markers, p);
1964
1963
  }
1965
1964
 
1966
1965
  override async visitMarker<M extends Marker>(marker: M, p: PrintOutputCapture): Promise<M> {
@@ -33,6 +33,12 @@ export interface AddDependencyOptions {
33
33
  scope?: NpmDependencyScope;
34
34
  /** Add only to a `package.json` that declared a package matching one of these globs before the cycle's edits. */
35
35
  onlyIfDeclaring?: string[];
36
+ /**
37
+ * Add only to a `package.json` that resolves every `name@range` entry, e.g. `react@>=16.9.0 <18`: by the version
38
+ * its lock resolves, else when the declared constraint admits nothing outside the range. An undeclared package is
39
+ * taken from the nearest enclosing `package.json` that declares it.
40
+ */
41
+ onlyIfResolving?: string[];
36
42
  }
37
43
 
38
44
  /**
@@ -73,6 +79,21 @@ export function upgradeDependencyVersion(options: UpgradeDependencyVersionOption
73
79
  return prepareJavaRecipe("org.openrewrite.javascript.UpgradeDependencyVersion", options);
74
80
  }
75
81
 
82
+ export interface UpgradeDependencyVersionsOptions {
83
+ /** Nonempty package-name glob map. Overlapping patterns must specify the same target constraint. */
84
+ versions: Record<string, string>;
85
+ /** Verify the upgraded manifest before recovering from stale npm lock peer conflicts. Defaults to false. */
86
+ reconcileNpmPeerDependencies?: boolean;
87
+ }
88
+
89
+ /**
90
+ * Upgrade matching npm dependencies together and regenerate the lock file once.
91
+ * Delegates to `org.openrewrite.javascript.UpgradeDependencyVersions` via RPC.
92
+ */
93
+ export function upgradeDependencyVersions(options: UpgradeDependencyVersionsOptions): Promise<Recipe> {
94
+ return prepareJavaRecipe("org.openrewrite.javascript.UpgradeDependencyVersions", options);
95
+ }
96
+
76
97
  export interface ChangeDependencyOptions {
77
98
  oldPackageName: string;
78
99
  newPackageName: string;