@openrewrite/recipes-nodejs 0.65.0 → 0.67.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 (79) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +12 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.d.ts +16 -0
  6. package/dist/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.d.ts.map +1 -0
  7. package/dist/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.js +89 -0
  8. package/dist/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.js.map +1 -0
  9. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-node-support.d.ts +33 -0
  10. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-node-support.d.ts.map +1 -0
  11. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-node-support.js +190 -0
  12. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-node-support.js.map +1 -0
  13. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-plan.d.ts +70 -0
  14. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-plan.d.ts.map +1 -0
  15. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-plan.js +315 -0
  16. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-plan.js.map +1 -0
  17. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-support.d.ts +181 -0
  18. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-support.d.ts.map +1 -0
  19. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-support.js +1504 -0
  20. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-support.js.map +1 -0
  21. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-tables.d.ts +3 -0
  22. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-tables.d.ts.map +1 -0
  23. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-tables.js +421 -0
  24. package/dist/migrate/aws-sdk-v3/aws-sdk-v3-tables.js.map +1 -0
  25. package/dist/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.d.ts +20 -0
  26. package/dist/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.d.ts.map +1 -0
  27. package/dist/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.js +146 -0
  28. package/dist/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.js.map +1 -0
  29. package/dist/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.d.ts +13 -0
  30. package/dist/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.d.ts.map +1 -0
  31. package/dist/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.js +69 -0
  32. package/dist/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.js.map +1 -0
  33. package/dist/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.d.ts +35 -0
  34. package/dist/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.d.ts.map +1 -0
  35. package/dist/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.js +132 -0
  36. package/dist/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.js.map +1 -0
  37. package/dist/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.d.ts +18 -0
  38. package/dist/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.d.ts.map +1 -0
  39. package/dist/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.js +562 -0
  40. package/dist/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.js.map +1 -0
  41. package/dist/migrate/builtin-binding-visitor.d.ts +1 -6
  42. package/dist/migrate/builtin-binding-visitor.d.ts.map +1 -1
  43. package/dist/migrate/builtin-binding-visitor.js +6 -69
  44. package/dist/migrate/builtin-binding-visitor.js.map +1 -1
  45. package/dist/migrate/express-request-id/replace-express-request-id.d.ts.map +1 -1
  46. package/dist/migrate/express-request-id/replace-express-request-id.js +1 -2
  47. package/dist/migrate/express-request-id/replace-express-request-id.js.map +1 -1
  48. package/dist/migrate/fs-extra/fs-extra-support.d.ts +0 -1
  49. package/dist/migrate/fs-extra/fs-extra-support.d.ts.map +1 -1
  50. package/dist/migrate/fs-extra/fs-extra-support.js +1 -2
  51. package/dist/migrate/fs-extra/fs-extra-support.js.map +1 -1
  52. package/dist/migrate/increase-node-engine-version.d.ts +1 -0
  53. package/dist/migrate/increase-node-engine-version.d.ts.map +1 -1
  54. package/dist/migrate/increase-node-engine-version.js +12 -7
  55. package/dist/migrate/increase-node-engine-version.js.map +1 -1
  56. package/dist/migrate/source-map-support/replace-source-map-support-api.js +1 -1
  57. package/dist/migrate/source-map-support/replace-source-map-support-api.js.map +1 -1
  58. package/dist/migrate/source-map-support/source-map-support-support.d.ts +0 -1
  59. package/dist/migrate/source-map-support/source-map-support-support.d.ts.map +1 -1
  60. package/dist/migrate/source-map-support/source-map-support-support.js +0 -1
  61. package/dist/migrate/source-map-support/source-map-support-support.js.map +1 -1
  62. package/dist/resources/advisories-npm.csv +97 -3
  63. package/package.json +2 -2
  64. package/src/index.ts +11 -0
  65. package/src/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.ts +71 -0
  66. package/src/migrate/aws-sdk-v3/aws-sdk-v3-node-support.ts +172 -0
  67. package/src/migrate/aws-sdk-v3/aws-sdk-v3-plan.ts +399 -0
  68. package/src/migrate/aws-sdk-v3/aws-sdk-v3-support.ts +1480 -0
  69. package/src/migrate/aws-sdk-v3/aws-sdk-v3-tables.ts +432 -0
  70. package/src/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.ts +126 -0
  71. package/src/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.ts +56 -0
  72. package/src/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.ts +119 -0
  73. package/src/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.ts +523 -0
  74. package/src/migrate/builtin-binding-visitor.ts +9 -94
  75. package/src/migrate/express-request-id/replace-express-request-id.ts +1 -2
  76. package/src/migrate/fs-extra/fs-extra-support.ts +1 -2
  77. package/src/migrate/increase-node-engine-version.ts +11 -7
  78. package/src/migrate/source-map-support/replace-source-map-support-api.ts +1 -1
  79. package/src/migrate/source-map-support/source-map-support-support.ts +0 -1
