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