@openrewrite/recipes-nodejs 0.64.0 → 0.66.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 (78) 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/package.json +2 -2
  63. package/src/index.ts +11 -0
  64. package/src/migrate/aws-sdk-v3/add-aws-sdk-v3-dependencies.ts +71 -0
  65. package/src/migrate/aws-sdk-v3/aws-sdk-v3-node-support.ts +172 -0
  66. package/src/migrate/aws-sdk-v3/aws-sdk-v3-plan.ts +399 -0
  67. package/src/migrate/aws-sdk-v3/aws-sdk-v3-support.ts +1480 -0
  68. package/src/migrate/aws-sdk-v3/aws-sdk-v3-tables.ts +432 -0
  69. package/src/migrate/aws-sdk-v3/find-aws-sdk-v2-manual-migrations.ts +126 -0
  70. package/src/migrate/aws-sdk-v3/migrate-aws-sdk-v2-to-v3.ts +56 -0
  71. package/src/migrate/aws-sdk-v3/remove-unused-aws-sdk-v2-dependency.ts +119 -0
  72. package/src/migrate/aws-sdk-v3/replace-aws-sdk-v2-clients.ts +523 -0
  73. package/src/migrate/builtin-binding-visitor.ts +9 -94
  74. package/src/migrate/express-request-id/replace-express-request-id.ts +1 -2
  75. package/src/migrate/fs-extra/fs-extra-support.ts +1 -2
  76. package/src/migrate/increase-node-engine-version.ts +11 -7
  77. package/src/migrate/source-map-support/replace-source-map-support-api.ts +1 -1
  78. package/src/migrate/source-map-support/source-map-support-support.ts +0 -1