@@ -0,0 +1,523 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {ExecutionContext, Option, randomId, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
9
+ import {
10
+ declarationsOf,
11
+ JavaScriptParser,
12
+ JavaScriptVisitor,
13
+ JS,
14
+ maybeBind,
15
+ maybeRebind,
16
+ maybeUnbind,
17
+ raw,
18
+ template,
19
+ withStringValue
20
+ } from "@openrewrite/rewrite/javascript";
21
+ import {AwsSdkPlan, AwsSdkScan, awsSdkScanner, newAwsSdkScan} from "./aws-sdk-v3-plan";
22
+ import {
23
+ Action,
24
+ Analysis,
25
+ analyzeAwsSdk,
26
+ args,
27
+ configEdit,
28
+ CREDENTIAL_KEYS,
29
+ isAwsSdkModule,
30
+ LIB_DYNAMODB,
31
+ LIB_STORAGE,
32
+ objectLiteral,
33
+ objectMembers,
34
+ propertyName,
35
+ requireOf,
36
+ presignedPostKey,
37
+ S3_PRESIGNED_POST,
38
+ S3_PRESIGNER,
39
+ v3Client
40
+ } from "./aws-sdk-v3-support";
41
+
42
+ /** Generated code is written as it lands, so the code it wraps keeps its own layout. */
43
+ const UNFORMATTED = {format: false};
44
+ const MARSHALL_KEYS = new Set(['convertEmptyValues']);
45
+ const UNMARSHALL_KEYS = new Set(['wrapNumbers']);
46
+
47
+ /** A tagged template built from pieces, for a replacement whose shape depends on the call. */
48
+ function templateOf(parts: string[], values: any[]) {
49
+ const strings = Object.assign([...parts], {raw: [...parts]}) as unknown as TemplateStringsArray;
50
+ return template(strings, ...values);
51
+ }
52
+
53
+ /** The literal without the members `drop` selects, keeping the space before its closing brace. */
54
+ function withoutMembers(literal: J.NewClass, drop: (member: J) => boolean): J.NewClass {
55
+ const original = literal.body!.statements;
56
+ const kept = original.filter(s => !drop(s.element));
57
+ if (kept.length === original.length) return literal;
58
+ if (kept.length > 0 && kept[kept.length - 1] !== original[original.length - 1]) {
59
+ kept[kept.length - 1] = {...kept[kept.length - 1], after: original[original.length - 1].after, markers: original[original.length - 1].markers};
60
+ }
61
+ return {...literal, body: {...literal.body!, statements: kept}} as J.NewClass;
62
+ }
63
+
64
+ /** The top-level import or declaration that binds `local`. */
65
+ function declaringStatement(cu: JS.CompilationUnit, local: string): J | undefined {
66
+ return cu.statements.map(s => s.element).find(s =>
67
+ (s.kind === JS.Kind.Import && [(s as JS.Import).importClause?.name?.element, ((s as JS.Import).importClause?.namedBindings as JS.Alias | undefined)?.alias]
68
+ .some(name => name && isIdentifier(name) && name.simpleName === local)) ||
69
+ declarationsOf(s).some(d => d.variables.some(v => isIdentifier(v.element.name) && v.element.name.simpleName === local)));
70
+ }
71
+
72
+ /**
73
+ * The v3 form of a v2 statement core's rebinding can't move, which reads an import's module specifier and one
74
+ * declarator's `require('m')`: `import X = require('m')`, `import * as X`, `require('m').X`, and several declarators. `''` drops
75
+ * the statement, `undefined` leaves it to core, and `false` means it can't be moved at all.
76
+ */
77
+ function byHand(statement: J, plan: Analysis): string | undefined | false {
78
+ const moved = (local: string) => {
79
+ const binding = plan.bindings.byLocal.get(local);
80
+ if (binding?.kind !== 'client' || !plan.rebound.has(local)) return undefined;
81
+ const v3 = v3Client(binding.client)!;
82
+ return {v3, renamed: v3.name !== local};
83
+ };
84
+ if (statement.kind === JS.Kind.Import) {
85
+ const imp = statement as JS.Import;
86
+ const namespace = imp.importClause?.namedBindings;
87
+ const star = namespace?.kind === JS.Kind.Alias && isIdentifier((namespace as JS.Alias).alias) && !imp.importClause?.name
88
+ ? ((namespace as JS.Alias).alias as J.Identifier).simpleName : undefined;
89
+ const local = star ?? imp.importClause?.name?.element?.simpleName;
90
+ const move = (imp.initializer || star) && local ? moved(local) : undefined;
91
+ return move ? `import {${move.renamed ? `${move.v3.name} as ${local}` : local}} from "${move.v3.pkg}";` : undefined;
92
+ }
93
+ const declarations = declarationsOf(statement);
94
+ const variables = declarations.flatMap(d => d.variables.map(v => v.element));
95
+ if (variables.length === 0) return undefined;
96
+ if (variables.length === 1 && requireOf(variables[0].initializer?.element)?.member === undefined) return undefined;
97
+ const parts: string[] = [];
98
+ for (const variable of variables) {
99
+ if (!isIdentifier(variable.name) || !isAwsSdkModule(requireOf(variable.initializer?.element)?.module)) return false;
100
+ const local = variable.name.simpleName;
101
+ const move = moved(local);
102
+ if (move) parts.push(`{${move.renamed ? `${move.v3.name}: ${local}` : local}} = require("${move.v3.pkg}")`);
103
+ else if (plan.rebound.has(local)) return false;
104
+ }
105
+ const modifiers = [...((statement as J.VariableDeclarations).modifiers ?? []), ...declarations.flatMap(d => d.modifiers)];
106
+ const keyword = modifiers.map(m => m.keyword).find(k => k === 'let' || k === 'var') ?? 'const';
107
+ return parts.length === 0 ? '' : `${keyword} ${parts.join(', ')};`;
108
+ }
109
+
110
+ /** Puts back the comments before an SDK statement that core's unbinding removed with it, at the statement's place. */
111
+ class RestoreComments extends JavaScriptVisitor<ExecutionContext> {
112
+ constructor(private readonly commented: {index: number; prefix: J.Space}[]) {
113
+ super();
114
+ }
115
+
116
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, _p: ExecutionContext): Promise<J | undefined> {
117
+ const text = (comment: any) => `${comment.kind}\u0000${comment.text}`;
118
+ const present = new Set(cu.statements.flatMap(s => s.element.prefix.comments.map(text)));
119
+ const statements = [...cu.statements];
120
+ for (const {index, prefix} of this.commented) {
121
+ if (statements.length === 0 || prefix.comments.every(c => present.has(text(c)))) continue;
122
+ const at = Math.min(index, statements.length - 1);
123
+ const target = statements[at].element;
124
+ const comments = [...prefix.comments, ...target.prefix.comments];
125
+ statements[at] = {...statements[at], element: {...target, prefix: {...target.prefix, whitespace: prefix.whitespace, comments}} as J};
126
+ }
127
+ return {...cu, statements} as JS.CompilationUnit;
128
+ }
129
+ }
130
+
131
+ export class ReplaceAwsSdkV2Clients extends ScanningRecipe<AwsSdkScan> {
132
+ readonly name = "org.openrewrite.node.migrate.aws-sdk-v3.replace-aws-sdk-v2-clients";
133
+ readonly displayName = "Replace AWS SDK v2 clients with v3 clients";
134
+ readonly description = "Ports the `v2-to-v3` transform of aws-sdk-js-codemod: each v2 client " +
135
+ "(`AWS.S3`, `require('aws-sdk/clients/s3')`, `import {S3} from 'aws-sdk'`, ...) becomes the v3 client class " +
136
+ "of the same shape from its `@aws-sdk/client-*` package, so calls keep their form: `.promise()` is dropped, " +
137
+ "and a callback-only call gets `{}` for its input. `AWSError` as a type becomes the service exception of the " +
138
+ "file's one client (`S3ServiceException`), or `ServiceException` from `@smithy/smithy-client` in a file with " +
139
+ "none or several, and an error's fields move to their v3 names (`code` → `name`, `statusCode` → " +
140
+ "`$metadata?.httpStatusCode`, `requestId` → `$metadata?.requestId`, `retryable` → `$retryable`, ...) where it " +
141
+ "is typed `AWSError` or handles a client call's failure. Client options move to their v3 names (credentials " +
142
+ "under `credentials`, `maxRetries` to `maxAttempts`, `s3ForcePathStyle` to `forcePathStyle`, ...). S3 " +
143
+ "`upload(...).promise()` becomes `Upload` from `@aws-sdk/lib-storage`, `getSignedUrl` and " +
144
+ "`getSignedUrlPromise` become `getSignedUrl` from `@aws-sdk/s3-request-presigner`, `createPresignedPost` " +
145
+ "becomes `createPresignedPost` from `@aws-sdk/s3-presigned-post` with `Fields.key` as its `Key`, " +
146
+ "`DynamoDB.DocumentClient` becomes `DynamoDBDocument` from " +
147
+ "`@aws-sdk/lib-dynamodb` (removing undefined values as v2 did), and v2 types (`AWS.S3.GetObjectRequest`) " +
148
+ "become v3 types (`GetObjectCommandInput`). A file is migrated whole or not at all: one that uses anything " +
149
+ "without a mechanical v3 equivalent is left unchanged, and `FindAwsSdkV2ManualMigrations` says why. So is a " +
150
+ "file that exports a client while another file of its lock group calls a v2-only API on a value from elsewhere. " +
151
+ "A lock group (a workspace root with its members, or a standalone `package.json`) is migrated whole or not at " +
152
+ "all: where one of its sources stays on v2, none of them is changed, and so where the oldest Node.js it " +
153
+ "declares (`engines.node`, `.nvmrc`, `.node-version`, a Lambda runtime) runs no v3 release.";
154
+ readonly tags = ["aws-sdk", "aws"];
155
+
156
+ @Option({
157
+ displayName: "Version",
158
+ description: "The version range the migration declares for each added `@aws-sdk/*` package. A lock group whose " +
159
+ "oldest declared Node.js can't run the newest release it admits is left on v2.",
160
+ example: ">=3.723.0 <3.968.0",
161
+ required: false
162
+ })
163
+ version?: string;
164
+
165
+ constructor(options?: {version?: string}) {
166
+ super(options);
167
+ }
168
+
169
+ initialValue(_ctx: ExecutionContext): AwsSdkScan {
170
+ return newAwsSdkScan();
171
+ }
172
+
173
+ async scanner(scan: AwsSdkScan): Promise<TreeVisitor<any, ExecutionContext>> {
174
+ return awsSdkScanner(scan);
175
+ }
176
+
177
+ async editorWithData(scan: AwsSdkScan): Promise<TreeVisitor<any, ExecutionContext>> {
178
+ const plan = new AwsSdkPlan(scan, this.version);
179
+ return rewriter(path => plan.migrates(path));
180
+ }
181
+ }
182
+
183
+ /** The editor of `ReplaceAwsSdkV2Clients`, for the sources `gate` lets through. */
184
+ function rewriter(gate: (path: string) => boolean): TreeVisitor<any, ExecutionContext> {
185
+ return new class extends JavaScriptVisitor<ExecutionContext> {
186
+ private plan!: Analysis;
187
+
188
+ private action(node: J): Action | undefined {
189
+ return this.plan.actions.get(node.id);
190
+ }
191
+
192
+ private bind(module: string, member: string, typeOnly = false): string {
193
+ return maybeBind(this, {module, member, onlyIfReferenced: false, ...(typeOnly ? {typeOnly} : {})}) ?? member;
194
+ }
195
+
196
+ private identifier(node: J, name: string): J.Identifier {
197
+ return {
198
+ kind: J.Kind.Identifier,
199
+ id: randomId(),
200
+ prefix: node.prefix,
201
+ markers: node.markers,
202
+ annotations: [],
203
+ simpleName: name
204
+ } as unknown as J.Identifier;
205
+ }
206
+
207
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
208
+ if (!gate(cu.sourcePath)) return cu;
209
+ const plan = await analyzeAwsSdk(cu);
210
+ if (plan.bindings.statements.size === 0 || plan.problems.some(problem => problem.package === undefined)) return cu;
211
+ this.plan = plan;
212
+ const replaced = new Map<string, J | undefined>();
213
+ for (const padded of cu.statements) {
214
+ const statement = padded.element;
215
+ if (!plan.bindings.statements.has(statement.id)) continue;
216
+ const text = byHand(statement, plan);
217
+ if (text === false) return cu;
218
+ if (text !== undefined) replaced.set(statement.id, text ? {...await this.parseStatement(text), prefix: statement.prefix} as J : undefined);
219
+ }
220
+ for (const [local, binding] of plan.bindings.byLocal) {
221
+ if (binding.kind !== 'client' || !plan.rebound.has(local) || replaced.has(declaringStatement(cu, local)?.id ?? '')) continue;
222
+ const v3 = v3Client(binding.client)!;
223
+ if (maybeRebind(this, {
224
+ from: {module: binding.module, member: binding.member ?? 'default'},
225
+ to: {module: v3.pkg, member: v3.name}
226
+ }) === undefined) {
227
+ return cu;
228
+ }
229
+ }
230
+ let result = await super.visitJsCompilationUnit(cu, p) as JS.CompilationUnit;
231
+ if (replaced.size > 0) {
232
+ result = {
233
+ ...result,
234
+ statements: result.statements
235
+ .filter(s => !replaced.has(s.element.id) || replaced.get(s.element.id))
236
+ .map(s => replaced.has(s.element.id) ? {...s, element: replaced.get(s.element.id)!} : s)
237
+ } as JS.CompilationUnit;
238
+ }
239
+ for (const module of plan.bindings.modules) {
240
+ maybeUnbind(this, {module});
241
+ for (const binding of plan.bindings.byLocal.values()) {
242
+ if (binding.module === module && 'member' in binding && binding.member) {
243
+ maybeUnbind(this, {module, member: binding.member});
244
+ }
245
+ }
246
+ maybeUnbind(this, {module, member: 'default'});
247
+ }
248
+ const commented = cu.statements.map((s, index) => ({index, prefix: s.element.prefix}))
249
+ .filter(({index, prefix}) => plan.bindings.statements.has(cu.statements[index].element.id) && prefix.comments.length > 0);
250
+ if (commented.length > 0) this.afterVisit.push(new RestoreComments(commented));
251
+ return result;
252
+ }
253
+
254
+ protected override async visitIdentifier(ident: J.Identifier, p: ExecutionContext): Promise<J | undefined> {
255
+ const result = await super.visitIdentifier(ident, p);
256
+ return this.reference(ident, result as J);
257
+ }
258
+
259
+ protected override async visitFieldAccess(fa: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
260
+ const action = this.action(fa);
261
+ if (action?.kind === 'errorField') {
262
+ const visited = await super.visitFieldAccess(fa, p) as J.FieldAccess;
263
+ const [first, second] = action.to.split('?.');
264
+ const renamed = {...visited, name: {...visited.name, element: {...visited.name.element, simpleName: first}}} as J.FieldAccess;
265
+ return second ? template`${renamed}?.${raw(second)}`.apply(visited, this.cursor, UNFORMATTED) : renamed;
266
+ }
267
+ if (action) return this.reference(fa, fa);
268
+ return super.visitFieldAccess(fa, p);
269
+ }
270
+
271
+ /** A client or type the file names, at `original`'s place. */
272
+ private async reference(original: J, node: J): Promise<J> {
273
+ const action = this.action(original);
274
+ switch (action?.kind) {
275
+ case 'client':
276
+ return this.identifier(node, this.bind(action.client.pkg, action.client.name));
277
+ case 'docClientType':
278
+ return this.identifier(node, this.bind(LIB_DYNAMODB, 'DynamoDBDocument'));
279
+ case 'type':
280
+ return this.identifier(node, this.bind(action.pkg, action.name, true));
281
+ case 'typeExpr': {
282
+ let text = action.text;
283
+ for (const name of action.names) {
284
+ const local = this.bind(action.pkg, name, true);
285
+ if (local !== name) text = text.replace(new RegExp(`\\b${name}\\b`, 'g'), local);
286
+ }
287
+ return {...await this.parseType(text), prefix: node.prefix} as J;
288
+ }
289
+ }
290
+ return node;
291
+ }
292
+
293
+ private async parseStatement(text: string): Promise<J> {
294
+ for await (const parsed of new JavaScriptParser().parse({text, sourcePath: 'statement.ts'})) {
295
+ return (parsed as JS.CompilationUnit).statements[0].element as J;
296
+ }
297
+ throw new Error(`Could not parse ${text}`);
298
+ }
299
+
300
+ private async parseType(text: string): Promise<J> {
301
+ const parser = new JavaScriptParser();
302
+ for await (const parsed of parser.parse({text: `let t: ${text};`, sourcePath: 'type.ts'})) {
303
+ const decl = (parsed as JS.CompilationUnit).statements[0].element as J.VariableDeclarations;
304
+ return (decl.typeExpression as JS.TypeInfo).typeIdentifier as J;
305
+ }
306
+ throw new Error(`Could not parse ${text}`);
307
+ }
308
+
309
+ protected override async visitNewClass(newClass: J.NewClass, p: ExecutionContext): Promise<J | undefined> {
310
+ const n = await super.visitNewClass(newClass, p) as J.NewClass;
311
+ const action = this.action(newClass);
312
+ if (action?.kind === 'newClient') {
313
+ const literal = objectLiteral(args(n)[0]);
314
+ if (!literal) return n;
315
+ const config = await this.clientConfig(literal);
316
+ return {...n, arguments: {...n.arguments, elements: [{...n.arguments.elements[0], element: config}]}} as J.NewClass;
317
+ }
318
+ if (action?.kind === 'newDocClient') return this.documentClient(n);
319
+ return n;
320
+ }
321
+
322
+ /** v2 client options under their v3 names. */
323
+ private async clientConfig(literal: J.NewClass): Promise<J> {
324
+ const credentials = objectMembers(literal).filter(m => CREDENTIAL_KEYS.includes(propertyName(m) ?? ''));
325
+ let result = withoutMembers(literal, m => {
326
+ const edit = configEdit(propertyName(m)!);
327
+ return edit.kind === 'drop' || (edit.kind === 'credentials' && m !== credentials[0]);
328
+ });
329
+ const statements = [];
330
+ for (const padded of result.body!.statements) {
331
+ const member = padded.element as JS.PropertyAssignment;
332
+ const edit = configEdit(propertyName(member)!);
333
+ let element: J = member;
334
+ if (edit.kind === 'rename' || edit.kind === 'maxAttempts') {
335
+ const to = edit.to ?? 'maxAttempts';
336
+ const name = member.name.element;
337
+ const renamed = isIdentifier(name) ? {...name, simpleName: to} : withStringValue(name as J.Literal, to);
338
+ let initializer = member.initializer;
339
+ if (edit.kind === 'maxAttempts' && initializer) {
340
+ const value = (initializer as J.Literal).value;
341
+ initializer = initializer.kind === J.Kind.Literal && typeof value === 'number'
342
+ ? {...initializer, value: value + 1, valueSource: String(value + 1)} as J.Literal
343
+ : await template`${initializer} + 1`.apply(initializer, this.cursor, UNFORMATTED) as J;
344
+ }
345
+ element = {...member, name: {...member.name, element: renamed}, initializer} as JS.PropertyAssignment;
346
+ } else if (edit.kind === 'credentials') {
347
+ const parts = ['({credentials: {'];
348
+ const values: J[] = [];
349
+ credentials.forEach((c, i) => {
350
+ parts[parts.length - 1] += `${i > 0 ? ', ' : ''}${propertyName(c)}: `;
351
+ values.push((c as JS.PropertyAssignment).initializer!);
352
+ parts.push('');
353
+ });
354
+ parts[parts.length - 1] += '}})';
355
+ const wrapped = await templateOf(parts, values).apply(literal, this.cursor, UNFORMATTED) as J;
356
+ const object = objectLiteral(wrapped.kind === J.Kind.Parentheses ? (wrapped as J.Parentheses<J>).tree.element : wrapped);
357
+ if (!object) return literal;
358
+ element = {...objectMembers(object)[0], prefix: member.prefix};
359
+ }
360
+ statements.push({...padded, element});
361
+ }
362
+ result = {...result, body: {...result.body!, statements}} as J.NewClass;
363
+ return result;
364
+ }
365
+
366
+ /** `new DocumentClient(options)` → `DynamoDBDocument.from(new DynamoDB(clientOptions), translateOptions)`. */
367
+ private async documentClient(n: J.NewClass): Promise<J | undefined> {
368
+ const from = this.bind(LIB_DYNAMODB, 'DynamoDBDocument');
369
+ const literal = objectLiteral(args(n)[0]);
370
+ const members = literal ? objectMembers(literal) : [];
371
+ const service = members.find(m => propertyName(m) === 'service') as JS.PropertyAssignment | undefined;
372
+ const parts: string[] = [`${from}.from(`];
373
+ const values: J[] = [];
374
+ if (service) {
375
+ values.push(service.initializer!);
376
+ } else {
377
+ const ddb = this.bind(v3Client('DynamoDB')!.pkg, 'DynamoDB');
378
+ const config = literal && withoutMembers(literal, m => MARSHALL_KEYS.has(propertyName(m)!) || UNMARSHALL_KEYS.has(propertyName(m)!));
379
+ if (config && objectMembers(config).length > 0) {
380
+ parts[0] += `new ${ddb}(`;
381
+ values.push(await this.clientConfig(config));
382
+ parts.push(')');
383
+ } else {
384
+ parts[0] += `new ${ddb}()`;
385
+ }
386
+ }
387
+ const option = (keys: Set<string>) => members.filter(m => keys.has(propertyName(m)!)) as JS.PropertyAssignment[];
388
+ const marshall = option(MARSHALL_KEYS);
389
+ const unmarshall = option(UNMARSHALL_KEYS);
390
+ const append = (text: string) => {
391
+ if (parts.length === values.length) parts.push(text);
392
+ else parts[parts.length - 1] += text;
393
+ };
394
+ append(', {marshallOptions: {');
395
+ for (const m of marshall) {
396
+ append(`${propertyName(m)}: `);
397
+ values.push(m.initializer!);
398
+ parts.push(', ');
399
+ }
400
+ append('removeUndefinedValues: true}');
401
+ if (unmarshall.length > 0) {
402
+ append(', unmarshallOptions: {');
403
+ unmarshall.forEach((m, i) => {
404
+ append(`${i > 0 ? ', ' : ''}${propertyName(m)}: `);
405
+ values.push(m.initializer!);
406
+ parts.push('');
407
+ });
408
+ append('}');
409
+ }
410
+ append('})');
411
+ return templateOf(parts, values).apply(n, this.cursor, UNFORMATTED);
412
+ }
413
+
414
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
415
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
416
+ const action = this.action(method);
417
+ switch (action?.kind) {
418
+ case 'unwrapPromise':
419
+ return {...m.select!.element, prefix: m.prefix} as J;
420
+ case 'bodyToString': {
421
+ const [encoding] = args(m);
422
+ const parts = [`${action.parenthesized ? '(' : ''}await `, `.transformToString(`, `)${action.parenthesized ? ')' : ''}`];
423
+ return templateOf(encoding ? parts : [parts[0], parts[1] + parts[2]], encoding ? [m.select!.element, encoding] : [m.select!.element])
424
+ .apply(m, this.cursor, UNFORMATTED);
425
+ }
426
+ case 'upload':
427
+ return this.upload(m);
428
+ case 'presign':
429
+ return this.presign(m, action.command, action.awaited);
430
+ case 'presignedPost':
431
+ return this.presignedPost(m);
432
+ case 'emptyArgs': {
433
+ const [callback] = args(m);
434
+ return template`${m.select!.element}.${raw(m.name.simpleName)}({}, ${callback})`.apply(m, this.cursor, UNFORMATTED);
435
+ }
436
+ case 'createSet':
437
+ return template`new Set(${args(m)[0]})`.apply(m, this.cursor, UNFORMATTED);
438
+ }
439
+ return m;
440
+ }
441
+
442
+ /** `client.upload(params, options).promise()` → `new Upload({client, params, ...options}).done()`. */
443
+ private async upload(m: J.MethodInvocation): Promise<J | undefined> {
444
+ const call = m.select!.element as J.MethodInvocation;
445
+ const receiver = call.select!.element;
446
+ const [params, options] = args(call);
447
+ const upload = this.bind(LIB_STORAGE, 'Upload');
448
+ const shorthand = isIdentifier(receiver) && receiver.simpleName === 'client';
449
+ const parts = [`new ${upload}({client${shorthand ? '' : ': '}`];
450
+ const values: J[] = [];
451
+ if (!shorthand) {
452
+ values.push(receiver);
453
+ parts.push('');
454
+ }
455
+ parts[parts.length - 1] += ', params: ';
456
+ values.push(params);
457
+ parts.push('');
458
+ if (options && isIdentifier(options)) {
459
+ parts[parts.length - 1] += ', ...';
460
+ values.push(options);
461
+ parts.push('');
462
+ }
463
+ for (const option of options && !isIdentifier(options) ? objectMembers(objectLiteral(options)!) as JS.PropertyAssignment[] : []) {
464
+ parts[parts.length - 1] += `, ${propertyName(option)}: `;
465
+ values.push(option.initializer!);
466
+ parts.push('');
467
+ }
468
+ parts[parts.length - 1] += '}).done()';
469
+ return templateOf(parts, values).apply(m, this.cursor, UNFORMATTED);
470
+ }
471
+
472
+ /** `s3.createPresignedPost(params)` → `await createPresignedPost(s3, {...params, Key: params.Fields.key})`, in place where params is a literal. */
473
+ private async presignedPost(m: J.MethodInvocation): Promise<J | undefined> {
474
+ const [params] = args(m);
475
+ const post = this.bind(S3_PRESIGNED_POST, 'createPresignedPost');
476
+ const literal = objectLiteral(params);
477
+ if (!literal) {
478
+ return templateOf([`await ${post}(`, ', {...', ', Key: ', '.Fields.key})'], [m.select!.element, params, params]).apply(m, this.cursor, UNFORMATTED);
479
+ }
480
+ const wrapped = await template`({Key: ${presignedPostKey(literal)!}})`.apply(literal, this.cursor, UNFORMATTED) as J;
481
+ const key = objectMembers(objectLiteral(wrapped.kind === J.Kind.Parentheses ? (wrapped as J.Parentheses<J>).tree.element : wrapped)!)[0];
482
+ const statements = literal.body!.statements;
483
+ const last = statements[statements.length - 1];
484
+ const withKey = {
485
+ ...literal,
486
+ body: {
487
+ ...literal.body!,
488
+ statements: [...statements.slice(0, -1), {...last, after: {...last.after, whitespace: '', comments: []}},
489
+ {...last, element: {...key, prefix: {...key.prefix, whitespace: last.element.prefix.whitespace || ' '}}}]
490
+ }
491
+ } as J.NewClass;
492
+ return templateOf([`await ${post}(`, ', ', ')'], [m.select!.element, withKey]).apply(m, this.cursor, UNFORMATTED);
493
+ }
494
+
495
+ /** `s3.getSignedUrl('getObject', {..., Expires})` → `await getSignedUrl(s3, new GetObjectCommand({...}), {expiresIn})`. */
496
+ private async presign(m: J.MethodInvocation, command: string, awaited: boolean): Promise<J | undefined> {
497
+ const [, params] = args(m);
498
+ const literal = objectLiteral(params)!;
499
+ const expires = objectMembers(literal).find(member => propertyName(member) === 'Expires') as JS.PropertyAssignment | undefined;
500
+ const input = withoutMembers(literal, member => member === expires);
501
+ const presigner = this.bind(S3_PRESIGNER, 'getSignedUrl');
502
+ const commandLocal = this.bind(v3Client('S3')!.pkg, command);
503
+ const values: J[] = [m.select!.element, input];
504
+ const parts = [`${awaited ? 'await ' : ''}${presigner}(`, `, new ${commandLocal}(`, ')'];
505
+ if (expires) {
506
+ parts[2] += ', {expiresIn: ';
507
+ values.push(expires.initializer!);
508
+ parts.push('})');
509
+ } else {
510
+ parts[2] += ')';
511
+ }
512
+ return templateOf(parts, values).apply(m, this.cursor, UNFORMATTED);
513
+ }
514
+ };
515
+ }
516
+
517
+ /**
518
+ * Whether `ReplaceAwsSdkV2Clients` changes `cu` taken alone, which its analysis can't tell where core can't move a
519
+ * binding. Whether another file or its lock group keeps it from moving is `AwsSdkPlan`'s to say.
520
+ */
521
+ export async function migrates(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<boolean> {
522
+ return await rewriter(() => true).visit(cu, ctx) !== cu;
523
+ }
@@ -4,50 +4,25 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
 
7
- import {Cursor, randomId} from "@openrewrite/rewrite";
8
- import {emptySpace, J} from "@openrewrite/rewrite/java";
9
7
  import {
10
8
  compilationUnitOf,
11
- declarationsOf,
12
- deconflict,
13
9
  hasEsmSyntax,
10
+ ImportStyle,
14
11
  isCommonJs,
15
12
  JavaScriptVisitor,
16
13
  JS,
17
14
  maybeBind,
18
- namesDeclaredIn,
19
- prologueLength,
20
- raw,
21
- scopeOf,
22
- template
15
+ scopeOf
23
16
  } from "@openrewrite/rewrite/javascript";
24
- import {bindingsOf, nodeSpecifier, requiredModule} from "./module-bindings";
17
+ import {bindingsOf, nodeSpecifier} from "./module-bindings";
25
18
 
26
- interface PendingRequire {
27
- module: string;
28
- member: string;
29
- local: string;
30
- }
31
-
32
- /**
33
- * Base visitor for migrating a library onto Node builtins: binds builtin members in whichever
34
- * module system the file uses, inserting `require`s itself in CommonJS files, where `AddImport`
35
- * can't create one yet. Subclasses call {@link resetBindings} and {@link insertPendingRequires}
36
- * around their compilation unit visit.
37
- */
38
19
  export abstract class BuiltinBindingVisitor<P> extends JavaScriptVisitor<P> {
39
- /** The modules being migrated away from, whose `require` marks a CommonJS file and anchors new requires. */
40
- protected abstract readonly migratedModules: ReadonlySet<string>;
41
-
42
- /** Whether a builtin was bound in this compilation unit, which commits the visit to an edit. */
43
20
  protected edited = false;
44
21
 
45
22
  private bound = new Map<string, string>();
46
- private pendingRequires: PendingRequire[] = [];
47
23
 
48
24
  protected resetBindings(): void {
49
25
  this.bound = new Map();
50
- this.pendingRequires = [];
51
26
  this.edited = false;
52
27
  }
53
28
 
@@ -68,12 +43,13 @@ export abstract class BuiltinBindingVisitor<P> extends JavaScriptVisitor<P> {
68
43
  } else if (this.moduleSystem(cu) === 'script') {
69
44
  // A plain script has nowhere to bind a module without turning it into one.
70
45
  return undefined;
71
- } else if (this.isRequireFile(cu)) {
72
- const taken = new Set([...namesDeclaredIn(cu), ...this.pendingRequires.map(r => r.local)]);
73
- local = deconflict(member, n => taken.has(n) || scopeOf(this.cursor).declares(n));
74
- this.pendingRequires.push({module: spec, member, local});
75
46
  } else {
76
- local = maybeBind(this, {module: spec, member, onlyIfReferenced: false});
47
+ local = maybeBind(this, {
48
+ module: spec,
49
+ member,
50
+ onlyIfReferenced: false,
51
+ style: isCommonJs(cu) ? ImportStyle.CommonJS : undefined
52
+ });
77
53
  }
78
54
  if (!local) return undefined;
79
55
  this.bound.set(key, local);
@@ -84,70 +60,9 @@ export abstract class BuiltinBindingVisitor<P> extends JavaScriptVisitor<P> {
84
60
  return local;
85
61
  }
86
62
 
87
- private requiresMigrated(stmt: J | undefined): boolean {
88
- return declarationsOf(stmt).some(d => d.variables.some(v => {
89
- let init = v.element.initializer?.element;
90
- // `require('m').default` and `require('m')()` load the module just the same.
91
- while (init?.kind === J.Kind.FieldAccess) init = (init as J.FieldAccess).target;
92
- if (init?.kind === JS.Kind.FunctionCall) {
93
- init = (init as JS.FunctionCall).function?.element;
94
- }
95
- return this.migratedModules.has(requiredModule(init) ?? '');
96
- }));
97
- }
98
-
99
- /** Whether the file loads modules with `require`, so new bindings should too. */
100
- protected isRequireFile(cu: JS.CompilationUnit): boolean {
101
- return this.moduleSystem(cu) === 'commonjs';
102
- }
103
-
104
63
  private moduleSystem(cu: JS.CompilationUnit): 'esm' | 'commonjs' | 'script' {
105
64
  if (isCommonJs(cu)) return 'commonjs';
106
65
  if (/\.m[jt]s$/.test(cu.sourcePath) || hasEsmSyntax(cu)) return 'esm';
107
66
  return 'script';
108
67
  }
109
-
110
- /**
111
- * Inserts the `require`s {@link bindNode} deferred, right after the migrated library's own. The
112
- * anchor is found in `original`, since the visit may have rewritten it (`require('m')()`), and
113
- * a visit never adds or removes top-level statements, so its index still holds in `cu`.
114
- */
115
- protected async insertPendingRequires(original: JS.CompilationUnit, cu: JS.CompilationUnit): Promise<JS.CompilationUnit> {
116
- if (this.pendingRequires.length === 0) return cu;
117
- if (cu.statements.length !== original.statements.length) {
118
- throw new Error(`Top-level statements of ${cu.sourcePath} changed while binding ${this.pendingRequires.map(r => r.member).join(', ')}`);
119
- }
120
- let anchorIndex = original.statements.findIndex(s => this.requiresMigrated(s.element));
121
- // Where the library is required in a nested scope, the new requires go at the top, after any shebang and directives.
122
- const atTop = anchorIndex < 0;
123
- if (atTop) anchorIndex = prologueLength(cu) - 1;
124
- const anchor = cu.statements[Math.max(anchorIndex, 0)];
125
-
126
- const byModule = new Map<string, PendingRequire[]>();
127
- for (const r of this.pendingRequires) {
128
- byModule.set(r.module, [...(byModule.get(r.module) ?? []), r]);
129
- }
130
-
131
- const inserted: J.RightPadded<any>[] = [];
132
- for (const [module, requires] of byModule) {
133
- const members = requires.map(r => r.local === r.member ? r.member : `${r.member}: ${r.local}`).join(', ');
134
- const stmt = await template`const { ${raw(members)} } = require('${raw(module)}')`
135
- .apply(anchor.element, new Cursor(anchor.element, this.cursor));
136
- if (!stmt) continue;
137
- inserted.push({
138
- ...anchor,
139
- element: {...stmt, prefix: {...emptySpace, whitespace: '\n'}},
140
- markers: {...anchor.markers, id: randomId()}
141
- });
142
- }
143
-
144
- const statements = [...cu.statements];
145
- if (anchorIndex < 0 && inserted.length > 0) {
146
- // First in the file: the new require takes the old first statement's prefix, which gets a line break of its own.
147
- inserted[0] = {...inserted[0], element: {...inserted[0].element, prefix: statements[0].element.prefix}};
148
- statements[0] = {...statements[0], element: {...statements[0].element, prefix: {...emptySpace, whitespace: '\n'}}};
149
- }
150
- statements.splice(anchorIndex + 1, 0, ...inserted);
151
- return {...cu, statements};
152
- }
153
68
  }