@openrewrite/rewrite 8.103.0 → 8.104.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/java/tree.d.ts +3 -0
  2. package/dist/java/tree.d.ts.map +1 -1
  3. package/dist/java/tree.js +3 -1
  4. package/dist/java/tree.js.map +1 -1
  5. package/dist/javascript/add-import.d.ts +28 -0
  6. package/dist/javascript/add-import.d.ts.map +1 -1
  7. package/dist/javascript/add-import.js +48 -25
  8. package/dist/javascript/add-import.js.map +1 -1
  9. package/dist/javascript/assertions.d.ts.map +1 -1
  10. package/dist/javascript/assertions.js +60 -67
  11. package/dist/javascript/assertions.js.map +1 -1
  12. package/dist/javascript/binding.d.ts +5 -2
  13. package/dist/javascript/binding.d.ts.map +1 -1
  14. package/dist/javascript/binding.js +58 -14
  15. package/dist/javascript/binding.js.map +1 -1
  16. package/dist/javascript/format/prettier-config-loader.d.ts +1 -0
  17. package/dist/javascript/format/prettier-config-loader.d.ts.map +1 -1
  18. package/dist/javascript/format/prettier-config-loader.js +23 -4
  19. package/dist/javascript/format/prettier-config-loader.js.map +1 -1
  20. package/dist/javascript/member-spellings.d.ts +88 -0
  21. package/dist/javascript/member-spellings.d.ts.map +1 -0
  22. package/dist/javascript/member-spellings.js +357 -0
  23. package/dist/javascript/member-spellings.js.map +1 -0
  24. package/dist/javascript/package-manager.d.ts +3 -0
  25. package/dist/javascript/package-manager.d.ts.map +1 -1
  26. package/dist/javascript/package-manager.js +49 -0
  27. package/dist/javascript/package-manager.js.map +1 -1
  28. package/dist/javascript/project-parser.d.ts.map +1 -1
  29. package/dist/javascript/project-parser.js +70 -109
  30. package/dist/javascript/project-parser.js.map +1 -1
  31. package/dist/javascript/scope.d.ts +2 -0
  32. package/dist/javascript/scope.d.ts.map +1 -1
  33. package/dist/javascript/scope.js +2 -1
  34. package/dist/javascript/scope.js.map +1 -1
  35. package/dist/json/index.d.ts +1 -0
  36. package/dist/json/index.d.ts.map +1 -1
  37. package/dist/json/index.js +1 -0
  38. package/dist/json/index.js.map +1 -1
  39. package/dist/json/path-matcher.d.ts +29 -0
  40. package/dist/json/path-matcher.d.ts.map +1 -0
  41. package/dist/json/path-matcher.js +974 -0
  42. package/dist/json/path-matcher.js.map +1 -0
  43. package/dist/rewrite-javascript-version.txt +1 -1
  44. package/dist/rpc/request/parse-project.d.ts.map +1 -1
  45. package/dist/rpc/request/parse-project.js +20 -23
  46. package/dist/rpc/request/parse-project.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/java/tree.ts +2 -0
  49. package/src/javascript/add-import.ts +58 -30
  50. package/src/javascript/assertions.ts +43 -57
  51. package/src/javascript/binding.ts +72 -17
  52. package/src/javascript/format/prettier-config-loader.ts +22 -3
  53. package/src/javascript/member-spellings.ts +374 -0
  54. package/src/javascript/package-manager.ts +51 -0
  55. package/src/javascript/project-parser.ts +17 -50
  56. package/src/javascript/scope.ts +2 -2
  57. package/src/json/index.ts +1 -0
  58. package/src/json/path-matcher.ts +1092 -0
  59. package/src/rpc/request/parse-project.ts +22 -32
@@ -13,19 +13,21 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import {J} from "../java";
16
+ import {isStringLiteral, J} from "../java";
17
17
  import {JS} from "./tree";
18
18
  import {JavaScriptVisitor} from "./visitor";
19
19
  import {
20
- compilationUnitOf, cursorOf, declarationsOf, isReference, namesUsedIn, scopeOf, valuesDeclaredAtTopLevel
20
+ compilationUnitOf, cursorOf, declarationsOf, isReference, namesUsedIn, referencesOf, scopeOf,
21
+ valuesDeclaredAtTopLevel
21
22
  } from "./scope";
22
23
  import {Cursor, isTree} from "../tree";
23
24
  import {
24
25
  AddImportOptions, bindImport, bindingShape, existingImportBinding, ExistingImportBinding, hasEsmSyntax, ImportStyle,
25
- isCommonJs, memberName, moduleNameOf, nameTaken, RebindImport, requireBinds, requireDeclarationOf,
26
- requiredModuleOfDeclaration, requireJoinTarget
26
+ isCommonJs, memberName, moduleNameOf, moduleScopeBindings, nameTaken, RebindImport, requireBinds, requireDeclarationOf,
27
+ requiredModuleOf, requiredModuleOfDeclaration, requireJoinTarget
27
28
  } from "./add-import";