@@ -0,0 +1,1480 @@
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 {Column, Cursor, DataTable} from "@openrewrite/rewrite";
8
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
9
+ import {declarationsOf, JavaScriptVisitor, JS, namesDeclaredWithin, walk} from "@openrewrite/rewrite/javascript";
10
+ import {importModule, isModuleScoped, requiredModule, stringLiteral} from "../module-bindings";
11
+ import {CLIENT_TYPES, CLIENTS} from "./aws-sdk-v3-tables";
12
+
13
+ // Resolution is syntactic, as in aws-sdk-js-codemod: a client is recognized by the binding it is constructed
14
+ // from or typed as, and a call by the name of the variable or `this` property holding the client.
15
+
16
+ export const AWS_SDK = 'aws-sdk';
17
+ const GLOBAL_MODULES = new Set(['aws-sdk', 'aws-sdk/global', 'aws-sdk/lib/core', 'aws-sdk/clients/all']);
18
+ const CLIENTS_PATH = 'aws-sdk/clients/';
19
+ export const DOCUMENT_CLIENT = 'DynamoDB.DocumentClient';
20
+ export const LIB_DYNAMODB = '@aws-sdk/lib-dynamodb';
21
+ export const LIB_STORAGE = '@aws-sdk/lib-storage';
22
+ export const S3_PRESIGNER = '@aws-sdk/s3-request-presigner';
23
+ export const S3_PRESIGNED_POST = '@aws-sdk/s3-presigned-post';
24
+ /** The parameters v2's `createPresignedPost` reads; it ignores any other. */
25
+ const PRESIGNED_POST_KEYS = new Set(['Bucket', 'Fields', 'Conditions', 'Expires']);
26
+ export const SMITHY_CLIENT = '@smithy/smithy-client';
27
+ /** v3 clients whose service exception isn't named `<Client>ServiceException` (checked against npm, 3.1166.0). */
28
+ const OTHER_EXCEPTION_NAMES = new Set(['ElasticBeanstalk']);
29
+ /** `AWSError` fields → what a v3 `ServiceException` holds them as, after the error. */
30
+ const ERROR_FIELDS: Record<string, string> = {
31
+ code: 'name',
32
+ statusCode: '$metadata?.httpStatusCode',
33
+ requestId: '$metadata?.requestId',
34
+ extendedRequestId: '$metadata?.extendedRequestId',
35
+ cfId: '$metadata?.cfId',
36
+ retryable: '$retryable',
37
+ };
38
+ /** `AWSError` fields a v3 `ServiceException` has no counterpart for. */
39
+ const LOST_ERROR_FIELDS = new Set(['time', 'hostname', 'region', 'retryDelay', 'originalError']);
40
+ const NATIVE_TYPES = new Set(['string', 'number', 'boolean', 'Date', 'Uint8Array', 'Array', 'Record']);
41
+
42
+ export function isAwsSdkModule(module: string | undefined): boolean {
43
+ return module === AWS_SDK || !!module?.startsWith(`${AWS_SDK}/`);
44
+ }
45
+
46
+ export interface V3Client {
47
+ /** The v2 client name, e.g. `CUR`. */
48
+ v2: string;
49
+ /** The v3 client class, e.g. `CostAndUsageReportService`. */
50
+ name: string;
51
+ pkg: string;
52
+ }
53
+
54
+ export function v3Client(v2: string): V3Client | undefined {
55
+ if (!Object.prototype.hasOwnProperty.call(CLIENTS, v2)) return undefined;
56
+ const entry = CLIENTS[v2];
57
+ return typeof entry === 'string' ? {v2, name: v2, pkg: entry} : {v2, name: entry[0], pkg: entry[1]};
58
+ }
59
+
60
+ const DEEP_PATHS = new Map(Object.keys(CLIENTS).map(name => [`${CLIENTS_PATH}${name.toLowerCase()}`, name]));
61
+
62
+ function clientOfModule(module: string): string | undefined {
63
+ return DEEP_PATHS.get(module);
64
+ }
65
+
66
+ interface TypeEntry {
67
+ /** The v3 type name, for an operation's input or output. */
68
+ named?: string;
69
+ /** The type a v2 alias stands for, for an alias v3 doesn't declare. */
70
+ alias?: string;
71
+ }
72
+
73
+ const typeTables = new Map<string, Map<string, TypeEntry>>();
74
+
75
+ /** The mapped v2 types of `client`, or undefined for a client whose types aren't mapped. */
76
+ function typesOf(client: string): Map<string, TypeEntry> | undefined {
77
+ let table = typeTables.get(client);
78
+ if (!table && Object.prototype.hasOwnProperty.call(CLIENT_TYPES, client)) {
79
+ table = new Map();
80
+ for (const entry of CLIENT_TYPES[client].split(';')) {
81
+ const alias = entry.indexOf(':');
82
+ const named = entry.indexOf('=');
83
+ if (alias >= 0) {
84
+ table.set(entry.substring(0, alias), {alias: entry.substring(alias + 1)});
85
+ } else if (named >= 0) {
86
+ table.set(entry.substring(0, named), {named: entry.substring(named + 1)});
87
+ } else {
88
+ table.set(entry, {named: entry.replace(/(Request|Input)$/, 'CommandInput').replace(/(Response|Output)$/, 'CommandOutput')});
89
+ }
90
+ }
91
+ typeTables.set(client, table);
92
+ }
93
+ return table;
94
+ }
95
+
96
+ /** A v2 binding the file's top-level imports and requires make. */
97
+ export type AwsBinding =
98
+ | {kind: 'global'; module: string}
99
+ | {kind: 'client'; client: string; module: string; member?: string}
100
+ | {kind: 'docClient'; module: string; member?: string}
101
+ | {kind: 'type'; client: string; type: string; module: string; member: string}
102
+ | {kind: 'error'; module: string; member: string}
103
+ | {kind: 'other'; module: string; member?: string};
104
+
105
+ export interface AwsBindings {
106
+ byLocal: Map<string, AwsBinding>;
107
+ /** Top-level statements that import or require the SDK, which the migration replaces. */
108
+ statements: Set<string>;
109
+ /** Every v2 module the file binds. */
110
+ modules: Set<string>;
111
+ /** The `aws-sdk` string literals those statements hold, which aren't references of their own. */
112
+ specifiers: Set<string>;
113
+ }
114
+
115
+ function bindingFor(module: string, member: string | undefined): AwsBinding {
116
+ if (member === 'AWSError' && (GLOBAL_MODULES.has(module) || module === 'aws-sdk/lib/error')) return {kind: 'error', module, member};
117
+ if (GLOBAL_MODULES.has(module)) {
118
+ if (member === undefined || member === 'default') return {kind: 'global', module};
119
+ return v3Client(member) ? {kind: 'client', client: member, module, member} : {kind: 'other', module, member};
120
+ }
121
+ const client = clientOfModule(module);
122
+ if (!client) return {kind: 'other', module, member};
123
+ if (member === undefined || member === 'default') return {kind: 'client', client, module, member};
124
+ if (client === 'DynamoDB' && member === 'DocumentClient') return {kind: 'docClient', module, member};
125
+ return {kind: 'type', client, type: member, module, member};
126
+ }
127
+
128
+ /** The module a `require('m')` or `require('m').X` initializer loads, with the member it reads. */
129
+ export function requireOf(e: J | undefined): {module: string; member?: string; literal: J} | undefined {
130
+ if (e?.kind === J.Kind.FieldAccess) {
131
+ const fa = e as J.FieldAccess;
132
+ const inner = requireOf(fa.target);
133
+ return inner && inner.member === undefined ? {...inner, member: fa.name.element.simpleName} : undefined;
134
+ }
135
+ const module = requiredModule(e);
136
+ return module !== undefined ? {module, literal: (e as J.MethodInvocation).arguments.elements[0].element} : undefined;
137
+ }
138
+
139
+ export function awsBindingsOf(cu: JS.CompilationUnit): AwsBindings {
140
+ const result: AwsBindings = {byLocal: new Map(), statements: new Set(), modules: new Set(), specifiers: new Set()};
141
+ for (const padded of cu.statements) {
142
+ const stmt = padded.element;
143
+ if (stmt?.kind === JS.Kind.Import) {
144
+ const imp = stmt as JS.Import;
145
+ const equals = imp.initializer ? requireOf(imp.initializer.element) : undefined;
146
+ const module = equals?.module ?? importModule(imp);
147
+ if (!isAwsSdkModule(module)) continue;
148
+ result.statements.add(imp.id);
149
+ result.modules.add(module!);
150
+ const literal = equals?.literal ?? imp.moduleSpecifier?.element;
151
+ if (literal) result.specifiers.add(literal.id);
152
+ const clause = imp.importClause;
153
+ if (!clause) continue;
154
+ if (clause.name?.element) result.byLocal.set(clause.name.element.simpleName, bindingFor(module!, equals?.member));
155
+ const named = clause.namedBindings;
156
+ if (named && isIdentifier(named)) {
157
+ result.byLocal.set(named.simpleName, bindingFor(module!, undefined));
158
+ } else if (named?.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
159
+ result.byLocal.set(((named as JS.Alias).alias as J.Identifier).simpleName, bindingFor(module!, undefined));
160
+ } else if (named?.kind === JS.Kind.NamedImports) {
161
+ for (const el of (named as JS.NamedImports).elements.elements) {
162
+ const spec = el.element as JS.ImportSpecifier;
163
+ if (spec.kind !== JS.Kind.ImportSpecifier) continue;
164
+ if (isIdentifier(spec.specifier)) {
165
+ result.byLocal.set(spec.specifier.simpleName, bindingFor(module!, spec.specifier.simpleName));
166
+ } else if (spec.specifier.kind === JS.Kind.Alias) {
167
+ const alias = spec.specifier as JS.Alias;
168
+ const property = alias.propertyName.element;
169
+ if (isIdentifier(alias.alias) && isIdentifier(property)) {
170
+ result.byLocal.set(alias.alias.simpleName, bindingFor(module!, property.simpleName));
171
+ }
172
+ }
173
+ }
174
+ }
175
+ continue;
176
+ }
177
+ for (const decl of declarationsOf(stmt)) {
178
+ for (const v of decl.variables) {
179
+ const variable = v.element;
180
+ const required = requireOf(variable.initializer?.element);
181
+ if (!required || !isAwsSdkModule(required.module)) continue;
182
+ result.statements.add(stmt.id);
183
+ result.modules.add(required.module);
184
+ result.specifiers.add(required.literal.id);
185
+ const name = variable.name as J;
186
+ if (isIdentifier(name)) {
187
+ result.byLocal.set(name.simpleName, bindingFor(required.module, required.member));
188
+ } else if (name.kind === JS.Kind.ObjectBindingPattern && required.member === undefined) {
189
+ for (const el of (name as JS.ObjectBindingPattern).bindings.elements) {
190
+ const b = el.element;
191
+ if (isIdentifier(b)) {
192
+ result.byLocal.set(b.simpleName, bindingFor(required.module, b.simpleName));
193
+ } else if (b.kind === JS.Kind.BindingElement) {
194
+ const be = b as JS.BindingElement;
195
+ const local = be.name as J;
196
+ const prop = be.propertyName?.element;
197
+ if (isIdentifier(local) && !be.initializer) {
198
+ result.byLocal.set(local.simpleName, bindingFor(required.module, prop && isIdentifier(prop) ? prop.simpleName : local.simpleName));
199
+ } else {
200
+ result.byLocal.set(isIdentifier(local) ? local.simpleName : '', {kind: 'other', module: required.module});
201
+ }
202
+ } else {
203
+ result.byLocal.set('', {kind: 'other', module: required.module});
204
+ }
205
+ }
206
+ } else {
207
+ result.byLocal.set('', {kind: 'other', module: required.module});
208
+ }
209
+ }
210
+ }
211
+ }
212
+ return result;
213
+ }
214
+
215
+ export class AwsSdkManualMigrationStep {
216
+ @Column({displayName: "Source path", description: "Path of the file the migration left unchanged."})
217
+ sourcePath!: string;
218
+
219
+ @Column({displayName: "Construct", description: "The v2 construct that has no mechanical v3 equivalent, e.g. `AWS.config.update`."})
220
+ construct!: string;
221
+
222
+ @Column({displayName: "Reason", description: "Why it can't be migrated automatically, and what to do instead."})
223
+ reason!: string;
224
+ }
225
+
226
+ export function awsSdkManualMigrationSteps(): DataTable<AwsSdkManualMigrationStep> {
227
+ return new DataTable<AwsSdkManualMigrationStep>(
228
+ "org.openrewrite.node.table.AwsSdkManualMigrationSteps",
229
+ "AWS SDK v2 manual migration steps",
230
+ "Uses of the AWS SDK for JavaScript v2 that the migration to v3 left in place, and why.",
231
+ AwsSdkManualMigrationStep,
232
+ );
233
+ }
234
+
235
+ export const REASONS = {
236
+ globalConfig: "v3 has no global configuration: `AWS.config` settings apply to no v3 client. Pass `region`, " +
237
+ "`credentials` and the other options to each client's constructor instead.",
238
+ events: "v3 has no request events or `AWS.Request`/`AWS.EventListeners`. Use client middleware " +
239
+ "(`client.middlewareStack.add`) for what the listeners did.",
240
+ credentials: "v3 credential providers are functions, not classes. Use the matching provider from " +
241
+ "`@aws-sdk/credential-providers` (`fromIni`, `fromEnv`, `fromInstanceMetadata`, `fromTemporaryCredentials`, ...) " +
242
+ "as the client's `credentials` option.",
243
+ config: "`AWS.Config` has no v3 class. Pass a plain object of v3 client options to each client.",
244
+ awsError: "v3 errors are `ServiceException`s from `@smithy/smithy-client`: the error code is `name` and the HTTP " +
245
+ "status `$metadata.httpStatusCode`. `AWSError` is migrated where it names a type, not as a value.",
246
+ lostErrorField: (name: string) => `An AWS error's \`${name}\` has no v3 counterpart: a v3 \`ServiceException\` holds ` +
247
+ "`name`, `message`, `$fault`, `$retryable` and `$metadata` (`httpStatusCode`, `requestId`, `extendedRequestId`, " +
248
+ "`cfId`, `attempts`, `totalRetryDelay`). Rewrite this use by hand.",
249
+ errorFieldForm: "An AWS error's fields are read here other than as `err.field` (destructured, as `err['field']`, or " +
250
+ "assigned), so they can't be moved to their v3 names (`code` → `name`, `statusCode` → `$metadata.httpStatusCode`, ...). " +
251
+ "Read them as `err.field`.",
252
+ retryable: "An AWS error's `retryable` is `$retryable` in v3, an object set only for errors the service models as " +
253
+ "retryable rather than a boolean, so it is migrated only where it is tested for truth (`if (err.retryable)`).",
254
+ indirectError: "This handles the failure of a function of this file that calls an AWS client, so the error fields " +
255
+ "read here (`code`, `statusCode`, ...) change in v3 (`name`, `$metadata.httpStatusCode`, ...), but the migration " +
256
+ "can't tell whether the error comes from the client. Rename them by hand where it does.",
257
+ response: "v3 responses have no `$response`. Read `$metadata` for the request id and status, or add middleware for the raw response.",
258
+ request: "Without a callback or `.promise()`, a v2 call returns an `AWS.Request` (`send`, `on`, `createReadStream`, " +
259
+ "`eachPage`, `abort`). v3 calls send at once and return a promise; stream an S3 body from `Body` of the awaited " +
260
+ "`getObject`, and page with the client's `paginate*` functions.",
261
+ shadowed: (name: string) => `\`${name}\` names both the SDK import and something the file declares, such as a ` +
262
+ "parameter, so the migration can't tell which uses are the SDK's. Rename one of them.",
263
+ orphanCall: (name: string) => `\`${name}\` on a value created in another file, which may be a v2 client: v3 clients ` +
264
+ "have no such method. Use the v3 form once its client is migrated.",
265
+ exportedClient: "The file hands out a v2 client that another file of its project calls as v2 (`.promise()`, " +
266
+ "`getSignedUrl`, ...), so it isn't migrated: that file would break. Migrate the calls there first.",
267
+ unparsed: "The file references `aws-sdk` but couldn't be parsed, so the migration can't tell how it uses the SDK. " +
268
+ "Migrate it by hand.",
269
+ unmovable: "The file binds the SDK in a way the migration can't move to v3 (such as a `let` destructuring of " +
270
+ "`require('aws-sdk')`), so it isn't migrated. Bind each client with its own `const` or import.",
271
+ unknownReceiver: "`.promise()` is called on something not known to be a v2 client in this file, so the file isn't " +
272
+ "migrated: it would mix v2 and v3 calls. Type the receiver as the client, or migrate the call by hand.",
273
+ orphanPromise: "`.promise()` on a value created in another file, which may be a v2 client the migration turns into " +
274
+ "a v3 one. v3 calls return a promise already; drop `.promise()` once its client is migrated.",
275
+ clientConfig: (key: string) => `The v2 client option \`${key}\` has no v3 equivalent the recipe knows. ` +
276
+ "See the v3 client configuration (https://github.com/aws/aws-sdk-js-v3/blob/main/UPGRADING.md#client-constructors).",
277
+ httpOptions: "`httpOptions` moves to `requestHandler` in v3, e.g. `requestHandler: {requestTimeout, httpsAgent}` " +
278
+ "or a `NodeHttpHandler` from `@smithy/node-http-handler`.",
279
+ params: "v3 clients have no bound `params`: pass them to each call.",
280
+ configNotLiteral: "The client options aren't written as an object literal, so v2 options in them (`accessKeyId`, " +
281
+ "`s3ForcePathStyle`, `httpOptions`, ...) can't be moved to their v3 names.",
282
+ upload: "S3 `upload` without `.promise()` (a callback, `send`, or `on('httpUploadProgress')`) has no direct v3 form. " +
283
+ "Use `new Upload({client, params}).done()` from `@aws-sdk/lib-storage`, with `upload.on('httpUploadProgress', ...)` for progress.",
284
+ signedUrl: "S3 `getSignedUrl` maps to `getSignedUrl(client, new <Operation>Command(params), {expiresIn})` from " +
285
+ "`@aws-sdk/s3-request-presigner`, which returns a promise. Await it in an async function, with the operation " +
286
+ "and params written in place so `Expires` can move to `expiresIn`.",
287
+ presignedPost: "S3 `createPresignedPost` moves to `createPresignedPost` from `@aws-sdk/s3-presigned-post`, which takes " +
288
+ "the client and the object's `Key` and returns a promise. It is migrated without a callback, in an async function, " +
289
+ "with params written in place or as a `const` literal holding `Bucket`, `Fields` (with `key`), `Conditions` and `Expires`.",
290
+ presignedPostKey: "v2's `createPresignedPost` ignores these params (it reads `Bucket`, `Fields`, `Conditions` and " +
291
+ "`Expires`), while v3's requires `Key` and signs it as the exact object key. Put the key in `Fields.key` if that " +
292
+ "is what is meant (v2 then signs it the same way), or drop what v2 ignores.",
293
+ waiter: "v3 waiters are functions: `waitFor('bucketExists', params)` becomes `waitUntilBucketExists({client, maxWaitTime}, params)`.",
294
+ body: "In v3 an S3 `getObject` `Body` is a stream, not a Buffer. Read it with `await Body.transformToString()` or " +
295
+ "`await Body.transformToByteArray()`.",
296
+ clientProperty: "A v3 client's properties differ from v2's: `config` values are resolved asynchronously and " +
297
+ "`endpoint` and the service's `api` metadata are gone.",
298
+ managedUpload: "`S3.ManagedUpload` moves to `Upload` from `@aws-sdk/lib-storage`.",
299
+ converter: "`DynamoDB.Converter` moves to `marshall`/`unmarshall` from `@aws-sdk/util-dynamodb`.",
300
+ documentClientOptions: "DocumentClient options other than an object literal of client options, `service`, " +
301
+ "`convertEmptyValues` and `wrapNumbers` have no v3 equivalent the recipe knows.",
302
+ untypedClient: (client: string) => `The recipe maps the types of a curated list of clients, and not ${client}'s. ` +
303
+ `Import the v3 type from its \`@aws-sdk/client-*\` package (\`<Operation>CommandInput\`, \`<Operation>CommandOutput\`, or the shape's name).`,
304
+ docClientType: "This DocumentClient type has no counterpart in `@aws-sdk/lib-dynamodb`; use the type from `@aws-sdk/client-dynamodb`.",
305
+ module: (module: string) => `\`${module}\` has no v3 equivalent the recipe knows.`,
306
+ dynamic: "The SDK is loaded or mocked somewhere other than a top-level import or require (a nested `require`, " +
307
+ "`import()`, a re-export, or a test mock such as `jest.mock('aws-sdk')`). Migrate it, and any mock, by hand.",
308
+ value: (name: string) => `\`${name}\` is used as a value rather than constructed or named as a type, so it can't be rewritten in place.`,
309
+ member: (name: string) => `\`${name}\` has no v3 equivalent the recipe knows.`,
310
+ };
311
+
312
+ /** What the rewrite does to one node, by id. */
313
+ export type Action =
314
+ | {kind: 'client'; client: V3Client}
315
+ | {kind: 'keep'}
316
+ | {kind: 'docClientType'}
317
+ | {kind: 'type'; pkg: string; name: string}
318
+ | {kind: 'typeExpr'; pkg: string; text: string; names: string[]}
319
+ | {kind: 'newClient'}
320
+ | {kind: 'newDocClient'}
321
+ | {kind: 'unwrapPromise'}
322
+ | {kind: 'bodyToString'; parenthesized: boolean}
323
+ | {kind: 'upload'}
324
+ | {kind: 'presign'; command: string; awaited: boolean}
325
+ | {kind: 'presignedPost'}
326
+ | {kind: 'emptyArgs'}
327
+ | {kind: 'createSet'}
328
+ | {kind: 'errorField'; to: string};
329
+
330
+ export interface Problem {
331
+ id: string;
332
+ construct: string;
333
+ reason: string;
334
+ /** A v2 call on a value from another file, which only matters in a project that declares `aws-sdk`. */
335
+ orphan?: boolean;
336
+ /** The package the call's receiver comes from, which voids the problem where the source's project declares it. */
337
+ package?: string;
338
+ }
339
+
340
+ export interface Analysis {
341
+ bindings: AwsBindings;
342
+ actions: Map<string, Action>;
343
+ problems: Problem[];
344
+ /** The v3 packages the migrated file imports. */
345
+ packages: Set<string>;
346
+ /** Locals of client bindings whose name the migration keeps, rebinding them to the v3 class. */
347
+ rebound: Set<string>;
348
+ /** Whether the file calls a v2-only API (`.promise()`, `getSignedUrl`, ...) on a value from another file. */
349
+ foreign: boolean;
350
+ /** The statements that export a client or the SDK, which another file may still call as v2. */
351
+ exports: string[];
352
+ }
353
+
354
+ export const SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
355
+
356
+ export function declaresAwsSdk(pkg: Record<string, any> | undefined): boolean {
357
+ return !!pkg && SECTIONS.some(section => pkg[section] && Object.prototype.hasOwnProperty.call(pkg[section], AWS_SDK));
358
+ }
359
+
360
+ /** v2 client methods v3 clients lack, which mark a call on a client from another file. */
361
+ const V2_ONLY_CALLS = new Set(['getSignedUrl', 'getSignedUrlPromise', 'createPresignedPost', 'waitFor']);
362
+
363
+ /** `x.getObject(params).createReadStream()`, the v2 request's stream, unlike `fs.createReadStream(path)`. */
364
+ function isRequestStream(m: J.MethodInvocation): boolean {
365
+ return m.name.simpleName === 'createReadStream' && m.select?.element.kind === J.Kind.MethodInvocation;
366
+ }
367
+
368
+ /** The deepest of `dirs` holding `path`, which is the project a source belongs to. */
369
+ export function ownerOf(path: string, dirs: string[]): string | undefined {
370
+ return dirs.filter(dir => dir === '' || path.startsWith(dir + '/')).sort((a, b) => b.length - a.length)[0];
371
+ }
372
+
373
+ const CREDENTIAL_CLASSES = new Set(['Credentials', 'CredentialProviderChain', 'ChainableTemporaryCredentials',
374
+ 'CognitoIdentityCredentials', 'EC2MetadataCredentials', 'ECSCredentials', 'EnvironmentCredentials',
375
+ 'FileSystemCredentials', 'ProcessCredentials', 'RemoteCredentials', 'SAMLCredentials', 'SharedIniFileCredentials',
376
+ 'SsoCredentials', 'TemporaryCredentials', 'TokenFileWebIdentityCredentials', 'WebIdentityCredentials',
377
+ 'SSOTokenProvider', 'StaticTokenProvider', 'Token', 'TokenProviderChain']);
378
+
379
+ function memberReason(name: string): string {
380
+ if (name === 'config') return REASONS.globalConfig;
381
+ if (name === 'Config') return REASONS.config;
382
+ if (name === 'Request' || name === 'EventListeners' || name === 'Response' || name === 'SequentialExecutor') return REASONS.events;
383
+ if (CREDENTIAL_CLASSES.has(name)) return REASONS.credentials;
384
+ if (name === 'AWSError') return REASONS.awsError;
385
+ return REASONS.member(`AWS.${name}`);
386
+ }
387
+
388
+ /** Client config keys v3 names differently. */
389
+ const RENAMED_KEYS: Record<string, string> = {
390
+ s3ForcePathStyle: 'forcePathStyle',
391
+ s3BucketEndpoint: 'bucketEndpoint',
392
+ s3UseArnRegion: 'useArnRegion',
393
+ sslEnabled: 'tls',
394
+ credentialProvider: 'credentials',
395
+ };
396
+ /** Client config keys v3 takes as they are. */
397
+ const KEPT_KEYS = new Set(['credentials', 'customUserAgent', 'endpoint', 'endpointCacheSize', 'endpointDiscoveryEnabled',
398
+ 'logger', 'region', 'systemClockOffset', 'useAccelerateEndpoint', 'useDualstackEndpoint', 'useFipsEndpoint']);
399
+ /** Client config keys whose v2 setting v3 always behaves as, so they are dropped. */
400
+ const DROPPED_KEYS = new Set(['apiVersion', 'correctClockSkew', 'hostPrefixEnabled', 'signatureCache',
401
+ 'computeChecksums', 'paramValidation', 'convertResponseTypes']);
402
+ export const CREDENTIAL_KEYS = ['accessKeyId', 'secretAccessKey', 'sessionToken'];
403
+
404
+ export function propertyName(prop: J): string | undefined {
405
+ if (prop.kind !== JS.Kind.PropertyAssignment) return undefined;
406
+ const name = (prop as JS.PropertyAssignment).name.element;
407
+ if (isIdentifier(name)) return name.simpleName;
408
+ return stringLiteral(name);
409
+ }
410
+
411
+ export function objectLiteral(e: J | undefined): J.NewClass | undefined {
412
+ return e?.kind === J.Kind.NewClass && !(e as J.NewClass).class && (e as J.NewClass).body ? e as J.NewClass : undefined;
413
+ }
414
+
415
+ export function objectMembers(literal: J.NewClass): J[] {
416
+ return literal.body!.statements.map(s => s.element);
417
+ }
418
+
419
+ export function args(m: J.MethodInvocation | J.NewClass): J[] {
420
+ return m.arguments.elements.map(a => a.element).filter(a => a.kind !== J.Kind.Empty);
421
+ }
422
+
423
+ /** `e` itself, or the function a `function () {}` expression holds. */
424
+ function unwrapFunction(e: J | undefined): J | undefined {
425
+ return e?.kind === JS.Kind.StatementExpression ? (e as JS.StatementExpression).statement as J : e;
426
+ }
427
+
428
+ export function isFunction(e: J | undefined): boolean {
429
+ const fn = unwrapFunction(e);
430
+ return fn?.kind === JS.Kind.ArrowFunction || fn?.kind === J.Kind.Lambda || fn?.kind === J.Kind.MethodDeclaration;
431
+ }
432
+
433
+ /** A value of a client config key the migration can't carry over, or undefined when it can. */
434
+ function configProblem(literal: J.NewClass): {construct: string; reason: string} | undefined {
435
+ const keys = new Set<string>();
436
+ for (const member of objectMembers(literal)) {
437
+ const key = propertyName(member);
438
+ if (key === undefined) return {construct: 'client options', reason: REASONS.configNotLiteral};
439
+ keys.add(key);
440
+ if (key === 'signatureVersion') {
441
+ const value = stringLiteral((member as JS.PropertyAssignment).initializer);
442
+ if (value !== 'v4') return {construct: key, reason: "v3 signs requests with Signature Version 4 only."};
443
+ } else if (key === 'httpOptions') {
444
+ return {construct: key, reason: REASONS.httpOptions};
445
+ } else if (key === 'params') {
446
+ return {construct: key, reason: REASONS.params};
447
+ } else if (!RENAMED_KEYS[key] && !KEPT_KEYS.has(key) && !DROPPED_KEYS.has(key) && !CREDENTIAL_KEYS.includes(key) && key !== 'maxRetries') {
448
+ return {construct: key, reason: REASONS.clientConfig(key)};
449
+ }
450
+ }
451
+ if (keys.has('credentials') && CREDENTIAL_KEYS.some(k => keys.has(k))) {
452
+ return {construct: 'credentials', reason: "Both `credentials` and `accessKeyId`/`secretAccessKey` are set."};
453
+ }
454
+ return undefined;
455
+ }
456
+
457
+ export interface ConfigEdit {
458
+ kind: 'keep' | 'rename' | 'drop' | 'maxAttempts' | 'credentials';
459
+ to?: string;
460
+ }
461
+
462
+ export function configEdit(key: string): ConfigEdit {
463
+ if (RENAMED_KEYS[key]) return {kind: 'rename', to: RENAMED_KEYS[key]};
464
+ if (DROPPED_KEYS.has(key) || key === 'signatureVersion') return {kind: 'drop'};
465
+ if (key === 'maxRetries') return {kind: 'maxAttempts'};
466
+ if (CREDENTIAL_KEYS.includes(key)) return {kind: 'credentials'};
467
+ return {kind: 'keep'};
468
+ }
469
+
470
+ /** The identifiers of a dotted chain, `AWS.S3.Types.Tag` → `AWS, S3, Types, Tag`, or undefined for anything else. */
471
+ export function chainOf(e: J | undefined): string[] | undefined {
472
+ if (!e) return undefined;
473
+ if (isIdentifier(e)) return [e.simpleName];
474
+ if (e.kind !== J.Kind.FieldAccess) return undefined;
475
+ const fa = e as J.FieldAccess;
476
+ const target = chainOf(fa.target);
477
+ return target ? [...target, fa.name.element.simpleName] : undefined;
478
+ }
479
+
480
+ type ClientKind = string;
481
+
482
+ const TYPE_KINDS = new Set<string>([JS.Kind.TypeInfo, JS.Kind.TypeDeclaration, JS.Kind.Union, JS.Kind.Intersection,
483
+ J.Kind.ParameterizedType, J.Kind.ArrayType, JS.Kind.TypeOperator, JS.Kind.IndexedAccessType,
484
+ JS.Kind.IndexedAccessTypeIndexType, JS.Kind.TypeQuery, JS.Kind.FunctionType, JS.Kind.TypeLiteral, JS.Kind.MappedType,
485
+ JS.Kind.ConditionalType, JS.Kind.TypePredicate, JS.Kind.ExpressionWithTypeArguments, J.Kind.TypeParameter,
486
+ J.Kind.TypeParameters, JS.Kind.Tuple, JS.Kind.InferType, J.Kind.NullableType, J.Kind.ParenthesizedTypeTree,
487
+ JS.Kind.TypeTreeExpression]);
488
+
489
+ /** Whether the node at `cursor` names a type rather than a value. */
490
+ function inTypeContext(cursor: Cursor): boolean {
491
+ let child: any = cursor.value;
492
+ for (let c = cursor.parentTree(); c; c = c.parentTree()) {
493
+ const kind = c.value?.kind;
494
+ if (TYPE_KINDS.has(kind)) return true;
495
+ if (kind === JS.Kind.As || kind === JS.Kind.SatisfiesExpression) {
496
+ return (c.value as JS.As).right === child;
497
+ }
498
+ if (kind === J.Kind.TypeCast || (kind === J.Kind.ControlParentheses && c.parentTree()?.value?.kind === J.Kind.TypeCast)) return true;
499
+ if (kind !== J.Kind.FieldAccess) return false;
500
+ child = c.value;
501
+ }
502
+ return false;
503
+ }
504
+
505
+ function isAsync(modifiers: J.Modifier[] | undefined): boolean {
506
+ return !!modifiers?.some(m => m.keyword === 'async' || m.type === J.ModifierType.Async);
507
+ }
508
+
509
+ /** Whether `await` may stand at the cursor: inside an async function. */
510
+ function awaitAllowed(cursor: Cursor): boolean {
511
+ for (let c = cursor.parentTree(); c; c = c.parentTree()) {
512
+ const v = c.value;
513
+ if (v?.kind === J.Kind.MethodDeclaration) return isAsync((v as J.MethodDeclaration).modifiers);
514
+ if (v?.kind === JS.Kind.ArrowFunction) return isAsync((v as JS.ArrowFunction).modifiers);
515
+ if (v?.kind === J.Kind.Lambda) {
516
+ const parent = c.parentTree()?.value;
517
+ if (parent?.kind !== JS.Kind.ArrowFunction) return false;
518
+ }
519
+ if (v?.kind === JS.Kind.CompilationUnit) return false;
520
+ }
521
+ return false;
522
+ }
523
+
524
+ /**
525
+ * Plans the migration of one file: what each v2 node becomes, which v3 packages the result imports, and every
526
+ * construct that keeps the file from migrating at all.
527
+ */
528
+ export async function analyzeAwsSdk(cu: JS.CompilationUnit): Promise<Analysis> {
529
+ const bindings = awsBindingsOf(cu);
530
+ const analysis: Analysis = {bindings, actions: new Map(), problems: [], packages: new Set(), rebound: new Set(), foreign: false, exports: []};
531
+ if (bindings.statements.size === 0) {
532
+ await new OrphanVisitor(analysis).visit(cu, undefined);
533
+ return analysis;
534
+ }
535
+ for (const [local, binding] of bindings.byLocal) {
536
+ if (binding.kind === 'other') {
537
+ const construct = binding.member ? `${binding.module}#${binding.member}` : binding.module;
538
+ const reason = !local ? REASONS.module(binding.module)
539
+ : GLOBAL_MODULES.has(binding.module) && binding.member ? memberReason(binding.member) : REASONS.module(binding.module);
540
+ analysis.problems.push({id: [...bindings.statements][0], construct, reason});
541
+ }
542
+ }
543
+ // Bindings are tracked by name, so a file that declares one of their names again elsewhere is left alone.
544
+ const declared = new Set(cu.statements.filter(s => !bindings.statements.has(s.element.id)).flatMap(s => [...namesDeclaredWithin(s.element)]));
545
+ for (const local of bindings.byLocal.keys()) {
546
+ if (local && declared.has(local)) analysis.problems.push({id: [...bindings.statements][0], construct: local, reason: REASONS.shadowed(local)});
547
+ }
548
+ if (analysis.problems.length > 0) return analysis;
549
+ const clients = collectClients(cu, bindings);
550
+ await new AnalysisVisitor(analysis, clients, promisedOnly(cu), constantLiterals(cu)).visit(cu, undefined);
551
+ analysis.exports = clientExports(cu, bindings, clients);
552
+ return analysis;
553
+ }
554
+
555
+ /** The kind of client `e` constructs or names as a type, or undefined. */
556
+ function clientKind(e: J | undefined, bindings: AwsBindings): ClientKind | undefined {
557
+ const chain = chainOf(e);
558
+ if (!chain) return undefined;
559
+ const binding = bindings.byLocal.get(chain[0]);
560
+ if (!binding) return undefined;
561
+ const rest = chain.slice(1).filter(n => n !== 'Types');
562
+ if (binding.kind === 'global') {
563
+ if (rest.length === 1 && v3Client(rest[0])) return rest[0];
564
+ if (rest.length === 2 && rest[0] === 'DynamoDB' && rest[1] === 'DocumentClient') return DOCUMENT_CLIENT;
565
+ } else if (binding.kind === 'client') {
566
+ if (rest.length === 0) return binding.client;
567
+ if (rest.length === 1 && binding.client === 'DynamoDB' && rest[0] === 'DocumentClient') return DOCUMENT_CLIENT;
568
+ } else if (binding.kind === 'docClient' && rest.length === 0) {
569
+ return DOCUMENT_CLIENT;
570
+ }
571
+ return undefined;
572
+ }
573
+
574
+ /** The client a variable or property is initialized or assigned with. */
575
+ function kindOfValue(e: J | undefined, bindings: AwsBindings): ClientKind | undefined {
576
+ if (!e) return undefined;
577
+ if (e.kind === J.Kind.NewClass) return clientKind((e as J.NewClass).class as J, bindings);
578
+ if (e.kind === J.Kind.Parentheses) return kindOfValue((e as J.Parentheses<J>).tree.element, bindings);
579
+ if (e.kind === J.Kind.MethodInvocation) {
580
+ // AWS X-Ray's `captureAWSClient(client)` returns the client it instruments.
581
+ const m = e as J.MethodInvocation;
582
+ const a = args(m);
583
+ if (m.name.simpleName === 'captureAWSClient' && a.length === 1) return kindOfValue(a[0], bindings);
584
+ }
585
+ return undefined;
586
+ }
587
+
588
+ /** Variables and `this` properties holding v2 clients, by name. */
589
+ function collectClients(cu: JS.CompilationUnit, bindings: AwsBindings): Map<string, ClientKind> {
590
+ const clients = new Map<string, ClientKind>();
591
+ // A client handed on from a variable known to hold one, as in `this.client = client`.
592
+ const valueKind = (e: J | undefined, b: AwsBindings) => kindOfValue(e, b) ?? (e && isIdentifier(e) ? clients.get(e.simpleName) : undefined);
593
+ walk(cu, node => {
594
+ if (node.kind === J.Kind.VariableDeclarations) {
595
+ const decl = node as J.VariableDeclarations;
596
+ const typed = clientKind((decl.typeExpression as JS.TypeInfo | undefined)?.kind === JS.Kind.TypeInfo
597
+ ? (decl.typeExpression as JS.TypeInfo).typeIdentifier as J : decl.typeExpression as J | undefined, bindings);
598
+ for (const v of decl.variables) {
599
+ const name = v.element.name as J;
600
+ if (!isIdentifier(name)) continue;
601
+ const kind = typed ?? valueKind(v.element.initializer?.element, bindings);
602
+ if (kind) clients.set(name.simpleName, kind);
603
+ }
604
+ } else if (node.kind === J.Kind.Assignment) {
605
+ const a = node as J.Assignment;
606
+ const kind = valueKind(a.assignment.element, bindings);
607
+ const target = a.variable as J;
608
+ if (kind && isIdentifier(target)) clients.set(target.simpleName, kind);
609
+ if (kind && target.kind === J.Kind.FieldAccess && isThis((target as J.FieldAccess).target)) {
610
+ clients.set((target as J.FieldAccess).name.element.simpleName, kind);
611
+ }
612
+ }
613
+ return true;
614
+ });
615
+ return clients;
616
+ }
617
+
618
+ /** The `const` object literals of the file, by name, for names it declares once. */
619
+ function constantLiterals(cu: JS.CompilationUnit): Map<string, J.NewClass> {
620
+ const literals = new Map<string, J.NewClass>();
621
+ const declared = new Map<string, number>();
622
+ walk(cu, node => {
623
+ for (const decl of node.kind === J.Kind.VariableDeclarations ? [node as J.VariableDeclarations] : []) {
624
+ const constant = decl.modifiers.some(m => m.keyword === 'const');
625
+ for (const v of decl.variables) {
626
+ if (!isIdentifier(v.element.name)) continue;
627
+ const name = v.element.name.simpleName;
628
+ declared.set(name, (declared.get(name) ?? 0) + 1);
629
+ const literal = objectLiteral(v.element.initializer?.element);
630
+ if (constant && literal) literals.set(name, literal);
631
+ }
632
+ }
633
+ return true;
634
+ });
635
+ return new Map([...literals].filter(([name]) => declared.get(name) === 1));
636
+ }
637
+
638
+ /**
639
+ * Top-level exports and `module.exports`/`exports.x` assignments that hand out a client or the SDK, not looking
640
+ * into functions, which use a client rather than hand it out.
641
+ */
642
+ function clientExports(cu: JS.CompilationUnit, bindings: AwsBindings, clients: Map<string, ClientKind>): string[] {
643
+ const holdsClient = (node: J) => {
644
+ let found = false;
645
+ walk(node, n => {
646
+ if (found || isFunction(n as J)) return false;
647
+ if (isIdentifier(n) && (clients.has(n.simpleName) || bindings.byLocal.has(n.simpleName))) found = true;
648
+ if (n.kind === J.Kind.NewClass && clientKind((n as J.NewClass).class as J, bindings)) found = true;
649
+ return !found;
650
+ });
651
+ return found;
652
+ };
653
+ const exported: string[] = [];
654
+ for (const padded of cu.statements) {
655
+ const statement = padded.element;
656
+ const modifiers: J.Modifier[] = (statement as any).modifiers ?? [];
657
+ const exporting = statement.kind === JS.Kind.ExportAssignment || statement.kind === JS.Kind.ExportDeclaration ||
658
+ modifiers.some(m => m.keyword === 'export');
659
+ if (exporting && !bindings.statements.has(statement.id) && holdsClient(statement)) exported.push(statement.id);
660
+ }
661
+ walk(cu, node => {
662
+ if (node.kind === J.Kind.Assignment) {
663
+ const chain = chainOf((node as J.Assignment).variable as J);
664
+ if (chain && (chain[0] === 'exports' || (chain[0] === 'module' && chain[1] === 'exports')) &&
665
+ holdsClient((node as J.Assignment).assignment.element)) {
666
+ exported.push(node.id);
667
+ }
668
+ }
669
+ return true;
670
+ });
671
+ return exported;
672
+ }
673
+
674
+ /** Names whose every use, past their declaration, is `name.promise()`. */
675
+ function promisedOnly(cu: JS.CompilationUnit): Set<string> {
676
+ const uses = new Map<string, number>();
677
+ const promised = new Map<string, number>();
678
+ walk(cu, node => {
679
+ if (isIdentifier(node)) uses.set(node.simpleName, (uses.get(node.simpleName) ?? 0) + 1);
680
+ if (node.kind === J.Kind.MethodInvocation) {
681
+ const m = node as J.MethodInvocation;
682
+ const select = m.select?.element;
683
+ if (m.name.simpleName === 'promise' && args(m).length === 0 && select && isIdentifier(select)) {
684
+ promised.set(select.simpleName, (promised.get(select.simpleName) ?? 0) + 1);
685
+ }
686
+ }
687
+ return true;
688
+ });
689
+ return new Set([...promised].filter(([name, count]) => uses.get(name) === count + 1).map(([name]) => name));
690
+ }
691
+
692
+ function isThis(e: J): boolean {
693
+ return isIdentifier(e) && e.simpleName === 'this';
694
+ }
695
+
696
+ /** The client a call's receiver holds: a variable, a `this` property, or a client constructed in place. */
697
+ export function receiverKind(e: J | undefined, clients: Map<string, ClientKind>, bindings: AwsBindings): ClientKind | undefined {
698
+ if (!e) return undefined;
699
+ if (isIdentifier(e)) return clients.get(e.simpleName);
700
+ if (e.kind === J.Kind.FieldAccess && isThis((e as J.FieldAccess).target)) return clients.get((e as J.FieldAccess).name.element.simpleName);
701
+ if (e.kind === J.Kind.Parentheses) return receiverKind((e as J.Parentheses<J>).tree.element, clients, bindings);
702
+ if (e.kind === J.Kind.NewClass) return clientKind((e as J.NewClass).class as J, bindings);
703
+ return undefined;
704
+ }
705
+
706
+ /** Flags `.promise()` on receivers created elsewhere, and the SDK loaded other than at the top, in a file that doesn't import it there. */
707
+ class OrphanVisitor extends JavaScriptVisitor<undefined> {
708
+ constructor(private readonly analysis: Analysis) {
709
+ super();
710
+ }
711
+
712
+ protected override async visitLiteral(literal: J.Literal, p: undefined): Promise<J | undefined> {
713
+ const module = stringLiteral(literal);
714
+ if (isAwsSdkModule(module)) this.analysis.problems.push({id: literal.id, construct: module!, reason: REASONS.dynamic});
715
+ return literal;
716
+ }
717
+
718
+ private cu!: JS.CompilationUnit;
719
+
720
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: undefined): Promise<J | undefined> {
721
+ this.cu = cu;
722
+ return super.visitJsCompilationUnit(cu, p);
723
+ }
724
+
725
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: undefined): Promise<J | undefined> {
726
+ if (isPromiseCall(method)) {
727
+ const pkg = otherPackage(method.select!.element, this.cu, () => false);
728
+ if (!pkg) this.analysis.foreign = true;
729
+ this.analysis.problems.push({id: method.id, construct: '.promise()', reason: REASONS.orphanPromise, orphan: true, package: pkg});
730
+ } else if ((V2_ONLY_CALLS.has(method.name.simpleName) && method.select) || isRequestStream(method)) {
731
+ this.analysis.foreign = true;
732
+ this.analysis.problems.push({id: method.id, construct: method.name.simpleName, reason: REASONS.orphanCall(method.name.simpleName), orphan: true});
733
+ }
734
+ return super.visitMethodInvocation(method, p);
735
+ }
736
+ }
737
+
738
+ export function isPromiseCall(m: J.MethodInvocation): boolean {
739
+ return m.name.simpleName === 'promise' && args(m).length === 0 && m.select?.element.kind === J.Kind.MethodInvocation;
740
+ }
741
+
742
+ /**
743
+ * The package a bare specifier names, other than the SDK: `.promise()` on its objects (mysql2's `createPool().promise()`)
744
+ * has nothing to do with v2. A path alias (`@/lib/s3`, `src/db`) looks the same, so `AwsSdkPlan` keeps only a package
745
+ * the project declares, or a Node.js built-in.
746
+ */
747
+ function packageOf(module: string | undefined): string | undefined {
748
+ if (!module || isAwsSdkModule(module) || module.startsWith('.') || module.startsWith('/')) return undefined;
749
+ const segments = module.split('/');
750
+ return module.startsWith('@') ? segments.slice(0, 2).join('/') : segments[0];
751
+ }
752
+
753
+ /** Each local a top-level import or require binds, to its module and whether it is a variable `require` declares. */
754
+ function importedModules(cu: JS.CompilationUnit): Map<string, {module: string; required: boolean}> {
755
+ const modules = new Map<string, {module: string; required: boolean}>();
756
+ for (const padded of cu.statements) {
757
+ const stmt = padded.element;
758
+ if (stmt?.kind === JS.Kind.Import) {
759
+ const imp = stmt as JS.Import;
760
+ const module = imp.initializer ? requireOf(imp.initializer.element)?.module : importModule(imp);
761
+ if (module) namesDeclaredWithin(imp).forEach(name => modules.set(name, {module, required: false}));
762
+ continue;
763
+ }
764
+ for (const decl of declarationsOf(stmt)) {
765
+ const module = decl.variables.length === 1 ? requireOf(decl.variables[0].element.initializer?.element)?.module : undefined;
766
+ if (module) namesDeclaredWithin(decl).forEach(name => modules.set(name, {module, required: isIdentifier(decl.variables[0].element.name)}));
767
+ }
768
+ }
769
+ return modules;
770
+ }
771
+
772
+ /** The package `e` traces to through calls, members and once-declared variables, naming no SDK binding on the way. */
773
+ function otherPackage(e: J, cu: JS.CompilationUnit, sdk: (name: string) => boolean): string | undefined {
774
+ const modules = importedModules(cu);
775
+ const initializers = new Map<string, J | undefined>();
776
+ const declared = new Map<string, number>();
777
+ walk(cu, node => {
778
+ if (node.kind === J.Kind.NamedVariable) {
779
+ const v = node as J.VariableDeclarations.NamedVariable;
780
+ if (isIdentifier(v.name)) {
781
+ declared.set(v.name.simpleName, (declared.get(v.name.simpleName) ?? 0) + 1);
782
+ initializers.set(v.name.simpleName, v.initializer?.element);
783
+ }
784
+ } else if (node.kind === J.Kind.MethodDeclaration || node.kind === J.Kind.ClassDeclaration) {
785
+ // A function or class of the same name is a value that isn't traced.
786
+ const name = (node as J.MethodDeclaration).name?.simpleName;
787
+ if (name) declared.set(name, (declared.get(name) ?? 0) + 2);
788
+ }
789
+ return true;
790
+ });
791
+ const namesSdk = (node: J) => {
792
+ let found = false;
793
+ walk(node, n => {
794
+ if (isIdentifier(n) && sdk(n.simpleName)) found = true;
795
+ if (isAwsSdkModule(stringLiteral(n as J))) found = true;
796
+ return !found;
797
+ });
798
+ return found;
799
+ };
800
+ const seen = new Set<string>();
801
+ const trace = (node: J | undefined): string | undefined => {
802
+ if (!node) return undefined;
803
+ if (node.kind === J.Kind.Parentheses) return trace((node as J.Parentheses<J>).tree.element);
804
+ if (node.kind === JS.Kind.Await) return trace((node as JS.Await).expression);
805
+ if (node.kind === J.Kind.FieldAccess) return trace((node as J.FieldAccess).target);
806
+ if (node.kind === J.Kind.MethodInvocation) {
807
+ const m = node as J.MethodInvocation;
808
+ if (args(m).some(namesSdk)) return undefined;
809
+ const required = requiredModule(m);
810
+ if (required !== undefined) return packageOf(required);
811
+ return m.select ? trace(m.select.element) : trace(m.name);
812
+ }
813
+ if (!isIdentifier(node) || sdk(node.simpleName) || seen.has(node.simpleName)) return undefined;
814
+ seen.add(node.simpleName);
815
+ const imported = modules.get(node.simpleName);
816
+ if (imported) return (declared.get(node.simpleName) ?? 0) === (imported.required ? 1 : 0) ? packageOf(imported.module) : undefined;
817
+ return declared.get(node.simpleName) === 1 ? trace(initializers.get(node.simpleName)) : undefined;
818
+ };
819
+ return trace(e);
820
+ }
821
+
822
+ /** A property's name, written in full or as shorthand (`{key}`). */
823
+ function memberName(member: J): string | undefined {
824
+ return isIdentifier(member) ? member.simpleName : propertyName(member);
825
+ }
826
+
827
+ /** A property's value, written in full or as shorthand. */
828
+ function memberValue(member: J | undefined): J | undefined {
829
+ if (!member || isIdentifier(member)) return member;
830
+ const assignment = member as JS.PropertyAssignment;
831
+ return assignment.initializer ?? assignment.name.element;
832
+ }
833
+
834
+ /** The `key` of a `createPresignedPost` params literal's `Fields` literal. */
835
+ export function presignedPostKey(params: J.NewClass): J | undefined {
836
+ const literal = objectLiteral(memberValue(objectMembers(params).find(m => memberName(m) === 'Fields')));
837
+ return memberValue(literal && objectMembers(literal).find(m => memberName(m) === 'key'));
838
+ }
839
+
840
+ /** Whether the value at `cursor` is only tested for truth: a condition, negated, or in an `&&`/`||` chain that is. */
841
+ function testedForTruth(cursor: Cursor): boolean {
842
+ let child = cursor.value;
843
+ for (let c = cursor.parentTree(); c; child = c.value, c = c.parentTree()) {
844
+ const parent = c.value;
845
+ switch (parent.kind) {
846
+ case J.Kind.ControlParentheses:
847
+ return [J.Kind.If, J.Kind.WhileLoop, J.Kind.DoWhileLoop].includes(c.parentTree()?.value.kind);
848
+ case J.Kind.Unary:
849
+ return parent.operator.element === J.Unary.Type.Not;
850
+ case J.Kind.Ternary:
851
+ return parent.condition === child;
852
+ case J.Kind.Binary:
853
+ if (parent.operator.element === J.Binary.Type.And || parent.operator.element === J.Binary.Type.Or) continue;
854
+ return false;
855
+ case JS.Kind.ExpressionStatement:
856
+ return true;
857
+ default:
858
+ return false;
859
+ }
860
+ }
861
+ return false;
862
+ }
863
+
864
+ /** Whether a binding pattern takes an `AWSError` field by name. */
865
+ function destructuresErrorField(name: J): boolean {
866
+ if (name.kind !== JS.Kind.ObjectBindingPattern) return false;
867
+ return (name as JS.ObjectBindingPattern).bindings.elements.some(el => {
868
+ const b = el.element as J;
869
+ const key = isIdentifier(b) ? b : b.kind === JS.Kind.BindingElement ? ((b as JS.BindingElement).propertyName?.element ?? (b as JS.BindingElement).name) as J : undefined;
870
+ return !!key && isIdentifier(key) && (ERROR_FIELDS[key.simpleName] !== undefined || LOST_ERROR_FIELDS.has(key.simpleName));
871
+ });
872
+ }
873
+
874
+ class AnalysisVisitor extends JavaScriptVisitor<undefined> {
875
+ /** Calls whose `.promise()` the migration handles. */
876
+ private readonly promised = new Set<string>();
877
+ /** Node ids → the names holding an AWS error there: a client call's failure, or a value typed `AWSError`. */
878
+ private readonly errorScopes = new Map<string, Set<string>>();
879
+ /** Node ids → the names holding the failure of a function of this file that calls a client. */
880
+ private readonly indirectScopes = new Map<string, Set<string>>();
881
+ /** References to `AWSError` as a type, which become the v3 service exception once the file's clients are known. */
882
+ private readonly errorTypes: J[] = [];
883
+ /** The v2 clients the file names. */
884
+ private readonly usedClients = new Set<string>();
885
+ private getObject = false;
886
+ /** `Body` reads that become `transformToString()`. */
887
+ private readonly bodies = new Set<string>();
888
+ /** Each variable name's initializers, one per declaration of the name. */
889
+ private readonly initializers = new Map<string, (J | undefined)[]>();
890
+ /** Variables holding a client call's request, whose only use is `.promise()`. */
891
+ private readonly requests = new Set<string>();
892
+
893
+ constructor(private readonly analysis: Analysis, private readonly clients: Map<string, ClientKind>,
894
+ private readonly promisedOnly: Set<string> = new Set(),
895
+ private readonly constants: Map<string, J.NewClass> = new Map()) {
896
+ super();
897
+ }
898
+
899
+ private problem(node: J, construct: string, reason: string, pkg?: string): void {
900
+ this.analysis.problems.push({id: node.id, construct, reason, package: pkg});
901
+ }
902
+
903
+ private act(node: J, action: Action, ...packages: string[]): void {
904
+ this.analysis.actions.set(node.id, action);
905
+ for (const pkg of packages) this.analysis.packages.add(pkg);
906
+ }
907
+
908
+ private cu!: JS.CompilationUnit;
909
+
910
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: undefined): Promise<J | undefined> {
911
+ this.cu = cu;
912
+ walk(cu, node => {
913
+ if (node.kind === J.Kind.MethodInvocation) {
914
+ const m = node as J.MethodInvocation;
915
+ if (this.receiver(m.select?.element) === 'S3' && m.name.simpleName === 'getObject') this.getObject = true;
916
+ } else if (node.kind === J.Kind.NamedVariable) {
917
+ const v = node as J.VariableDeclarations.NamedVariable;
918
+ if (isIdentifier(v.name)) {
919
+ const inits = this.initializers.get(v.name.simpleName) ?? [];
920
+ inits.push(v.initializer?.element);
921
+ this.initializers.set(v.name.simpleName, inits);
922
+ }
923
+ }
924
+ return true;
925
+ });
926
+ this.registerIndirectScopes(cu);
927
+ const result = await super.visitJsCompilationUnit(cu, p);
928
+ if (this.errorTypes.length > 0) {
929
+ const [only] = this.usedClients;
930
+ const v3 = this.usedClients.size === 1 && !OTHER_EXCEPTION_NAMES.has(only) ? v3Client(only) : undefined;
931
+ const pkg = v3?.pkg ?? SMITHY_CLIENT;
932
+ for (const node of this.errorTypes) this.act(node, {kind: 'type', pkg, name: v3 ? `${v3.name}ServiceException` : 'ServiceException'}, pkg);
933
+ }
934
+ return result;
935
+ }
936
+
937
+ /** Whether `e` is an S3 `getObject` result: the call or its `.promise()`, awaited, or a name declared once as one. */
938
+ private isGetObjectResult(e: J | undefined, seen = new Set<string>()): boolean {
939
+ if (!e) return false;
940
+ if (e.kind === J.Kind.Parentheses) return this.isGetObjectResult((e as J.Parentheses<J>).tree.element, seen);
941
+ if (e.kind === JS.Kind.Await) return this.isGetObjectResult((e as JS.Await).expression, seen);
942
+ if (e.kind === J.Kind.MethodInvocation) {
943
+ const m = e as J.MethodInvocation;
944
+ if (isPromiseCall(m)) return this.isGetObjectResult(m.select!.element, seen);
945
+ return m.name.simpleName === 'getObject' && this.receiver(m.select?.element) === 'S3';
946
+ }
947
+ if (!isIdentifier(e) || seen.has(e.simpleName)) return false;
948
+ seen.add(e.simpleName);
949
+ const inits = this.initializers.get(e.simpleName);
950
+ return inits?.length === 1 && this.isGetObjectResult(inits[0], seen);
951
+ }
952
+
953
+ /** Whether a call of `fn` reaches a client of this file, directly or through a function that `sdk` names. */
954
+ private callsClient(fn: J, sdk: Set<string>): boolean {
955
+ let found = false;
956
+ walk(fn, n => {
957
+ if (n.kind === J.Kind.MethodInvocation) {
958
+ const m = n as J.MethodInvocation;
959
+ const select = m.select?.element;
960
+ if (this.receiver(select) || ((!select || isThis(select)) && sdk.has(m.name.simpleName))) found = true;
961
+ }
962
+ return !found;
963
+ });
964
+ return found;
965
+ }
966
+
967
+ /** `try { await load() } catch (e) {...}` and `load().catch(e => ...)`, where `load` is a function of this file calling a client. */
968
+ private registerIndirectScopes(cu: JS.CompilationUnit): void {
969
+ const functions = new Map<string, J>();
970
+ walk(cu, node => {
971
+ if (node.kind === J.Kind.MethodDeclaration) functions.set((node as J.MethodDeclaration).name.simpleName, node as J);
972
+ if (node.kind === J.Kind.NamedVariable) {
973
+ const v = node as J.VariableDeclarations.NamedVariable;
974
+ if (isIdentifier(v.name) && isFunction(v.initializer?.element)) functions.set(v.name.simpleName, v.initializer!.element);
975
+ }
976
+ return true;
977
+ });
978
+ const sdk = new Set<string>();
979
+ for (let grown = true; grown;) {
980
+ grown = false;
981
+ for (const [name, fn] of functions) {
982
+ if (!sdk.has(name) && this.callsClient(fn, sdk)) {
983
+ sdk.add(name);
984
+ grown = true;
985
+ }
986
+ }
987
+ }
988
+ if (sdk.size === 0) return;
989
+ walk(cu, node => {
990
+ if (node.kind === J.Kind.Try && this.callsClient((node as J.Try).body, sdk)) {
991
+ for (const katch of (node as J.Try).catches) this.catchScope(this.indirectScopes, katch);
992
+ } else if (node.kind === J.Kind.MethodInvocation) {
993
+ const m = node as J.MethodInvocation;
994
+ const a = args(m);
995
+ const handler = m.name.simpleName === 'catch' && a.length === 1 ? a[0] : m.name.simpleName === 'then' && a.length === 2 ? a[1] : undefined;
996
+ if (handler && m.select && this.callsClient(m.select.element, sdk)) this.functionScope(this.indirectScopes, handler, 0);
997
+ }
998
+ return true;
999
+ });
1000
+ }
1001
+
1002
+ private receiver(e: J | undefined): ClientKind | undefined {
1003
+ return receiverKind(e, this.clients, this.analysis.bindings);
1004
+ }
1005
+
1006
+ protected override async visitLiteral(literal: J.Literal, p: undefined): Promise<J | undefined> {
1007
+ const module = stringLiteral(literal);
1008
+ if (isAwsSdkModule(module) && !this.analysis.bindings.specifiers.has(literal.id)) {
1009
+ this.problem(literal, module!, REASONS.dynamic);
1010
+ }
1011
+ return literal;
1012
+ }
1013
+
1014
+ protected override async visitIdentifier(ident: J.Identifier, p: undefined): Promise<J | undefined> {
1015
+ const binding = this.analysis.bindings.byLocal.get(ident.simpleName);
1016
+ if (!binding || !this.isReference(ident) || !isModuleScoped(this.cursor, ident.simpleName)) return ident;
1017
+ this.reference(ident, binding);
1018
+ return ident;
1019
+ }
1020
+
1021
+ /** Whether the identifier at the cursor refers to a binding, rather than declaring one or naming a member. */
1022
+ private isReference(ident: J.Identifier): boolean {
1023
+ const parent = this.cursor.parentTree()?.value;
1024
+ if (!parent) return false;
1025
+ if (parent.kind === J.Kind.FieldAccess) return (parent as J.FieldAccess).target === ident;
1026
+ if (parent.kind === JS.Kind.PropertyAssignment) return (parent as JS.PropertyAssignment).name.element !== ident;
1027
+ if (parent.kind === J.Kind.NamedVariable) return (parent as J.VariableDeclarations.NamedVariable).name !== ident;
1028
+ if (parent.kind === J.Kind.MethodInvocation) return (parent as J.MethodInvocation).name !== ident;
1029
+ if (parent.kind === J.Kind.MethodDeclaration || parent.kind === J.Kind.ClassDeclaration) return false;
1030
+ if (parent.kind === JS.Kind.ImportSpecifier || parent.kind === JS.Kind.ImportClause || parent.kind === JS.Kind.Alias
1031
+ || parent.kind === JS.Kind.BindingElement || parent.kind === JS.Kind.ObjectBindingPattern) return false;
1032
+ return true;
1033
+ }
1034
+
1035
+ private reference(ident: J.Identifier, binding: AwsBinding): void {
1036
+ // The longest dotted chain the identifier starts.
1037
+ let top: Cursor = this.cursor;
1038
+ const chain = [ident.simpleName];
1039
+ for (let parent = top.parentTree(); parent?.value?.kind === J.Kind.FieldAccess && (parent.value as J.FieldAccess).target === top.value; parent = top.parentTree()) {
1040
+ chain.push((parent.value as J.FieldAccess).name.element.simpleName);
1041
+ top = parent;
1042
+ }
1043
+ const node = top.value as J;
1044
+ const parent = top.parentTree()?.value;
1045
+ const constructed = parent?.kind === J.Kind.NewClass && (parent as J.NewClass).class === node;
1046
+ const type = !constructed && inTypeContext(top);
1047
+ const written = chain.join('.');
1048
+ const rest = chain.slice(1).filter(n => n !== 'Types');
1049
+
1050
+ if (binding.kind === 'other') return;
1051
+ if (binding.kind === 'error' || (binding.kind === 'global' && rest.length === 1 && rest[0] === 'AWSError')) {
1052
+ if (type && rest.length === (binding.kind === 'error' ? 0 : 1)) this.errorType(top);
1053
+ else this.problem(node, written, REASONS.awsError);
1054
+ return;
1055
+ }
1056
+ if (binding.kind === 'type') {
1057
+ this.usedClients.add(binding.client);
1058
+ if (type && rest.length === 0) this.typeReference(node, binding.client, binding.type, written);
1059
+ else this.problem(node, written, REASONS.value(written));
1060
+ return;
1061
+ }
1062
+ let client: string | undefined;
1063
+ let members: string[];
1064
+ if (binding.kind === 'global') {
1065
+ if (rest.length === 0) {
1066
+ this.problem(node, written, REASONS.value(written));
1067
+ return;
1068
+ }
1069
+ if (!v3Client(rest[0])) {
1070
+ this.problem(node, `AWS.${rest[0]}`, memberReason(rest[0]));
1071
+ return;
1072
+ }
1073
+ client = rest[0];
1074
+ members = rest.slice(1);
1075
+ } else if (binding.kind === 'client') {
1076
+ client = binding.client;
1077
+ members = rest;
1078
+ } else {
1079
+ client = 'DynamoDB';
1080
+ members = ['DocumentClient', ...rest];
1081
+ }
1082
+ this.usedClients.add(client);
1083
+
1084
+ if (members.length === 0) {
1085
+ if (constructed) {
1086
+ this.newClient(parent as J.NewClass, client, written);
1087
+ } else if (!type) {
1088
+ this.problem(node, written, REASONS.value(written));
1089
+ return;
1090
+ }
1091
+ const v3 = v3Client(client)!;
1092
+ if (binding.kind === 'client') {
1093
+ this.analysis.rebound.add(ident.simpleName);
1094
+ this.act(node, {kind: 'keep'}, v3.pkg);
1095
+ } else {
1096
+ this.act(node, {kind: 'client', client: v3}, v3.pkg);
1097
+ }
1098
+ return;
1099
+ }
1100
+ if (client === 'DynamoDB' && members[0] === 'DocumentClient') {
1101
+ if (members.length === 1 && constructed) {
1102
+ this.newDocClient(parent as J.NewClass, written);
1103
+ } else if (members.length === 1 && type) {
1104
+ this.act(node, {kind: 'docClientType'}, LIB_DYNAMODB);
1105
+ } else if (members.length === 2 && type) {
1106
+ this.typeReference(node, DOCUMENT_CLIENT, members[1], written);
1107
+ } else {
1108
+ this.problem(node, written, REASONS.value(written));
1109
+ }
1110
+ return;
1111
+ }
1112
+ if (members.length === 1 && type) {
1113
+ this.typeReference(node, client, members[0], written);
1114
+ return;
1115
+ }
1116
+ const reason = members[0] === 'ManagedUpload' ? REASONS.managedUpload
1117
+ : members[0] === 'Converter' ? REASONS.converter : REASONS.value(written);
1118
+ this.problem(node, written, reason);
1119
+ }
1120
+
1121
+ /** `AWSError` named as a type at `cursor`; a variable or parameter declared with it holds an AWS error in its scope. */
1122
+ private errorType(cursor: Cursor): void {
1123
+ this.errorTypes.push(cursor.value as J);
1124
+ let c = cursor.parentTree();
1125
+ while (c && (c.value.kind === JS.Kind.TypeInfo || c.value.kind === JS.Kind.Union || c.value.kind === J.Kind.NullableType ||
1126
+ c.value.kind === J.Kind.ParenthesizedTypeTree)) {
1127
+ c = c.parentTree();
1128
+ }
1129
+ if (c?.value.kind !== J.Kind.VariableDeclarations) return;
1130
+ let scope = c.parentTree();
1131
+ while (scope && !isFunction(scope.value) && scope.value.kind !== J.Kind.Block && scope.value.kind !== JS.Kind.CompilationUnit) {
1132
+ scope = scope.parentTree();
1133
+ }
1134
+ for (const v of (c.value as J.VariableDeclarations).variables) {
1135
+ if (scope && isIdentifier(v.element.name)) this.addScope(this.errorScopes, scope.value.id, v.element.name.simpleName);
1136
+ }
1137
+ }
1138
+
1139
+ private typeReference(node: J, client: string, type: string, written: string): void {
1140
+ const types = typesOf(client);
1141
+ if (!types) {
1142
+ this.problem(node, written, REASONS.untypedClient(client));
1143
+ return;
1144
+ }
1145
+ const pkg = client === DOCUMENT_CLIENT ? LIB_DYNAMODB : v3Client(client)!.pkg;
1146
+ const entry = types.get(type);
1147
+ if (entry?.alias) {
1148
+ const names = [...entry.alias.matchAll(/[A-Za-z_]\w*/g)].map(m => m[0]).filter(n => !NATIVE_TYPES.has(n));
1149
+ if (client === DOCUMENT_CLIENT && names.some(n => n !== 'NativeAttributeValue')) {
1150
+ this.problem(node, written, REASONS.docClientType);
1151
+ return;
1152
+ }
1153
+ this.act(node, {kind: 'typeExpr', pkg, text: entry.alias, names: [...new Set(names)]}, ...(names.length > 0 ? [pkg] : []));
1154
+ } else {
1155
+ if (client === DOCUMENT_CLIENT && !entry) {
1156
+ this.problem(node, written, REASONS.docClientType);
1157
+ return;
1158
+ }
1159
+ this.act(node, {kind: 'type', pkg, name: entry?.named ?? type}, pkg);
1160
+ }
1161
+ }
1162
+
1163
+ private newClient(n: J.NewClass, client: string, written: string): void {
1164
+ const a = args(n);
1165
+ if (a.length > 1) {
1166
+ this.problem(n, written, REASONS.configNotLiteral);
1167
+ return;
1168
+ }
1169
+ if (a.length === 1) {
1170
+ const literal = objectLiteral(a[0]);
1171
+ const named = isIdentifier(a[0]) ? this.constants.get(a[0].simpleName) : undefined;
1172
+ // Options named by a constant pass through as they are, which is right only when no key changes.
1173
+ const unchanged = named && !configProblem(named) && objectMembers(named).every(m => configEdit(propertyName(m)!).kind === 'keep');
1174
+ const problem = unchanged ? undefined : literal ? configProblem(literal) : {construct: 'client options', reason: REASONS.configNotLiteral};
1175
+ if (problem) {
1176
+ this.problem(a[0], problem.construct, problem.reason);
1177
+ return;
1178
+ }
1179
+ }
1180
+ this.act(n, {kind: 'newClient'}, v3Client(client)!.pkg);
1181
+ }
1182
+
1183
+ private newDocClient(n: J.NewClass, written: string): void {
1184
+ const a = args(n);
1185
+ if (a.length > 1) {
1186
+ this.problem(n, written, REASONS.documentClientOptions);
1187
+ return;
1188
+ }
1189
+ if (a.length === 1) {
1190
+ const literal = objectLiteral(a[0]);
1191
+ if (!literal) {
1192
+ this.problem(a[0], 'DocumentClient options', REASONS.documentClientOptions);
1193
+ return;
1194
+ }
1195
+ const options = objectMembers(literal);
1196
+ const service = options.find(m => propertyName(m) === 'service') as JS.PropertyAssignment | undefined;
1197
+ const rest = options.filter(m => !['service', 'convertEmptyValues', 'wrapNumbers'].includes(propertyName(m) ?? ''));
1198
+ if (service) {
1199
+ const value = service.initializer;
1200
+ const dynamoDb = receiverKind(value, this.clients, this.analysis.bindings) === 'DynamoDB' || kindOfValue(value, this.analysis.bindings) === 'DynamoDB';
1201
+ if (rest.length > 0 || !dynamoDb) {
1202
+ this.problem(service, 'DocumentClient service', REASONS.documentClientOptions);
1203
+ return;
1204
+ }
1205
+ } else {
1206
+ const problem = configProblem({...literal, body: {...literal.body!, statements: literal.body!.statements.filter(s => rest.includes(s.element))}} as J.NewClass);
1207
+ if (problem) {
1208
+ this.problem(a[0], problem.construct, problem.reason);
1209
+ return;
1210
+ }
1211
+ }
1212
+ }
1213
+ this.act(n, {kind: 'newDocClient'}, LIB_DYNAMODB, v3Client('DynamoDB')!.pkg);
1214
+ }
1215
+
1216
+ protected override async visitFieldAccess(fa: J.FieldAccess, p: undefined): Promise<J | undefined> {
1217
+ const name = fa.name.element.simpleName;
1218
+ if (name === '$response') this.problem(fa, '$response', REASONS.response);
1219
+ if (name === 'Body' && this.getObject && !this.bodies.has(fa.id)) this.problem(fa, 'getObject Body', REASONS.body);
1220
+ const error = this.errorKind(fa.target);
1221
+ if (error && (ERROR_FIELDS[name] !== undefined || LOST_ERROR_FIELDS.has(name))) this.errorField(fa, name, error);
1222
+ if (this.receiver(fa.target)) this.problem(fa, `client.${name}`, REASONS.clientProperty);
1223
+ return super.visitFieldAccess(fa, p);
1224
+ }
1225
+
1226
+ private reaches(scopes: Map<string, Set<string>>, name: string): boolean {
1227
+ for (let c = this.cursor.parentTree(); c; c = c.parentTree()) {
1228
+ if (scopes.get(c.value?.id)?.has(name)) return true;
1229
+ }
1230
+ return false;
1231
+ }
1232
+
1233
+ private addScope(scopes: Map<string, Set<string>>, id: string, name: string): void {
1234
+ scopes.set(id, new Set([...scopes.get(id) ?? [], name]));
1235
+ }
1236
+
1237
+ /** Whether `e` holds an AWS error: a client call's failure, a value typed or cast as `AWSError`, or maybe one. */
1238
+ private errorKind(e: J | undefined): 'known' | 'indirect' | undefined {
1239
+ if (!e) return undefined;
1240
+ if (isIdentifier(e)) {
1241
+ return this.reaches(this.errorScopes, e.simpleName) ? 'known' : this.reaches(this.indirectScopes, e.simpleName) ? 'indirect' : undefined;
1242
+ }
1243
+ if (e.kind !== J.Kind.Parentheses) return undefined;
1244
+ const inner = (e as J.Parentheses<J>).tree.element;
1245
+ const type = inner.kind === JS.Kind.As ? (inner as JS.As).right
1246
+ : inner.kind === J.Kind.TypeCast ? (inner as J.TypeCast).class.tree.element : undefined;
1247
+ return type && this.isAwsErrorType(type) ? 'known' : undefined;
1248
+ }
1249
+
1250
+ private isAwsErrorType(e: J): boolean {
1251
+ const chain = chainOf(e.kind === JS.Kind.TypeInfo ? (e as JS.TypeInfo).typeIdentifier as J : e);
1252
+ const binding = chain && this.analysis.bindings.byLocal.get(chain[0]);
1253
+ return binding?.kind === 'error' && chain!.length === 1 || binding?.kind === 'global' && chain!.length === 2 && chain![1] === 'AWSError';
1254
+ }
1255
+
1256
+ private errorField(fa: J.FieldAccess, name: string, error: 'known' | 'indirect'): void {
1257
+ const parent = this.cursor.parentTree()?.value;
1258
+ if (error === 'indirect') {
1259
+ this.problem(fa, `error.${name}`, REASONS.indirectError);
1260
+ } else if (LOST_ERROR_FIELDS.has(name)) {
1261
+ this.problem(fa, `error.${name}`, REASONS.lostErrorField(name));
1262
+ } else if ((parent?.kind === J.Kind.Assignment || parent?.kind === J.Kind.AssignmentOperation) && parent.variable === fa) {
1263
+ this.problem(fa, `error.${name}`, REASONS.errorFieldForm);
1264
+ } else if (name === 'retryable' && !testedForTruth(this.cursor)) {
1265
+ this.problem(fa, 'error.retryable', REASONS.retryable);
1266
+ } else {
1267
+ this.act(fa, {kind: 'errorField', to: ERROR_FIELDS[name]});
1268
+ }
1269
+ }
1270
+
1271
+ /** `err['statusCode']`, which can't keep its meaning by a rename. */
1272
+ protected override async visitArrayAccess(access: J.ArrayAccess, p: undefined): Promise<J | undefined> {
1273
+ const field = stringLiteral(access.dimension.index.element);
1274
+ if (field && (ERROR_FIELDS[field] !== undefined || LOST_ERROR_FIELDS.has(field)) && this.errorKind(access.indexed)) {
1275
+ this.problem(access, `error['${field}']`, REASONS.errorFieldForm);
1276
+ }
1277
+ return super.visitArrayAccess(access, p);
1278
+ }
1279
+
1280
+ /** `const {statusCode} = err`. */
1281
+ protected override async visitVariable(variable: J.VariableDeclarations.NamedVariable, p: undefined): Promise<J | undefined> {
1282
+ if (destructuresErrorField(variable.name as J) && this.errorKind(variable.initializer?.element)) {
1283
+ this.problem(variable, 'error fields', REASONS.errorFieldForm);
1284
+ }
1285
+ return super.visitVariable(variable, p);
1286
+ }
1287
+
1288
+ protected override async visitMethodInvocation(m: J.MethodInvocation, p: undefined): Promise<J | undefined> {
1289
+ const select = m.select?.element;
1290
+ // `data.Body.toString(encoding)` reads the v2 Buffer; the v3 stream reads the same text with `transformToString`.
1291
+ if (this.getObject && m.name.simpleName === 'toString' && args(m).length <= 1 && select?.kind === J.Kind.FieldAccess &&
1292
+ (select as J.FieldAccess).name.element.simpleName === 'Body' && this.isGetObjectResult((select as J.FieldAccess).target) &&
1293
+ awaitAllowed(this.cursor)) {
1294
+ const parent = this.cursor.parentTree()?.value;
1295
+ this.bodies.add(select.id);
1296
+ this.act(m, {kind: 'bodyToString', parenthesized: parent?.kind === J.Kind.MethodInvocation || parent?.kind === J.Kind.FieldAccess});
1297
+ }
1298
+ if (m.name.simpleName === 'promise' && args(m).length === 0 && select && isIdentifier(select) && this.requests.has(select.simpleName)) {
1299
+ this.act(m, {kind: 'unwrapPromise'});
1300
+ this.registerPromiseErrorScopes();
1301
+ } else if (isPromiseCall(m)) {
1302
+ const call = m.select!.element as J.MethodInvocation;
1303
+ const kind = this.receiver(call.select?.element);
1304
+ if (!kind) {
1305
+ const pkg = otherPackage(call, this.cu, name => this.analysis.bindings.byLocal.has(name) || this.clients.has(name));
1306
+ if (!pkg) this.analysis.foreign = true;
1307
+ this.problem(m, '.promise()', REASONS.unknownReceiver, pkg);
1308
+ } else if (call.name.simpleName === 'upload' && kind === 'S3') {
1309
+ this.promised.add(call.id);
1310
+ this.upload(m, call);
1311
+ } else if (call.name.simpleName === 'waitFor') {
1312
+ this.promised.add(call.id);
1313
+ this.problem(call, 'waitFor', REASONS.waiter);
1314
+ } else {
1315
+ this.promised.add(call.id);
1316
+ this.act(m, {kind: 'unwrapPromise'});
1317
+ this.registerPromiseErrorScopes();
1318
+ }
1319
+ } else {
1320
+ const kind = this.receiver(m.select?.element);
1321
+ if (kind) this.clientCall(m, kind);
1322
+ else if ((m.select && V2_ONLY_CALLS.has(m.name.simpleName)) ||
1323
+ (isRequestStream(m) && !this.receiver((m.select!.element as J.MethodInvocation).select?.element))) {
1324
+ this.analysis.foreign = true;
1325
+ }
1326
+ }
1327
+ return super.visitMethodInvocation(m, p);
1328
+ }
1329
+
1330
+ private clientCall(m: J.MethodInvocation, kind: ClientKind): void {
1331
+ const name = m.name.simpleName;
1332
+ const a = args(m);
1333
+ const callback = a.length > 0 && isFunction(a[a.length - 1]) ? a[a.length - 1] : undefined;
1334
+ this.registerTryScope();
1335
+ if (callback) this.functionScope(this.errorScopes, callback, 0);
1336
+ if (kind === 'S3' && (name === 'getSignedUrl' || name === 'getSignedUrlPromise')) {
1337
+ this.signedUrl(m, name === 'getSignedUrl');
1338
+ return;
1339
+ }
1340
+ if (kind === 'S3' && name === 'createPresignedPost') {
1341
+ this.presignedPost(m);
1342
+ return;
1343
+ }
1344
+ if (this.promised.has(m.id)) return;
1345
+ if (kind === 'S3' && name === 'upload') {
1346
+ this.problem(m, 'upload', REASONS.upload);
1347
+ return;
1348
+ }
1349
+ if (name === 'waitFor') {
1350
+ this.problem(m, name, REASONS.waiter);
1351
+ return;
1352
+ }
1353
+ if (kind === DOCUMENT_CLIENT && name === 'createSet' && a.length === 1) {
1354
+ this.act(m, {kind: 'createSet'});
1355
+ return;
1356
+ }
1357
+ if (!callback) {
1358
+ const variable = this.cursor.parentTree()?.value;
1359
+ const held = variable?.kind === J.Kind.VariableDeclarations ? undefined : variable;
1360
+ if (held?.kind === J.Kind.NamedVariable && isIdentifier(held.name) && held.initializer?.element === m &&
1361
+ this.promisedOnly.has(held.name.simpleName)) {
1362
+ this.requests.add(held.name.simpleName);
1363
+ } else {
1364
+ this.problem(m, `${name}(...)`, REASONS.request);
1365
+ }
1366
+ return;
1367
+ }
1368
+ if (a.length === 1) this.act(m, {kind: 'emptyArgs'});
1369
+ }
1370
+
1371
+ private upload(promise: J.MethodInvocation, call: J.MethodInvocation): void {
1372
+ const a = args(call);
1373
+ const receiver = call.select!.element;
1374
+ const plainReceiver = isIdentifier(receiver) || receiver.kind === J.Kind.FieldAccess;
1375
+ const literal = a.length === 2 ? objectLiteral(a[1]) : undefined;
1376
+ const options = a.length === 2 && (isIdentifier(a[1]) ||
1377
+ (!!literal && objectMembers(literal).every(member => member.kind === JS.Kind.PropertyAssignment && !!propertyName(member))));
1378
+ if (a.length < 1 || a.length > 2 || (a.length === 2 && !options) || !plainReceiver) {
1379
+ this.problem(call, 'upload', REASONS.upload);
1380
+ return;
1381
+ }
1382
+ this.registerTryScope();
1383
+ this.act(promise, {kind: 'upload'}, LIB_STORAGE);
1384
+ }
1385
+
1386
+ private signedUrl(m: J.MethodInvocation, sync: boolean): void {
1387
+ const a = args(m);
1388
+ const operation = stringLiteral(a[0]);
1389
+ const params = a.length === 2 ? objectLiteral(a[1]) : undefined;
1390
+ const parent = this.cursor.parentTree()?.value;
1391
+ const awaitable = !sync || (awaitAllowed(this.cursor) && !(parent?.kind === J.Kind.MethodInvocation || parent?.kind === J.Kind.FieldAccess));
1392
+ if (!operation || !params || !awaitable || !/^[a-z]\w*$/.test(operation)) {
1393
+ this.problem(m, m.name.simpleName, REASONS.signedUrl);
1394
+ return;
1395
+ }
1396
+ const command = `${operation.charAt(0).toUpperCase()}${operation.substring(1)}Command`;
1397
+ this.act(m, {kind: 'presign', command, awaited: sync}, S3_PRESIGNER, v3Client('S3')!.pkg);
1398
+ }
1399
+
1400
+ /** `s3.createPresignedPost(params)` → `await createPresignedPost(s3, {...params, Key})`, with v2's `Fields.key` as `Key`. */
1401
+ private presignedPost(m: J.MethodInvocation): void {
1402
+ const a = args(m);
1403
+ const literal = a.length === 1 ? objectLiteral(a[0]) ?? (isIdentifier(a[0]) ? this.constants.get(a[0].simpleName) : undefined) : undefined;
1404
+ const parent = this.cursor.parentTree()?.value;
1405
+ if (!literal || !awaitAllowed(this.cursor) || parent?.kind === J.Kind.MethodInvocation || parent?.kind === J.Kind.FieldAccess) {
1406
+ this.problem(m, 'createPresignedPost', REASONS.presignedPost);
1407
+ return;
1408
+ }
1409
+ const names = objectMembers(literal).map(memberName);
1410
+ if (names.some(n => n === undefined || !PRESIGNED_POST_KEYS.has(n))) {
1411
+ this.problem(a[0], 'createPresignedPost params', REASONS.presignedPostKey);
1412
+ return;
1413
+ }
1414
+ const key = presignedPostKey(literal);
1415
+ // Params written in place get `Key` beside `Fields`, which evaluates the key a second time.
1416
+ if (!key || (objectLiteral(a[0]) && key.kind !== J.Kind.Literal && !chainOf(key))) {
1417
+ this.problem(m, 'createPresignedPost', REASONS.presignedPost);
1418
+ return;
1419
+ }
1420
+ this.act(m, {kind: 'presignedPost'}, S3_PRESIGNED_POST);
1421
+ }
1422
+
1423
+ /** `try { await client.op(...).promise() } catch (e) {...}`: `e` is the call's error. */
1424
+ private registerTryScope(): void {
1425
+ let child: any = this.cursor.value;
1426
+ for (let c = this.cursor.parentTree(); c; c = c.parentTree()) {
1427
+ const v = c.value;
1428
+ if (isFunction(v)) return;
1429
+ if (v?.kind === J.Kind.Try && (v as J.Try).body === child) {
1430
+ for (const katch of (v as J.Try).catches) this.catchScope(this.errorScopes, katch);
1431
+ return;
1432
+ }
1433
+ child = v;
1434
+ }
1435
+ }
1436
+
1437
+ /** `.catch(e => ...)` and `.then(ok, e => ...)` after the `.promise()` at the cursor. */
1438
+ private registerPromiseErrorScopes(): void {
1439
+ this.registerTryScope();
1440
+ let child: any = this.cursor.value;
1441
+ for (let c = this.cursor.parentTree(); c?.value?.kind === J.Kind.MethodInvocation; c = c.parentTree()) {
1442
+ const m = c.value as J.MethodInvocation;
1443
+ if (m.select?.element !== child) return;
1444
+ const a = args(m);
1445
+ if (m.name.simpleName === 'catch' && a.length === 1) this.functionScope(this.errorScopes, a[0], 0);
1446
+ if (m.name.simpleName === 'then' && a.length === 2) this.functionScope(this.errorScopes, a[1], 0);
1447
+ child = m;
1448
+ }
1449
+ }
1450
+
1451
+ /** `catch (e)` holds the error in its body; `catch ({code})` reads its fields where no rename reaches. */
1452
+ private catchScope(scopes: Map<string, Set<string>>, katch: J.Try.Catch): void {
1453
+ const param = katch.parameter.tree.element as J.VariableDeclarations;
1454
+ const name = param?.variables?.[0]?.element.name as J;
1455
+ if (name && isIdentifier(name)) this.addScope(scopes, katch.body.id, name.simpleName);
1456
+ else if (name && destructuresErrorField(name)) this.destructuredError(scopes, name);
1457
+ }
1458
+
1459
+ private destructuredError(scopes: Map<string, Set<string>>, name: J): void {
1460
+ this.problem(name, 'error fields', scopes === this.indirectScopes ? REASONS.indirectError : REASONS.errorFieldForm);
1461
+ }
1462
+
1463
+ private functionScope(scopes: Map<string, Set<string>>, expression: J, index: number): void {
1464
+ const fn = unwrapFunction(expression)!;
1465
+ let params: J[] = [];
1466
+ if (fn.kind === JS.Kind.ArrowFunction) {
1467
+ params = (fn as JS.ArrowFunction).lambda.parameters.parameters.map(p => p.element);
1468
+ } else if (fn.kind === J.Kind.MethodDeclaration) {
1469
+ params = (fn as J.MethodDeclaration).parameters.elements.map(p => p.element);
1470
+ } else if (fn.kind === J.Kind.Lambda) {
1471
+ params = (fn as J.Lambda).parameters.parameters.map(p => p.element);
1472
+ }
1473
+ const param = params[index];
1474
+ const name = param?.kind === J.Kind.VariableDeclarations ? (param as J.VariableDeclarations).variables[0]?.element.name as J
1475
+ : param;
1476
+ if (name && isIdentifier(name)) this.addScope(scopes, fn.id, name.simpleName);
1477
+ else if (name && destructuresErrorField(name)) this.destructuredError(scopes, name);
1478
+ }
1479
+ }
1480
+