28
29
  import {RemoveImport} from "./remove-import";
30
+ import {RenameMemberSpellings} from "./member-spellings";
29
31
  import {sameModule} from "./package-name";
30
32
  import {
31
33
  AmdCalleeOptions, amdBlockOf, bindAmd, calleesOf, dependencyNames, derivedBindingName, enclosingAmdBlock,
@@ -147,6 +149,9 @@ interface ModuleObjectBinding {
147
149
 
148
150
  /** A type-only import erases, so the name it binds stands for no value at runtime. */
149
151
  typeOnly: boolean;
152
+
153
+ /** Whether a `let` or `var` declares it, which the file may assign another value to. Never an import. */
154
+ reassignable?: boolean;
150
155
  }
151
156
 
152
157
  /**
@@ -169,9 +174,7 @@ function dynamicallyImportedModule(declaration: J.VariableDeclarations): string
169
174
  return undefined;
170
175
  }
171
176
  const argument = call.arguments.elements[0]?.element;
172
- return argument?.kind === J.Kind.Literal && typeof (argument as J.Literal).value === "string"
173
- ? moduleNameOf(argument as J.Literal)
174
- : undefined;
177
+ return isStringLiteral(argument) ? moduleNameOf(argument) : undefined;
175
178
  }
176
179
 
177
180
  function isImportIdentifier(expression: J | undefined): boolean {
@@ -195,14 +198,25 @@ function wholeModuleBindingsVia(
195
198
  const module = moduleOf(declaration);
196
199
  const name = declaration.variables[0]?.element?.name;
197
200
  if (module !== undefined && name?.kind === J.Kind.Identifier) {
198
- bindings.push({name: (name as J.Identifier).simpleName, module, shape, typeOnly: false});
201
+ bindings.push({name: (name as J.Identifier).simpleName, module, shape, typeOnly: false,
202
+ reassignable: !declaresConst(stmt.element)});
199
203
  }
200
204
  }
201
205
  }
202
206
  return bindings;
203
207
  }
204
208
 
205
- /** Only whole-module bindings: a named member does not name the module object. */
209
+ /** Whether `statement` declares `const`, which a list (`const a = 1, NS = require("m")`) spells on the statement. */
210
+ function declaresConst(statement: J | undefined): boolean {
211
+ const modifiers = statement?.kind === J.Kind.VariableDeclarations ? (statement as J.VariableDeclarations).modifiers :
212
+ statement?.kind === JS.Kind.ScopedVariableDeclarations ? (statement as JS.ScopedVariableDeclarations).modifiers : [];
213
+ return modifiers.some(m => m.keyword === "const");
214
+ }
215
+
216
+ /**
217
+ * Only whole-module bindings: a named member does not name the module object.
218
+ * `import X = require("m")` counts as `const X = require("m")`.
219
+ */
206
220
  function moduleObjectBindings(cu: JS.CompilationUnit): ModuleObjectBinding[] {
207
221
  const bindings: ModuleObjectBinding[] = [];
208
222
  for (const stmt of cu.statements) {
@@ -211,16 +225,21 @@ function moduleObjectBindings(cu: JS.CompilationUnit): ModuleObjectBinding[] {
211
225
  continue;
212
226
  }
213
227
  const jsImport = statement as JS.Import;
214
- const specifier = jsImport.moduleSpecifier?.element;
215
- if (specifier?.kind !== J.Kind.Literal) {
228
+ const clause = jsImport.importClause;
229
+ const typeOnly = clause?.typeOnly ?? false;
230
+ const initializer = jsImport.initializer?.element;
231
+ const required = initializer?.kind === J.Kind.MethodInvocation
232
+ ? requiredModuleOf(initializer as J.MethodInvocation)
233
+ : undefined;
234
+ if (required !== undefined && clause?.name?.element?.kind === J.Kind.Identifier) {
235
+ bindings.push({name: (clause.name.element as J.Identifier).simpleName, module: required, shape: "require", typeOnly});
216
236
  continue;
217
237
  }
218
- if (typeof (specifier as J.Literal).value !== "string") {
238
+ const specifier = jsImport.moduleSpecifier?.element;
239
+ if (!isStringLiteral(specifier)) {
219
240
  continue;
220
241
  }
221
- const module = moduleNameOf(specifier as J.Literal);
222
- const clause = jsImport.importClause;
223
- const typeOnly = clause?.typeOnly ?? false;
242
+ const module = moduleNameOf(specifier);
224
243
  if (clause?.name?.element?.kind === J.Kind.Identifier) {
225
244
  bindings.push({name: (clause.name.element as J.Identifier).simpleName, module, shape: "default", typeOnly});
226
245
  }
@@ -337,8 +356,11 @@ function sameCallees(a: readonly string[], b: readonly string[]): boolean {
337
356
  }
338
357
 
339
358
  /**
340
- * Moves the binding for `from` to `to` and answers with the name it now carries, or `undefined`,
341
- * changing nothing, where the move cannot be expressed safely. One call moves one binding.
359
+ * Moves the binding for `from` to `to` and answers with the name it now carries, or `undefined`
360
+ * where nothing binds `from` or the move isn't safe. One call moves one binding.
361
+ * Spellings through the module (`NS.Old`, `import("m").Old`, `export {Old} from "m"`) move too, also
362
+ * when nothing binds `from` and the answer is `undefined`, but not when the binding can't move
363
+ * (`const {Old, ...rest} = require("m")`); see {@link RenameMemberSpellings}.
342
364
  * Named members of one import moved to one module, a call each, end up in one import of it,
343
365
  * whether the calls share a visit or come from separate recipes.
344
366
  * On an ES import, every type in the file naming what moved is renamed the way a parse of the result names it.
@@ -373,6 +395,11 @@ export function maybeRebind(visitor: JavaScriptVisitor<any>, options: MaybeRebin
373
395
  }
374
396
  const existing = existingImportBinding(cu, options.from.module, options.from.member);
375
397
  if (existing === undefined) {
398
+ const bound = moduleScopeBindings(cu).some(b => b.module !== undefined &&
399
+ sameModule(b.module, options.from.module) && b.member === memberName(options.from.member));
400
+ if (!bound) {
401
+ queueRenameMemberSpellings(visitor, cu, options);
402
+ }
376
403
  return undefined;
377
404
  }
378
405
  // A binding leaving a `let` or `var` destructuring would land in a `const` require.
@@ -393,9 +420,37 @@ export function maybeRebind(visitor: JavaScriptVisitor<any>, options: MaybeRebin
393
420
  v.localName === existing.localName)) {
394
421
  visitor.afterVisit.push(new RebindImport(options.from, options.to, existing.localName, boundName));
395
422
  }
423
+ queueRenameMemberSpellings(visitor, cu, options);
396
424
  return boundName;
397
425
  }
398
426
 
427
+ /**
428
+ * Queues one {@link RenameMemberSpellings} per move of a named member, after any `RebindImport` of the move.
429
+ * Skips `import D from "m"`: `D.Old` reads the default export, which is the module only with `export =`.
430
+ * Skips a `let` or `var` `NS` of the module that the file assigns to: after `NS = other`, `NS.Old` may not
431
+ * read the module. Only those are looked for, since finding an assignment reads the whole file.
432
+ */
433
+ function queueRenameMemberSpellings(
434
+ visitor: JavaScriptVisitor<any>,
435
+ cu: JS.CompilationUnit,
436
+ options: MaybeRebindOptions
437
+ ): void {
438
+ const from = memberName(options.from.member);
439
+ const to = memberName(options.to.member);
440
+ if (from === undefined || to === undefined || bindingShape(from) !== "named" || bindingShape(to) !== "named" ||
441
+ (visitor.afterVisit || []).some(v => v instanceof RenameMemberSpellings && v.from.member === from &&
442
+ sameModule(v.from.module, options.from.module) && v.to.member === to && sameModule(v.to.module, options.to.module))) {
443
+ return;
444
+ }
445
+ const root = new Cursor(cu);
446
+ const moduleObjects = new Set(moduleObjectBindings(cu)
447
+ .filter(b => b.shape !== "default" && sameModule(b.module, options.from.module) &&
448
+ !(b.reassignable && referencesOf(root, b.name).some(r => r.writes)))
449
+ .map(b => b.name));
450
+ visitor.afterVisit.push(new RenameMemberSpellings(
451
+ {module: options.from.module, member: from}, {module: options.to.module, member: to}, moduleObjects));
452
+ }
453
+
399
454
  /**
400
455
  * The name the moved binding takes, or undefined where a pinned alias cannot be bound verbatim,
401
456
  * since deconflicting it would leave the references the caller emits unbound, or would split the
@@ -275,6 +275,23 @@ export class PrettierConfigLoader {
275
275
  return undefined;
276
276
  }
277
277
 
278
+ private hasDirectPrettierDependency(filePath: string): boolean {
279
+ let dir = path.dirname(filePath);
280
+ while (true) {
281
+ const packageJsonPath = path.join(dir, 'package.json');
282
+ if (fs.existsSync(packageJsonPath)) {
283
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
284
+ return !!(pkg.dependencies?.prettier || pkg.devDependencies?.prettier ||
285
+ pkg.optionalDependencies?.prettier);
286
+ }
287
+ const parent = path.dirname(dir);
288
+ if (parent === dir) {
289
+ return false;
290
+ }
291
+ dir = parent;
292
+ }
293
+ }
294
+
278
295
  /**
279
296
  * Finds the .prettierignore file by scanning upward from projectRoot.
280
297
  * Returns undefined if no .prettierignore file is found.
@@ -324,9 +341,11 @@ export class PrettierConfigLoader {
324
341
  ignored = fileInfo.ignored;
325
342
  }
326
343
 
327
- // Resolve config for this specific file (applies overrides)
328
- // If no config file exists, use empty config (Prettier defaults)
329
- const config = await this.detection.bundledPrettier.resolveConfig(absolutePath) ?? {};
344
+ const resolvedConfig = await this.detection.bundledPrettier.resolveConfig(absolutePath);
345
+ if (resolvedConfig === null && !this.hasDirectPrettierDependency(absolutePath)) {
346
+ return undefined;
347
+ }
348
+ const config = resolvedConfig ?? {};
330
349
 
331
350
  // Create a cache key from the resolved config + version + ignored status
332
351
  const configKey = JSON.stringify({ config, version: this.detection.version, ignored });
@@ -0,0 +1,374 @@
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 {create as produce, Draft} from "mutative";
17
+ import {ElementRemovalFormatter, emptySpace, Expression, isIdentifier, isStringLiteral, J, singleSpace, Statement} from "../java";
18
+ import {randomId, UUID} from "../uuid";
19
+ import {Cursor} from "../tree";
20
+ import {isObjectBindingPattern, JS, moduleExportName} from "./tree";
21
+ import {JavaScriptVisitor} from "./visitor";
22
+ import {resolve, rootName} from "./scope";
23
+ import {aliasing, moduleNameOf, movedBinding, newIdentifier, respecify, withMovedTypes, withoutStatement} from "./add-import";
24
+ import {sameModule, spelledLike} from "./package-name";
25
+
26
+ /**
27
+ * Renames a moved member where the file reads it through its module rather than an import of it.
28
+ * `NS` is a module object: `import * as NS from "m"`, `import NS = require("m")`, `const NS = require("m")`
29
+ * or `const NS = await import("m")`.
30
+ *
31
+ * // m.Old → m.New
32
+ * NS.Old() → NS.New()
33
+ * NS["Old"] → NS["New"]
34
+ * const {Old} = NS → const {New: Old} = NS
35
+ * import("m").Old → import("m").New
36
+ * export {Old} from "m" → export {New as Old} from "m"
37
+ *
38
+ * // m.Old → m2.New: NS still reads "m", so NS.Old stays
39
+ * import("m").Old → import("m2").New
40
+ * export {Old, X} from "m" → export {X} from "m"; export {New as Old} from "m2"
41
+ */
42
+ export class RenameMemberSpellings<P> extends JavaScriptVisitor<P> {
43
+ constructor(
44
+ readonly from: {module: string; member: string},
45
+ readonly to: {module: string; member: string},
46
+ /** The module objects of `from`'s module, like `NS` in `import * as NS from "m"`. */
47
+ readonly moduleObjects: ReadonlySet<string>
48
+ ) {
49
+ super();
50
+ }
51
+
52
+ /**
53
+ * Moves re-exports to another module on the whole file, since `export {Old, X} from "m"` can split in two.
54
+ * Renames the types only in a file this changed. Where a `RebindImport` of the same move ran first, it already
55
+ * renamed them, so nothing is left to rename.
56
+ */
57
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: P): Promise<J | undefined> {
58
+ const visited = await super.visitJsCompilationUnit(cu, p) as JS.CompilationUnit;
59
+ const moved = this.withinModule ? visited : this.withReExportsMoved(visited);
60
+ return moved === cu ? moved : withMovedTypes(moved, this.from, this.to);
61
+ }
62
+
63
+ private get withinModule(): boolean {
64
+ return sameModule(this.from.module, this.to.module);
65
+ }
66
+
67
+ /**
68
+ * Whether `qualifier.member` reads the moved member through a module object: `NS.Old`, `(NS).Old`.
69
+ * For `(NS)` the cursor steps inside, since `resolve` wants the cursor of the node holding `NS`.
70
+ */
71
+ private readsMovedMember(qualifier: J | undefined, member: string): boolean {
72
+ let object = qualifier, cursor = this.cursor;
73
+ while (object?.kind === J.Kind.Parentheses) {
74
+ cursor = new Cursor(object, cursor);
75
+ object = (object as J.Parentheses<J>).tree.element;
76
+ }
77
+ return this.withinModule && member === this.from.member &&
78
+ object !== undefined && isIdentifier(object) && this.moduleObjects.has(object.simpleName) &&
79
+ resolve(cursor, object)?.kind === JS.Kind.CompilationUnit;
80
+ }
81
+
82
+ /** `NS.Old` → `NS.New` */
83
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, p: P): Promise<J | undefined> {
84
+ const visited = await super.visitFieldAccess(fieldAccess, p);
85
+ if (visited?.kind !== J.Kind.FieldAccess || !this.readsMovedMember(fieldAccess.target, fieldAccess.name.element.simpleName)) {
86
+ return visited;
87
+ }
88
+ return produce(visited as J.FieldAccess, draft => {
89
+ draft.name.element.simpleName = this.to.member;
90
+ });
91
+ }
92
+
93
+ /** `NS.Old()` → `NS.New()` */
94
+ override async visitMethodInvocation(method: J.MethodInvocation, p: P): Promise<J | undefined> {
95
+ const visited = await super.visitMethodInvocation(method, p);
96
+ if (visited?.kind !== J.Kind.MethodInvocation || !this.readsMovedMember(method.select?.element, method.name.simpleName)) {
97
+ return visited;
98
+ }
99
+ return produce(visited as J.MethodInvocation, draft => {
100
+ draft.name.simpleName = this.to.member;
101
+ if (draft.methodType) {
102
+ draft.methodType = {...draft.methodType, name: this.to.member};
103
+ }
104
+ });
105
+ }
106
+
107
+ /** `NS["Old"]` → `NS["New"]` */
108
+ override async visitArrayAccess(arrayAccess: J.ArrayAccess, p: P): Promise<J | undefined> {
109
+ const visited = await super.visitArrayAccess(arrayAccess, p);
110
+ const index = arrayAccess.dimension.index.element;
111
+ if (visited?.kind !== J.Kind.ArrayAccess || !isStringLiteral(index) || !this.readsMovedMember(arrayAccess.indexed, index.value)) {
112
+ return visited;
113
+ }
114
+ return produce(visited as J.ArrayAccess, draft => {
115
+ respecify(draft.dimension.index.element as Draft<J.Literal>, this.to.member);
116
+ });
117
+ }
118
+
119
+ /** `const {Old} = NS` → `const {New: Old} = NS`, so the local name stays `Old`. */
120
+ override async visitVariable(variable: J.VariableDeclarations.NamedVariable, p: P): Promise<J | undefined> {
121
+ const visited = await super.visitVariable(variable, p);
122
+ if (visited?.kind !== J.Kind.NamedVariable) {
123
+ return visited;
124
+ }
125
+ const named = visited as J.VariableDeclarations.NamedVariable;
126
+ const pattern = named.name;
127
+ if (!isObjectBindingPattern(pattern) || !this.readsMovedMember(variable.initializer?.element, this.from.member)) {
128
+ return visited;
129
+ }
130
+ const elements = pattern.bindings.elements.map((e, i) => {
131
+ const element = e.element as JS.BindingElement;
132
+ const read = element.kind === JS.Kind.BindingElement ? element.propertyName?.element ?? element.name : undefined;
133
+ return read !== undefined && isIdentifier(read) && read.simpleName === this.from.member && isIdentifier(element.name)
134
+ ? {...e, element: movedBinding(pattern, i, this.to.member, element.name.simpleName)} : e;
135
+ });
136
+ if (elements.every((e, i) => e === pattern.bindings.elements[i])) {
137
+ return visited;
138
+ }
139
+ const destructured: JS.ObjectBindingPattern = {...pattern, bindings: {...pattern.bindings, elements}};
140
+ const moved: J.VariableDeclarations.NamedVariable = {...named, name: destructured};
141
+ return moved;
142
+ }
143
+
144
+ /** `import("m").Old` → `import("m2").New` */
145
+ override async visitImportType(importType: JS.ImportType, p: P): Promise<J | undefined> {
146
+ const visited = await super.visitImportType(importType, p);
147
+ if (visited?.kind !== JS.Kind.ImportType) {
148
+ return visited;
149
+ }
150
+ const argument = importType.argumentAndAttributes.elements[0]?.element;
151
+ const literal = argument?.kind === JS.Kind.LiteralType ? (argument as JS.LiteralType).literal : undefined;
152
+ const qualifier = rootName(importType.qualifier?.element);
153
+ if (!isStringLiteral(literal) || !sameModule(moduleNameOf(literal), this.from.module) ||
154
+ qualifier === undefined || !isIdentifier(qualifier) || qualifier.simpleName !== this.from.member) {
155
+ return visited;
156
+ }
157
+ return produce(visited as JS.ImportType, draft => {
158
+ (rootName(draft.qualifier!.element) as Draft<J.Identifier>).simpleName = this.to.member;
159
+ if (!this.withinModule) {
160
+ const spelled = (draft.argumentAndAttributes.elements[0].element as Draft<JS.LiteralType>).literal as Draft<J.Literal>;
161
+ respecify(spelled, spelledLike(this.to.module, String(spelled.value)));
162
+ }
163
+ });
164
+ }
165
+
166
+ /** Within one module: `export {Old} from "m"` → `export {New as Old} from "m"`. */
167
+ override async visitExportDeclaration(exportDeclaration: JS.ExportDeclaration, p: P): Promise<J | undefined> {
168
+ const visited = await super.visitExportDeclaration(exportDeclaration, p);
169
+ const declaration = reExportFrom(visited, this.from.module);
170
+ if (!this.withinModule || declaration === undefined) {
171
+ return visited;
172
+ }
173
+ const elements = clauseOf(declaration).elements.elements;
174
+ return elements.some(e => this.reExportsMember(e.element))
175
+ ? withElements(declaration, elements.map(e => this.reExportsMember(e.element) ? this.renamed(e) : e))
176
+ : visited;
177
+ }
178
+
179
+ /**
180
+ * Moves the member's re-exports to `to`'s module:
181
+ *
182
+ * export {Old} from "m" → export {New as Old} from "m2"
183
+ * export {Old, X} from "m" → export {X} from "m"; export {New as Old} from "m2"
184
+ * export {Old} from "m"; → export {Y, New as Old} from "m2"
185
+ * export {Y} from "m2" (joins a re-export of the same kind, `export type` or not)
186
+ *
187
+ * A comment ending the line (`export {X} from "m"; // note`) stays on it, before the new statement.
188
+ */
189
+ private withReExportsMoved(cu: JS.CompilationUnit): JS.CompilationUnit {
190
+ const statements = [...cu.statements];
191
+ const emptied: UUID[] = [];
192
+ let eof = cu.eof;
193
+ let changed = false;
194
+ for (let i = 0; i < statements.length; i++) {
195
+ const declaration = reExportFrom(statements[i].element, this.from.module);
196
+ const elements = declaration && clauseOf(declaration).elements.elements;
197
+ const moving = new Set(elements?.filter(e => this.reExportsMember(e.element)));
198
+ if (declaration === undefined || elements === undefined || moving.size === 0) {
199
+ continue;
200
+ }
201
+ changed = true;
202
+ const staying = new Set(elements.filter(e => !moving.has(e)));
203
+ const target = statements.findIndex((s, j) =>
204
+ j !== i && reExportFrom(s.element, this.to.module)?.typeOnly.element === declaration.typeOnly.element);
205
+ if (target < 0 && staying.size === 0) {
206
+ statements[i] = {...statements[i], element: this.respecified(withElements(declaration, elements.map(e => this.renamed(e))))};
207
+ continue;
208
+ }
209
+ const moved = without(elements, staying).map(e => this.renamed(e));
210
+ if (target >= 0) {
211
+ const into = statements[target].element as JS.ExportDeclaration;
212
+ statements[target] = {...statements[target], element: withElements(into, appended(clauseOf(into).elements.elements, moved))};
213
+ } else {
214
+ const next = statements[i + 1];
215
+ const split = splitAtLineEnd(next?.element.prefix ?? eof, next === undefined);
216
+ if (split !== undefined && next !== undefined) {
217
+ statements[i + 1] = {...next, element: {...next.element, prefix: split.rest}};
218
+ } else if (split !== undefined) {
219
+ eof = split.rest;
220
+ }
221
+ statements.splice(i + 1, 0, this.ownStatement(statements[i], declaration, moved, split?.line));
222
+ }
223
+ if (staying.size > 0) {
224
+ statements[i] = {...statements[i], element: withElements(declaration, without(elements, moving))};
225
+ } else {
226
+ emptied.push(declaration.id);
227
+ }
228
+ }
229
+ return changed ? emptied.reduce((left, id) => withoutStatement(left, id), {...cu, statements, eof}) : cu;
230
+ }
231
+
232
+ /** A new `export {…} from "m2"` for `moved` on the next line, after `line`: the comments ending this one. */
233
+ private ownStatement(stmt: J.RightPadded<Statement>, declaration: JS.ExportDeclaration,
234
+ moved: J.RightPadded<Expression>[], line: J.Space | undefined): J.RightPadded<Statement> {
235
+ const indent = declaration.prefix.whitespace.slice(declaration.prefix.whitespace.lastIndexOf("\n") + 1);
236
+ const clause = clauseOf(declaration);
237
+ const own = this.respecified({
238
+ ...declaration,
239
+ id: randomId(),
240
+ prefix: line === undefined ? {...declaration.prefix, comments: [], whitespace: "\n" + indent} :
241
+ {...line, comments: line.comments.map((c, k) => k < line.comments.length - 1 ? c : {...c, suffix: "\n" + indent})},
242
+ exportClause: {...clause, id: randomId(), elements: {...clause.elements, elements: moved}} as JS.NamedExports
243
+ });
244
+ return {...stmt, element: own, markers: {...stmt.markers, id: randomId()}};
245
+ }
246
+
247
+ /** `export … from "m"` → `export … from "m2"`, keeping a `node:` scheme the file uses. */
248
+ private respecified(declaration: JS.ExportDeclaration): JS.ExportDeclaration {
249
+ return produce(declaration, draft => {
250
+ const literal = draft.moduleSpecifier!.element as Draft<J.Literal>;
251
+ literal.id = randomId();
252
+ respecify(literal, spelledLike(this.to.module, String(literal.value)));
253
+ });
254
+ }
255
+
256
+ /**
257
+ * The specifier reading the new member, still exporting the same name: `Old` → `New as Old`,
258
+ * and `Old as X` or `"Old" as X` → `New as X`. Unchanged where only the module moves.
259
+ * `New` is typed as the specifier is, which the type rename then follows.
260
+ */
261
+ private renamed(element: J.RightPadded<Expression>): J.RightPadded<Expression> {
262
+ if (this.to.member === this.from.member || element.element.kind !== JS.Kind.ExportSpecifier) {
263
+ return element;
264
+ }
265
+ const specifier = element.element as JS.ExportSpecifier;
266
+ const read = specifier.specifier;
267
+ const member: J.Identifier = {...newIdentifier(this.to.member), type: specifier.type};
268
+ let renamed: JS.Alias;
269
+ if (read.kind === JS.Kind.Alias) {
270
+ const alias = read as JS.Alias;
271
+ renamed = {...alias, propertyName: {...alias.propertyName, element: {...member, prefix: alias.propertyName.element.prefix}}};
272
+ } else if (read.kind === J.Kind.Identifier || read.kind === J.Kind.Literal) {
273
+ const alias = aliasing(read as J.Identifier | J.Literal, this.to.member);
274
+ renamed = {...alias, propertyName: {...alias.propertyName, element: member}};
275
+ } else {
276
+ return element;
277
+ }
278
+ const reading: JS.ExportSpecifier = {...specifier, specifier: renamed};
279
+ return {...element, element: reading};
280
+ }
281
+
282
+ /** Whether the entry is `Old`, `Old as X` or `"Old" as X`. */
283
+ private reExportsMember(element: J): boolean {
284
+ if (element.kind !== JS.Kind.ExportSpecifier) {
285
+ return false;
286
+ }
287
+ const specifier = (element as JS.ExportSpecifier).specifier;
288
+ const read = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).propertyName.element : specifier;
289
+ return (read.kind === J.Kind.Identifier || read.kind === J.Kind.Literal) &&
290
+ moduleExportName(read as J.Identifier | J.Literal) === this.from.member;
291
+ }
292
+ }
293
+
294
+ /** `statement` as an `export {…} from "<module>"` declaration, where it is one. */
295
+ function reExportFrom(statement: J | undefined, module: string): JS.ExportDeclaration | undefined {
296
+ if (statement?.kind !== JS.Kind.ExportDeclaration) {
297
+ return undefined;
298
+ }
299
+ const declaration = statement as JS.ExportDeclaration;
300
+ const source = declaration.moduleSpecifier?.element;
301
+ return isStringLiteral(source) && sameModule(moduleNameOf(source), module) && declaration.exportClause?.kind === JS.Kind.NamedExports
302
+ ? declaration : undefined;
303
+ }
304
+
305
+ /**
306
+ * The space after a statement, split where its line ends:
307
+ * ` // note\n// next` → `line` ` // note`, `rest` `\n// next`. At the end of the file all of it is `line`.
308
+ * `undefined` where no comment follows on the same line.
309
+ */
310
+ function splitAtLineEnd(space: J.Space, endsFile: boolean): {line: J.Space, rest: J.Space} | undefined {
311
+ if (space.whitespace.includes("\n") || space.comments.length === 0) {
312
+ return undefined;
313
+ }
314
+ const end = space.comments.findIndex(c => c.suffix.includes("\n"));
315
+ if (end < 0) {
316
+ return endsFile ? {line: space, rest: {...space, whitespace: "", comments: []}} : undefined;
317
+ }
318
+ return {
319
+ line: {...space, comments: space.comments.slice(0, end + 1)},
320
+ rest: {...space, whitespace: space.comments[end].suffix, comments: space.comments.slice(end + 1)}
321
+ };
322
+ }
323
+
324
+ function clauseOf(declaration: JS.ExportDeclaration): JS.NamedExports {
325
+ return declaration.exportClause as JS.NamedExports;
326
+ }
327
+
328
+ function withElements(declaration: JS.ExportDeclaration, elements: J.RightPadded<Expression>[]): JS.ExportDeclaration {
329
+ const clause = clauseOf(declaration);
330
+ return {...declaration, exportClause: {...clause, elements: {...clause.elements, elements}} as JS.NamedExports};
331
+ }
332
+
333
+ /** `elements` without `dropped`, each keeping its comments: `{ a, b }` without `a` is `{ b }`. */
334
+ function without<T extends J>(elements: J.RightPadded<T>[], dropped: ReadonlySet<J.RightPadded<T>>): J.RightPadded<T>[] {
335
+ const formatter = new ElementRemovalFormatter<T>();
336
+ const kept: J.RightPadded<T>[] = [];
337
+ for (const e of elements) {
338
+ if (dropped.has(e)) {
339
+ formatter.markRemoved(e.element);
340
+ } else {
341
+ kept.push({...e, element: formatter.processKept(e.element)});
342
+ }
343
+ }
344
+ const last = elements[elements.length - 1];
345
+ kept[kept.length - 1] = {...kept[kept.length - 1], after: last.after, markers: last.markers};
346
+ return kept;
347
+ }
348
+
349
+ /**
350
+ * `elements` with `added` at the end, separated the same way and each keeping its comments:
351
+ * `{a, b,}` + `c` → `{a, b, c,}`, and `{}` + `c` → `{c}`.
352
+ */
353
+ function appended<T extends J>(elements: J.RightPadded<T>[], added: J.RightPadded<T>[]): J.RightPadded<T>[] {
354
+ const last = elements[elements.length - 1];
355
+ const plain = (markers: J.RightPadded<T>["markers"]) =>
356
+ ({...markers, markers: markers.markers.filter(m => m.kind !== J.Markers.TrailingComma)});
357
+ if (elements.length === 1 && last.element.kind === J.Kind.Empty) {
358
+ return added.map((e, i) => ({
359
+ ...e,
360
+ element: {...e.element, prefix: {...e.element.prefix, whitespace: i === 0 ? last.element.prefix.whitespace : " "}},
361
+ ...(i === added.length - 1 ? {after: last.after, markers: last.markers} : {after: emptySpace, markers: plain(e.markers)})
362
+ }));
363
+ }
364
+ const separator = (elements[1]?.element.prefix ??
365
+ (elements[0].element.prefix.whitespace.includes("\n") ? elements[0].element.prefix : singleSpace)).whitespace;
366
+ const separated = (e: J.RightPadded<T>) => ({...e.element, prefix: {...e.element.prefix, whitespace: separator}});
367
+ return [
368
+ ...elements.slice(0, -1),
369
+ {...last, after: emptySpace, markers: plain(last.markers)},
370
+ ...added.map((e, i) => i === added.length - 1
371
+ ? {...e, element: separated(e), after: last.after, markers: last.markers}
372
+ : {...e, element: separated(e), after: emptySpace, markers: plain(e.markers)})
373
+ ];
374
+ }
@@ -437,6 +437,9 @@ const RELEASE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A
437
437
  * It runs as the parser's other package manager commands do, with `COREPACK_ENABLE_DOWNLOAD_PROMPT=0`, no input and
438
438
  * a short timeout, so it never prompts and never throws.
439
439
  *
440
+ * npm is asked once per process where `npm` on PATH is npm's own `npm-cli.js` ({@link npmEntryPoint}). That prints
441
+ * the version of the package it belongs to, whatever the project configures, so its answer is the same in every root.
442
+ *
440
443
  * @param pm The package manager to ask
441
444
  * @param cwd The project's root directory
442
445
  * @param timeout Timeout in milliseconds
@@ -444,6 +447,54 @@ const RELEASE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A
444
447
  * that is no version
445
448
  */
446
449
  export function runVersion(pm: PackageManager, cwd: string, timeout: number = 10000): string | undefined {
450
+ const entryPoint = pm === PackageManager.Npm ? npmEntryPoint(cwd) : undefined;
451
+ const known = entryPoint === undefined ? undefined : npmVersions.get(entryPoint);
452
+ if (known !== undefined) {
453
+ return known;
454
+ }
455
+ const answer = spawnVersion(pm, cwd, timeout);
456
+ // a failure, such as a timeout on a busy machine, is asked again
457
+ if (entryPoint !== undefined && answer !== undefined) {
458
+ npmVersions.set(entryPoint, answer);
459
+ }
460
+ return answer;
461
+ }
462
+
463
+ const npmVersions = new Map<string, string>();
464
+
465
+ const NPM_CLI = path.sep + path.join('npm', 'bin', 'npm-cli.js');
466
+
467
+ /**
468
+ * The `npm-cli.js` that `npm` on PATH runs in `cwd`, with its change time, so that an npm upgraded in place is asked
469
+ * again. Installers may keep the archive's modification time, but writing the file moves its change time. A relative
470
+ * directory on PATH is resolved against `cwd`, as the spawn resolves it. Undefined where `npm` is something else, such
471
+ * as a shim that picks a release per project or a Windows `.cmd` script.
472
+ */
473
+ function npmEntryPoint(cwd: string): string | undefined {
474
+ if (os.platform() === 'win32' || process.env.PATH === undefined) {
475
+ return undefined;
476
+ }
477
+ for (const dir of process.env.PATH.split(path.delimiter)) {
478
+ const candidate = path.resolve(cwd, dir, 'npm');
479
+ try {
480
+ if (!fs.statSync(candidate).isFile()) {
481
+ continue;
482
+ }
483
+ fs.accessSync(candidate, fs.constants.X_OK);
484
+ } catch {
485
+ continue;
486
+ }
487
+ try {
488
+ const real = fs.realpathSync(candidate);
489
+ return real.endsWith(NPM_CLI) ? `${real}\0${fs.statSync(real).ctimeMs}` : undefined;
490
+ } catch {
491
+ return undefined;
492
+ }
493
+ }
494
+ return undefined;
495
+ }
496
+
497
+ function spawnVersion(pm: PackageManager, cwd: string, timeout: number): string | undefined {
447
498
  const [cmd, ...args] = PACKAGE_MANAGER_CONFIGS[pm].versionCommand;
448
499
  try {
449
500
  const result = spawnSync(getPlatformCommand(cmd), args, {