@aligent/aws-wrappers 0.5.9 → 0.5.11

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 (71) hide show
  1. package/README.md +78 -10
  2. package/cjs/index.cjs +427 -133
  3. package/cjs/package.json +3 -2
  4. package/cjs/src/dynamodb/dynamodb.d.ts +23 -4
  5. package/cjs/src/dynamodb/dynamodb.d.ts.map +1 -1
  6. package/cjs/src/eventbridge/eventbridge.d.ts.map +1 -1
  7. package/cjs/src/index.d.ts +1 -0
  8. package/cjs/src/index.d.ts.map +1 -1
  9. package/cjs/src/s3/s3.d.ts +6 -1
  10. package/cjs/src/s3/s3.d.ts.map +1 -1
  11. package/cjs/src/secrets-manager/secrets-manager.d.ts +3 -1
  12. package/cjs/src/secrets-manager/secrets-manager.d.ts.map +1 -1
  13. package/cjs/src/ses/ses.d.ts +64 -0
  14. package/cjs/src/ses/ses.d.ts.map +1 -0
  15. package/cjs/src/sns/sns.d.ts +8 -5
  16. package/cjs/src/sns/sns.d.ts.map +1 -1
  17. package/cjs/src/sqs/sqs.d.ts +7 -3
  18. package/cjs/src/sqs/sqs.d.ts.map +1 -1
  19. package/cjs/src/ssm/ssm.d.ts +3 -1
  20. package/cjs/src/ssm/ssm.d.ts.map +1 -1
  21. package/cjs/src/util/batch-operation-error.d.ts +19 -2
  22. package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
  23. package/cjs/src/util/chunk.d.ts +8 -0
  24. package/cjs/src/util/chunk.d.ts.map +1 -1
  25. package/cjs/src/util/json.d.ts +14 -0
  26. package/cjs/src/util/json.d.ts.map +1 -0
  27. package/docs/index/classes/APIGatewayService.md +6 -6
  28. package/docs/index/classes/APIGatewayV2Service.md +5 -5
  29. package/docs/index/classes/BatchOperationError.md +15 -6
  30. package/docs/index/classes/DynamoDBService.md +39 -16
  31. package/docs/index/classes/EventBridgeService.md +3 -3
  32. package/docs/index/classes/LambdaFunctionError.md +7 -7
  33. package/docs/index/classes/LambdaService.md +3 -3
  34. package/docs/index/classes/S3Service.md +24 -16
  35. package/docs/index/classes/SESService.md +123 -0
  36. package/docs/index/classes/SNSService.md +12 -9
  37. package/docs/index/classes/SQSService.md +14 -10
  38. package/docs/index/classes/SSMService.md +10 -8
  39. package/docs/index/classes/SchedulerService.md +11 -11
  40. package/docs/index/classes/SecretsManagerService.md +11 -9
  41. package/docs/index/classes/StepFunctionsService.md +6 -6
  42. package/docs/index/interfaces/BatchFailedEntry.md +6 -5
  43. package/docs/index/interfaces/EmptyBucketPageResult.md +2 -2
  44. package/docs/index/modules.md +1 -0
  45. package/docs/testing/testing/functions/createMockService.md +1 -1
  46. package/esm/index.mjs +428 -135
  47. package/esm/package.json +3 -2
  48. package/esm/src/dynamodb/dynamodb.d.ts +23 -4
  49. package/esm/src/dynamodb/dynamodb.d.ts.map +1 -1
  50. package/esm/src/eventbridge/eventbridge.d.ts.map +1 -1
  51. package/esm/src/index.d.ts +1 -0
  52. package/esm/src/index.d.ts.map +1 -1
  53. package/esm/src/s3/s3.d.ts +6 -1
  54. package/esm/src/s3/s3.d.ts.map +1 -1
  55. package/esm/src/secrets-manager/secrets-manager.d.ts +3 -1
  56. package/esm/src/secrets-manager/secrets-manager.d.ts.map +1 -1
  57. package/esm/src/ses/ses.d.ts +64 -0
  58. package/esm/src/ses/ses.d.ts.map +1 -0
  59. package/esm/src/sns/sns.d.ts +8 -5
  60. package/esm/src/sns/sns.d.ts.map +1 -1
  61. package/esm/src/sqs/sqs.d.ts +7 -3
  62. package/esm/src/sqs/sqs.d.ts.map +1 -1
  63. package/esm/src/ssm/ssm.d.ts +3 -1
  64. package/esm/src/ssm/ssm.d.ts.map +1 -1
  65. package/esm/src/util/batch-operation-error.d.ts +19 -2
  66. package/esm/src/util/batch-operation-error.d.ts.map +1 -1
  67. package/esm/src/util/chunk.d.ts +8 -0
  68. package/esm/src/util/chunk.d.ts.map +1 -1
  69. package/esm/src/util/json.d.ts +14 -0
  70. package/esm/src/util/json.d.ts.map +1 -0
  71. package/package.json +3 -2
package/esm/index.mjs CHANGED
@@ -3,13 +3,14 @@ import { ApiGatewayV2Client, GetRouteCommand, GetApisCommand, GetRoutesCommand }
3
3
  import xray from 'aws-xray-sdk-core';
4
4
  import { APIGatewayClient, paginateGetRestApis, paginateGetApiKeys, GetApiKeyCommand, paginateGetResources } from '@aws-sdk/client-api-gateway';
5
5
  import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
6
- import { DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, DeleteCommand, QueryCommand, ScanCommand, BatchGetCommand, BatchWriteCommand, paginateQuery, paginateScan } from '@aws-sdk/lib-dynamodb';
6
+ import { DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, DeleteCommand, QueryCommand, ScanCommand, paginateQuery, paginateScan, BatchGetCommand, BatchWriteCommand } from '@aws-sdk/lib-dynamodb';
7
7
  import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';
8
8
  import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
9
9
  import { S3Client, PutObjectCommand, GetObjectCommand, HeadObjectCommand, CopyObjectCommand, paginateListObjectsV2, DeleteObjectCommand, DeleteObjectsCommand } from '@aws-sdk/client-s3';
10
10
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
11
11
  import { SchedulerClient, CreateScheduleCommand, GetScheduleCommand, UpdateScheduleCommand, DeleteScheduleCommand, paginateListSchedules, CreateScheduleGroupCommand, GetScheduleGroupCommand, DeleteScheduleGroupCommand, paginateListScheduleGroups } from '@aws-sdk/client-scheduler';
12
12
  import { SecretsManagerClient, CreateSecretCommand, UpdateSecretCommand, PutSecretValueCommand, DeleteSecretCommand, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
13
+ import { SESv2Client, SendEmailCommand, SendBulkEmailCommand } from '@aws-sdk/client-sesv2';
13
14
  import { SFNClient, paginateListExecutions, StartExecutionCommand, DescribeExecutionCommand, StopExecutionCommand } from '@aws-sdk/client-sfn';
14
15
  import { SNSClient, PublishCommand, PublishBatchCommand } from '@aws-sdk/client-sns';
15
16
  import { SQSClient, SendMessageCommand, ReceiveMessageCommand, DeleteMessageCommand, SendMessageBatchCommand, DeleteMessageBatchCommand } from '@aws-sdk/client-sqs';
@@ -143,6 +144,110 @@ class APIGatewayService {
143
144
  }
144
145
  }
145
146
 
147
+ /**
148
+ * Thrown by the batch methods once every chunk has been sent and at least one
149
+ * entry was rejected.
150
+ *
151
+ * `results` holds the raw SDK output of every chunk, so the outputs of the
152
+ * entries that succeeded (message ids, sequence numbers) stay readable. The
153
+ * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
154
+ * `SSM.getParameters`, whose `results` are empty, and the DynamoDB batch
155
+ * methods, whose `results` hold a single output (the last response, with the
156
+ * `Responses` merged so far for `batchGet`) carrying what is still pending.
157
+ * `failed` is the normalised list of rejected entries across all chunks.
158
+ *
159
+ * Do not pass the error object itself to a logger. `results` is an enumerable
160
+ * property and the Powertools logger serialises every enumerable property of
161
+ * an error, so `logger.error('…', error)` writes `results` to the log — which
162
+ * for the DynamoDB batch methods holds the caller's keys and items. Log `name`,
163
+ * `message` and `failed`, which never carry a payload, and read `results` only
164
+ * to retry or recover.
165
+ *
166
+ * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
167
+ * this package may be loaded in one process.
168
+ */
169
+ class BatchOperationError extends Error {
170
+ results;
171
+ failed;
172
+ name = 'BatchOperationError';
173
+ constructor(results, failed) {
174
+ super(failureMessage(failed));
175
+ this.results = results;
176
+ this.failed = failed;
177
+ }
178
+ }
179
+ function failureMessage(failed) {
180
+ const noun = failed.length === 1 ? 'entry' : 'entries';
181
+ const codes = distinctCodes(failed);
182
+ const suffix = codes.length === 0 ? '' : ` (${codes.join(', ')})`;
183
+ return `Batch operation failed for ${failed.length} ${noun}${suffix}`;
184
+ }
185
+ /**
186
+ * SQS and SNS report rejected entries under `Failed` on an otherwise
187
+ * successful response, so a resolved chunk does not mean every entry was
188
+ * accepted. Extracts those entries and delegates to {@link throwIfAny}.
189
+ *
190
+ * Only id, code and message are copied out — never the entry itself — so
191
+ * neither the error nor the warning can leak a payload.
192
+ */
193
+ function throwIfAnyFailed(logger, operation, results) {
194
+ const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
195
+ id: Id,
196
+ code: Code,
197
+ message: Message,
198
+ })));
199
+ return throwIfAny(logger, operation, results, failed);
200
+ }
201
+ /**
202
+ * S3 reports undeleted keys under `Errors` on an otherwise successful
203
+ * `DeleteObjects` response. Same contract as {@link throwIfAnyFailed}; the
204
+ * key is carried as the failed entry's `id`, and `VersionId` is dropped.
205
+ */
206
+ function throwIfAnyDeleteErrors(logger, operation, results) {
207
+ const failed = results.flatMap(result => (result.Errors ?? []).map(({ Key, Code, Message }) => ({
208
+ id: Key,
209
+ code: Code,
210
+ message: Message,
211
+ })));
212
+ return throwIfAny(logger, operation, results, failed);
213
+ }
214
+ /**
215
+ * Warn-and-throw step for services whose responses don't use the SQS/SNS
216
+ * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
217
+ * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
218
+ * Returns `results` untouched when `failed` is empty.
219
+ *
220
+ * Callers must build `failed` by copying id, code and message explicitly —
221
+ * never by spreading the SDK entry — because it goes straight into the error
222
+ * and the warning.
223
+ */
224
+ function throwIfAny(logger, operation, results, failed) {
225
+ if (failed.length === 0)
226
+ return results;
227
+ return throwBatchFailure(logger, operation, results, failed);
228
+ }
229
+ /**
230
+ * The warn-and-throw half of {@link throwIfAny}, for callers that already know
231
+ * `failed` is non-empty and need the compiler to see that the call never
232
+ * returns. The same rule applies: build `failed` by copying id, code and
233
+ * message explicitly.
234
+ */
235
+ function throwBatchFailure(logger, operation, results, failed) {
236
+ logger.warn(`${operation} had rejected entries`, {
237
+ failedCount: failed.length,
238
+ codes: distinctCodes(failed),
239
+ });
240
+ throw new BatchOperationError(results, failed);
241
+ }
242
+ /**
243
+ * Distinct error codes in first-seen order, for the error message and the
244
+ * warning log line.
245
+ */
246
+ function distinctCodes(failed) {
247
+ const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
248
+ return [...new Set(codes)];
249
+ }
250
+
146
251
  /**
147
252
  * Whether the logger is verbose enough that full SDK inputs may be written to
148
253
  * the log. The unlock rule is documented on {@link redactInput}.
@@ -178,6 +283,29 @@ const BATCH_GET_BASE_DELAY_MS = 200;
178
283
  function summariseTables(input) {
179
284
  return { tables: Object.keys(input.RequestItems ?? {}) };
180
285
  }
286
+ /**
287
+ * The tables that still have unprocessed keys or writes. Tables whose list is
288
+ * empty are dropped, so an empty result means there is nothing left to retry.
289
+ */
290
+ function pendingCounts(unprocessed, countOf) {
291
+ return Object.entries(unprocessed)
292
+ .map(([table, entry]) => ({ table, count: countOf(entry) ?? 0 }))
293
+ .filter(({ count }) => count > 0);
294
+ }
295
+ /**
296
+ * One failed entry per request still unprocessed after the final attempt. The
297
+ * `id` is the table name plus the position within that table's unprocessed
298
+ * list — deliberately not the key or item, which is caller data and must not
299
+ * reach the error message or the warning. The position indexes into the
300
+ * `UnprocessedKeys` / `UnprocessedItems` the error carries in `results`.
301
+ */
302
+ function unprocessedEntries(pending, code, attempts) {
303
+ return pending.flatMap(({ table, count }) => Array.from({ length: count }, (_, index) => ({
304
+ id: `${table}[${index}]`,
305
+ code,
306
+ message: `Still unprocessed after ${attempts} attempts`,
307
+ })));
308
+ }
181
309
  /**
182
310
  * Fields safe to log at INFO. Omits `Key` (may carry customer IDs / tenant IDs).
183
311
  */
@@ -394,63 +522,101 @@ class DynamoDBService {
394
522
  /**
395
523
  * Batch-get items from one or more DynamoDB tables, retrying
396
524
  * `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
397
- * (200ms base delay). Throws when keys remain unprocessed after the final
398
- * attempt. `Responses` are merged across attempts, keyed by table name.
525
+ * (200ms base delay). `Responses` are merged across attempts, keyed by
526
+ * table name.
399
527
  *
400
528
  * Note: this method is intentionally **not** generic. `BatchGet`'s
401
529
  * `Responses` field is a multi-table `Record<string, item[]>` whose item
402
530
  * shapes can differ per table — no single `T` can soundly describe it.
403
531
  * Callers should narrow the result type at the call site.
532
+ *
533
+ * @throws {@link BatchOperationError} when keys remain unprocessed after
534
+ * the final attempt. `results` holds one output: the merged `Responses`
535
+ * retrieved so far, plus the still-pending `UnprocessedKeys` to retry.
536
+ * `failed` has one entry per pending key with `code: 'UnprocessedKeys'`
537
+ * and an `id` of `<table>[<index>]`, the key's position in
538
+ * `results[0].UnprocessedKeys[<table>].Keys`. The `failed` list never
539
+ * carries key values; `results` does, as it is data the caller requested,
540
+ * so don't log the error object itself (see {@link BatchOperationError}).
541
+ * Request-level SDK exceptions propagate unchanged.
404
542
  */
405
543
  async batchGet(input) {
406
544
  this.logger.info('Batch getting DynamoDB items', {
407
545
  input: redactInput(this.logger, input, summariseTables),
408
546
  });
409
- let current = input;
410
547
  const mergedResponses = {};
411
- for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS; attempt++) {
412
- const response = await this.client.send(new BatchGetCommand(current));
548
+ const attempt = async (request) => {
549
+ const response = await this.client.send(new BatchGetCommand(request));
413
550
  for (const [table, items] of Object.entries(response.Responses ?? {})) {
414
551
  mergedResponses[table] = [...(mergedResponses[table] ?? []), ...items];
415
552
  }
416
- const unprocessed = response.UnprocessedKeys;
417
- if (!unprocessed || Object.keys(unprocessed).length === 0) {
418
- return { ...response, Responses: mergedResponses };
419
- }
553
+ const unprocessed = response.UnprocessedKeys ?? {};
554
+ return {
555
+ output: { ...response, Responses: mergedResponses },
556
+ unprocessed,
557
+ pending: pendingCounts(unprocessed, ({ Keys }) => Keys?.length),
558
+ };
559
+ };
560
+ let current = input;
561
+ for (let attemptNumber = 1; attemptNumber < BATCH_GET_MAX_ATTEMPTS; attemptNumber++) {
562
+ const { output, unprocessed, pending } = await attempt(current);
563
+ if (pending.length === 0)
564
+ return output;
420
565
  this.logger.warn('Retrying unprocessed DynamoDB items', {
421
- attempt: attempt + 1,
422
- tables: Object.keys(unprocessed),
566
+ attempt: attemptNumber,
567
+ tables: pending.map(({ table }) => table),
423
568
  });
424
- if (attempt < BATCH_GET_MAX_ATTEMPTS - 1)
425
- await sleep(backoffDelay(attempt, BATCH_GET_BASE_DELAY_MS));
569
+ await sleep(backoffDelay(attemptNumber - 1, BATCH_GET_BASE_DELAY_MS));
426
570
  current = { ...input, RequestItems: unprocessed };
427
571
  }
428
- throw new Error(`batchGet failed after ${BATCH_GET_MAX_ATTEMPTS} attempts`);
572
+ const { output, pending } = await attempt(current);
573
+ if (pending.length === 0)
574
+ return output;
575
+ return throwBatchFailure(this.logger, 'DynamoDB batchGet', [output], unprocessedEntries(pending, 'UnprocessedKeys', BATCH_GET_MAX_ATTEMPTS));
429
576
  }
430
577
  /**
431
578
  * Batch-write items to DynamoDB, retrying `UnprocessedItems` with jittered
432
- * exponential backoff. Up to 5 attempts (200ms base delay). Throws when
433
- * items remain unprocessed after the final attempt.
579
+ * exponential backoff. Up to 5 attempts (200ms base delay).
580
+ *
581
+ * @throws {@link BatchOperationError} when items remain unprocessed after
582
+ * the final attempt. `results` holds one output: the last response, whose
583
+ * `UnprocessedItems` are the writes still to retry. `failed` has one entry
584
+ * per pending write with `code: 'UnprocessedItems'` and an `id` of
585
+ * `<table>[<index>]`, the write's position in
586
+ * `results[0].UnprocessedItems[<table>]`. The `failed` list never carries
587
+ * item data; `results` does, as it is data the caller supplied, so don't
588
+ * log the error object itself (see {@link BatchOperationError}).
589
+ * Request-level SDK exceptions propagate unchanged.
434
590
  */
435
591
  async batchWrite(input) {
436
592
  this.logger.info('Batch writing DynamoDB items', {
437
593
  input: redactInput(this.logger, input, summariseTables),
438
594
  });
595
+ const attempt = async (request) => {
596
+ const response = await this.client.send(new BatchWriteCommand(request));
597
+ const unprocessed = response.UnprocessedItems ?? {};
598
+ return {
599
+ response,
600
+ unprocessed,
601
+ pending: pendingCounts(unprocessed, writes => writes.length),
602
+ };
603
+ };
439
604
  let current = input;
440
- for (let attempt = 0; attempt < BATCH_WRITE_MAX_ATTEMPTS; attempt++) {
441
- const response = await this.client.send(new BatchWriteCommand(current));
442
- const unprocessed = response.UnprocessedItems;
443
- if (!unprocessed || Object.keys(unprocessed).length === 0)
605
+ for (let attemptNumber = 1; attemptNumber < BATCH_WRITE_MAX_ATTEMPTS; attemptNumber++) {
606
+ const { response, unprocessed, pending } = await attempt(current);
607
+ if (pending.length === 0)
444
608
  return response;
445
609
  this.logger.warn('Retrying unprocessed DynamoDB items', {
446
- attempt: attempt + 1,
447
- tables: Object.keys(unprocessed),
610
+ attempt: attemptNumber,
611
+ tables: pending.map(({ table }) => table),
448
612
  });
449
- if (attempt < BATCH_WRITE_MAX_ATTEMPTS - 1)
450
- await sleep(backoffDelay(attempt, BATCH_WRITE_BASE_DELAY_MS));
613
+ await sleep(backoffDelay(attemptNumber - 1, BATCH_WRITE_BASE_DELAY_MS));
451
614
  current = { ...input, RequestItems: unprocessed };
452
615
  }
453
- throw new Error(`batchWrite failed after ${BATCH_WRITE_MAX_ATTEMPTS} attempts`);
616
+ const { response, pending } = await attempt(current);
617
+ if (pending.length === 0)
618
+ return response;
619
+ return throwBatchFailure(this.logger, 'DynamoDB batchWrite', [response], unprocessedEntries(pending, 'UnprocessedItems', BATCH_WRITE_MAX_ATTEMPTS));
454
620
  }
455
621
  /**
456
622
  * Paginate over Query results, yielding one unmarshalled item at a time.
@@ -513,86 +679,6 @@ class DynamoDBService {
513
679
  }
514
680
  }
515
681
 
516
- /**
517
- * Thrown by the batch methods once every chunk has been sent and at least one
518
- * entry was rejected.
519
- *
520
- * `results` holds the raw SDK output of every chunk, so the outputs of the
521
- * entries that succeeded (message ids, sequence numbers) stay readable. The
522
- * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
523
- * and `SSM.getParameters`, whose `results` are empty.
524
- * `failed` is the normalised list of rejected entries across all chunks.
525
- *
526
- * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
527
- * this package may be loaded in one process.
528
- */
529
- class BatchOperationError extends Error {
530
- results;
531
- failed;
532
- name = 'BatchOperationError';
533
- constructor(results, failed) {
534
- super(`Batch operation failed for ${failed.length} entries (${distinctCodes(failed).join(', ')})`);
535
- this.results = results;
536
- this.failed = failed;
537
- }
538
- }
539
- /**
540
- * SQS and SNS report rejected entries under `Failed` on an otherwise
541
- * successful response, so a resolved chunk does not mean every entry was
542
- * accepted. Extracts those entries and delegates to {@link throwIfAny}.
543
- *
544
- * Only id, code and message are copied out — never the entry itself — so
545
- * neither the error nor the warning can leak a payload.
546
- */
547
- function throwIfAnyFailed(logger, operation, results) {
548
- const failed = results.flatMap(result => (result.Failed ?? []).map(({ Id, Code, Message }) => ({
549
- id: Id,
550
- code: Code,
551
- message: Message,
552
- })));
553
- return throwIfAny(logger, operation, results, failed);
554
- }
555
- /**
556
- * S3 reports undeleted keys under `Errors` on an otherwise successful
557
- * `DeleteObjects` response. Same contract as {@link throwIfAnyFailed}; the
558
- * key is carried as the failed entry's `id`, and `VersionId` is dropped.
559
- */
560
- function throwIfAnyDeleteErrors(logger, operation, results) {
561
- const failed = results.flatMap(result => (result.Errors ?? []).map(({ Key, Code, Message }) => ({
562
- id: Key,
563
- code: Code,
564
- message: Message,
565
- })));
566
- return throwIfAny(logger, operation, results, failed);
567
- }
568
- /**
569
- * Warn-and-throw step for services whose responses don't use the SQS/SNS
570
- * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
571
- * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
572
- * Returns `results` untouched when `failed` is empty.
573
- *
574
- * Callers must build `failed` by copying id, code and message explicitly —
575
- * never by spreading the SDK entry — because it goes straight into the error
576
- * and the warning.
577
- */
578
- function throwIfAny(logger, operation, results, failed) {
579
- if (failed.length === 0)
580
- return results;
581
- logger.warn(`${operation} had rejected entries`, {
582
- failedCount: failed.length,
583
- codes: distinctCodes(failed),
584
- });
585
- throw new BatchOperationError(results, failed);
586
- }
587
- /**
588
- * Distinct error codes in first-seen order, for the error message and the
589
- * warning log line.
590
- */
591
- function distinctCodes(failed) {
592
- const codes = failed.flatMap(entry => (entry.code === undefined ? [] : [entry.code]));
593
- return [...new Set(codes)];
594
- }
595
-
596
682
  /**
597
683
  * Split a list into consecutive chunks of at most `size` items, mirroring the
598
684
  * per-request caps the AWS APIs enforce on batch operations.
@@ -604,6 +690,16 @@ function chunk(items, size) {
604
690
  }
605
691
  return chunks;
606
692
  }
693
+ /**
694
+ * The index, as a string, that an entry had in the list `chunk` split, given
695
+ * its chunk number and its position within that chunk. Batch operations whose
696
+ * entries carry no identifier of their own report failures by this index.
697
+ * `chunk` fills every chunk but the last, so the chunk's offset is the chunk
698
+ * number times the chunk size.
699
+ */
700
+ function originalIndex(chunkIndex, chunkSize, position) {
701
+ return String(chunkIndex * chunkSize + position);
702
+ }
607
703
 
608
704
  const PUT_EVENTS_LIMIT = 10;
609
705
  /**
@@ -613,13 +709,8 @@ const PUT_EVENTS_LIMIT = 10;
613
709
  function summariseEntries$1({ EndpointId, Entries }) {
614
710
  return { EndpointId, entryCount: Entries?.length ?? 0 };
615
711
  }
616
- /**
617
- * Chunks are full except the last, so the caller's original index of a
618
- * rejected entry is the chunk's offset (chunk number times the chunk size)
619
- * plus its position within the chunk.
620
- */
621
712
  function extractPutEventsFailures(results) {
622
- return results.flatMap((result, chunkIndex) => extractChunkFailures(result, chunkIndex * PUT_EVENTS_LIMIT));
713
+ return results.flatMap(extractChunkFailures);
623
714
  }
624
715
  /**
625
716
  * `PutEvents` reports a rejected entry by an error code on the result entry at
@@ -628,10 +719,10 @@ function extractPutEventsFailures(results) {
628
719
  * Copies only code and message out, never the request entry, so neither the
629
720
  * error nor the warning can carry event detail.
630
721
  */
631
- function extractChunkFailures(result, offset) {
722
+ function extractChunkFailures(result, chunkIndex) {
632
723
  return (result.Entries ?? [])
633
724
  .map(({ ErrorCode, ErrorMessage }, position) => ({
634
- id: String(offset + position),
725
+ id: originalIndex(chunkIndex, PUT_EVENTS_LIMIT, position),
635
726
  code: ErrorCode,
636
727
  message: ErrorMessage,
637
728
  }))
@@ -834,8 +925,34 @@ class LambdaService {
834
925
  }
835
926
  }
836
927
 
928
+ /**
929
+ * `JSON.parse` that never leaks the parsed text. V8's `SyntaxError` message
930
+ * embeds a snippet of the input (`Unexpected token 'h', ..."assword": hunter2}"
931
+ * is not valid JSON`), and the wrappers parse secrets and stored objects, so
932
+ * letting it through would put that content into the caller's error logs.
933
+ *
934
+ * The original error is deliberately not attached as `cause`: loggers serialise
935
+ * `cause` and its message carries the snippet. `context` should identify the
936
+ * source (a secret id, a bucket and key) so the failure is still diagnosable.
937
+ *
938
+ * @throws An `Error` naming `context`, without any of the input text.
939
+ */
940
+ function parseJson(text, context) {
941
+ try {
942
+ return JSON.parse(text);
943
+ }
944
+ catch {
945
+ throw new Error(`${context} does not contain valid JSON`);
946
+ }
947
+ }
948
+
837
949
  const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
838
950
  const DELETE_OBJECTS_BATCH_LIMIT = 1000;
951
+ /**
952
+ * `Key` is `string | undefined` here because the SDK types a required `Key`
953
+ * that way even through `Required<Pick<...>>`.
954
+ */
955
+ const parseJsonObject = (body, bucket, key) => parseJson(body, `S3 object s3://${bucket}/${key}`);
839
956
  /**
840
957
  * Fields safe to log at INFO for `putObject`. Omits `Body` (object payload).
841
958
  */
@@ -930,13 +1047,15 @@ class S3Service {
930
1047
  * Get an object from S3 and parse it as JSON.
931
1048
  * @template T - Expected type of the parsed value.
932
1049
  * @returns The parsed value, or `undefined` if the response has no body.
933
- * @throws If the body is non-empty and not valid JSON.
1050
+ * @throws If the body is non-empty and not valid JSON. The error names the
1051
+ * object and never includes any of its content, unlike the native
1052
+ * `SyntaxError`.
934
1053
  */
935
1054
  async getJsonObject(input) {
936
1055
  this.logger.info('Getting S3 JSON object', { input });
937
1056
  const response = await this.client.send(new GetObjectCommand(input));
938
1057
  const body = await response.Body?.transformToString();
939
- return body ? JSON.parse(body) : undefined;
1058
+ return body ? parseJsonObject(body, input.Bucket, input.Key) : undefined;
940
1059
  }
941
1060
  /**
942
1061
  * Fetch the metadata for an S3 object without downloading its body.
@@ -966,6 +1085,9 @@ class S3Service {
966
1085
  * List and JSON-parse every object under a bucket and optional prefix.
967
1086
  * Auto-paginated. Objects without a body are skipped.
968
1087
  * @template T - Expected type of each parsed object.
1088
+ * @throws If any object is not valid JSON. The error names that object's
1089
+ * key and never includes any of its content, unlike the native
1090
+ * `SyntaxError`; objects after it are not fetched.
969
1091
  */
970
1092
  async getAllObjects(bucket, prefix) {
971
1093
  this.logger.info('Getting all S3 objects', { input: { bucket, prefix } });
@@ -978,7 +1100,7 @@ class S3Service {
978
1100
  const response = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: object.Key }));
979
1101
  const body = await response.Body?.transformToString();
980
1102
  if (body)
981
- bodies.push(JSON.parse(body));
1103
+ bodies.push(parseJsonObject(body, bucket, object.Key));
982
1104
  }
983
1105
  }
984
1106
  return bodies;
@@ -1323,12 +1445,14 @@ class SecretsManagerService {
1323
1445
  * @param secretId - The ARN or friendly name of the secret.
1324
1446
  * @template T - Expected shape of the parsed secret.
1325
1447
  * @returns The parsed secret value.
1326
- * @throws If the secret has no `SecretString` or the value is not valid JSON.
1448
+ * @throws If the secret has no `SecretString`, or the value is not valid
1449
+ * JSON. The latter error names the secret and never includes any of its
1450
+ * value, unlike the native `SyntaxError`.
1327
1451
  */
1328
1452
  async getJsonSecret(secretId) {
1329
1453
  this.logger.info('Fetching JSON secret', { input: { secretId } });
1330
1454
  const secretString = await this.fetchSecretString(secretId);
1331
- return JSON.parse(secretString);
1455
+ return parseJson(secretString, `Secret '${secretId}'`);
1332
1456
  }
1333
1457
  /**
1334
1458
  * Create a new secret. At INFO level the log line includes only identity
@@ -1389,6 +1513,139 @@ class SecretsManagerService {
1389
1513
  }
1390
1514
  }
1391
1515
 
1516
+ const SEND_BULK_EMAIL_LIMIT = 50;
1517
+ /**
1518
+ * Sent entries whose result isn't `SUCCESS`, identified by their original
1519
+ * index in the caller's `BulkEmailEntries`. Walks the entries that were sent
1520
+ * rather than the results that came back, so an entry SES returned no result
1521
+ * for counts as failed instead of passing unnoticed. Only status and error are
1522
+ * copied out, never the entry, so no destination can leak.
1523
+ */
1524
+ function extractBulkEmailFailures(sentChunks, results) {
1525
+ return sentChunks.flatMap((sent, chunkIndex) => sent.flatMap((_, entryIndex) => {
1526
+ const result = results[chunkIndex]?.BulkEmailEntryResults?.[entryIndex];
1527
+ if (result?.Status === 'SUCCESS')
1528
+ return [];
1529
+ return [
1530
+ {
1531
+ id: originalIndex(chunkIndex, SEND_BULK_EMAIL_LIMIT, entryIndex),
1532
+ code: result?.Status,
1533
+ message: result?.Error ?? result?.Status ?? 'No status returned for entry',
1534
+ },
1535
+ ];
1536
+ }));
1537
+ }
1538
+ /**
1539
+ * Safe log shape for `sendEmail`. Keeps routing metadata and reduces the
1540
+ * recipients to a count; the sender and reply-to addresses, the subject, the
1541
+ * body and any template data are omitted as PII or payload. The template name
1542
+ * is operational metadata, not PII, so it is kept.
1543
+ */
1544
+ function summariseSendEmail(input) {
1545
+ const { ToAddresses, CcAddresses, BccAddresses } = input.Destination ?? {};
1546
+ return {
1547
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1548
+ ConfigurationSetName: input.ConfigurationSetName,
1549
+ EmailTags: input.EmailTags,
1550
+ EndpointId: input.EndpointId,
1551
+ TenantName: input.TenantName,
1552
+ templateName: input.Content?.Template?.TemplateName,
1553
+ recipientCount: (ToAddresses?.length ?? 0) + (CcAddresses?.length ?? 0) + (BccAddresses?.length ?? 0),
1554
+ };
1555
+ }
1556
+ /**
1557
+ * Safe log shape for `sendBulkEmail`. The entries carry destinations and
1558
+ * replacement data, and the default template data may carry PII, so they are
1559
+ * reduced to a count and the template name.
1560
+ */
1561
+ function summariseSendBulkEmail(input) {
1562
+ return {
1563
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1564
+ ConfigurationSetName: input.ConfigurationSetName,
1565
+ DefaultEmailTags: input.DefaultEmailTags,
1566
+ EndpointId: input.EndpointId,
1567
+ TenantName: input.TenantName,
1568
+ templateName: input.DefaultContent?.Template?.TemplateName,
1569
+ entryCount: input.BulkEmailEntries?.length ?? 0,
1570
+ };
1571
+ }
1572
+ /**
1573
+ * Wrapper around the AWS SES v2 client providing structured Powertools logging
1574
+ * and X-Ray tracing by default.
1575
+ *
1576
+ * Wraps SES v2 (`@aws-sdk/client-sesv2`), not the legacy v1 API. No defaults
1577
+ * are baked in: every send option, including `FromEmailAddress` and
1578
+ * `ConfigurationSetName`, comes from the caller.
1579
+ *
1580
+ * Where a method's input carries payloads or PII, the INFO log line omits
1581
+ * them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or `TRACE`) log full
1582
+ * SDK inputs.
1583
+ */
1584
+ class SESService {
1585
+ client;
1586
+ logger;
1587
+ /**
1588
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
1589
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1590
+ * @param opts.client - Optional pre-configured `SESv2Client`. When supplied,
1591
+ * the wrapper does not apply X-Ray instrumentation.
1592
+ */
1593
+ constructor(opts) {
1594
+ this.client = opts?.client ?? xray.captureAWSv3Client(new SESv2Client());
1595
+ this.logger = opts?.logger ?? new Logger();
1596
+ }
1597
+ /**
1598
+ * Send a single email (Simple, Raw or Template content).
1599
+ *
1600
+ * At INFO level the log line includes only routing metadata and a
1601
+ * recipient count; see `summariseSendEmail`.
1602
+ *
1603
+ * Pass-through: SDK exceptions (`MessageRejected`, `SendingPausedException`,
1604
+ * …) propagate unwrapped.
1605
+ *
1606
+ * @returns The SDK output, including `MessageId`.
1607
+ */
1608
+ async sendEmail(input) {
1609
+ this.logger.info('Sending SES email', {
1610
+ input: redactInput(this.logger, input, summariseSendEmail),
1611
+ });
1612
+ return this.client.send(new SendEmailCommand(input));
1613
+ }
1614
+ /**
1615
+ * Send a templated email to many destinations. SES caps `SendBulkEmail`
1616
+ * at 50 entries per request, so this method auto-chunks `BulkEmailEntries`
1617
+ * and sends one request per chunk, in order. Every chunk shares the other
1618
+ * input fields.
1619
+ *
1620
+ * At INFO level the log line includes only routing metadata, the template
1621
+ * name and an entry count; see `summariseSendBulkEmail`.
1622
+ *
1623
+ * SES answers HTTP 200 even when entries fail, so every chunk is sent
1624
+ * before the outcome is judged. If any entry's `Status` isn't `SUCCESS`
1625
+ * (or SES returned no result for it), a {@link BatchOperationError} is thrown whose
1626
+ * `failed[].id` is the entry's original index in `BulkEmailEntries` as a
1627
+ * string, and whose `results` are the per-chunk outputs — so a caller can
1628
+ * retry only the failed indexes. Request-level SDK exceptions are not
1629
+ * wrapped.
1630
+ *
1631
+ * Sending is not idempotent: retrying the whole batch after a throw
1632
+ * re-sends the entries that succeeded.
1633
+ *
1634
+ * @returns One SDK output per request sent.
1635
+ */
1636
+ async sendBulkEmail(input) {
1637
+ this.logger.info('Sending SES bulk email', {
1638
+ input: redactInput(this.logger, input, summariseSendBulkEmail),
1639
+ });
1640
+ const results = [];
1641
+ const sentChunks = chunk(input.BulkEmailEntries ?? [], SEND_BULK_EMAIL_LIMIT);
1642
+ for (const entries of sentChunks) {
1643
+ results.push(await this.client.send(new SendBulkEmailCommand({ ...input, BulkEmailEntries: entries })));
1644
+ }
1645
+ return throwIfAny(this.logger, 'SES sendBulkEmail', results, extractBulkEmailFailures(sentChunks, results));
1646
+ }
1647
+ }
1648
+
1392
1649
  /**
1393
1650
  * Fields safe to log at INFO for `startExecution`. Omits `input` — the SFN
1394
1651
  * execution payload, which routinely carries PII (customer IDs, addresses,
@@ -1489,8 +1746,16 @@ function truncateCodepoints(str, maxChars) {
1489
1746
  }
1490
1747
 
1491
1748
  const PUBLISH_BATCH_LIMIT = 10;
1749
+ /**
1750
+ * The default `MaximumMessageSize` of an SNS topic. Topics can be raised to
1751
+ * 1 MiB, but the wrapper does not know a topic's setting, so it cuts at the
1752
+ * size every topic accepts. Message attributes count toward the topic limit
1753
+ * too and are not truncated, so a message at this size plus attributes can
1754
+ * still be rejected.
1755
+ */
1492
1756
  const SNS_MESSAGE_MAX_BYTES = 256 * 1024;
1493
- const SNS_SUBJECT_MAX_CHARS = 100;
1757
+ /** SNS requires a subject of *less than* 100 characters, so 99 is the maximum. */
1758
+ const SNS_SUBJECT_MAX_CHARS = 99;
1494
1759
  /**
1495
1760
  * Fields safe to log at INFO level for `publish`. Omits `Message`, `Subject`,
1496
1761
  * `MessageAttributes`, and `PhoneNumber` — payloads, user-visible content
@@ -1521,11 +1786,14 @@ class SNSService {
1521
1786
  * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1522
1787
  * @param opts.client - Optional pre-configured `SNSClient`. When supplied,
1523
1788
  * the wrapper does not apply X-Ray instrumentation.
1524
- * @param opts.truncate - When `true`, oversized `Message` / `Subject` are
1525
- * truncated (byte-safe / codepoint-safe) before sending instead of failing
1526
- * at the SDK. Defaults to `false` — the SDK throws on oversize, which is
1527
- * usually the right failure mode. Each `publish` call can override via
1528
- * its own `truncate` option.
1789
+ * @param opts.truncate - When `true`, an oversized `Message` (above 256 KiB,
1790
+ * the default topic limit — raising a topic's `MaximumMessageSize` does not
1791
+ * raise this cut-off) or `Subject` (above 99 characters) is truncated
1792
+ * (byte-safe / codepoint-safe) before sending instead of failing at the
1793
+ * SDK. Truncating a structured `Message` such as JSON can leave it invalid.
1794
+ * Defaults to `false` — the SDK throws on oversize, which is usually the
1795
+ * right failure mode. Each `publish` call can override via its own
1796
+ * `truncate` option.
1529
1797
  */
1530
1798
  constructor(opts) {
1531
1799
  this.client = opts?.client ?? xray.captureAWSv3Client(new SNSClient());
@@ -1611,7 +1879,12 @@ class SNSService {
1611
1879
  }
1612
1880
 
1613
1881
  const SQS_BATCH_LIMIT = 10;
1614
- const SQS_MESSAGE_BODY_MAX_BYTES = 256 * 1024;
1882
+ /**
1883
+ * The SQS maximum message size. A queue's own `MaximumMessageSize` may be set
1884
+ * lower, and the wrapper cannot see it, so a queue configured below this still
1885
+ * rejects a body truncated to it.
1886
+ */
1887
+ const SQS_MESSAGE_BODY_MAX_BYTES = 1024 * 1024;
1615
1888
  /**
1616
1889
  * Fields safe to log at INFO level for `sendMessage`. Omits `MessageBody` and
1617
1890
  * `MessageAttributes` — both carry payload content.
@@ -1646,9 +1919,13 @@ class SQSService {
1646
1919
  * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1647
1920
  * @param opts.client - Optional pre-configured `SQSClient`. When supplied,
1648
1921
  * the wrapper does not apply X-Ray instrumentation.
1649
- * @param opts.truncate - When `true`, oversized `MessageBody` is truncated
1650
- * (byte-safe) before sending instead of failing at the SDK. Defaults to
1651
- * `false`. Each `sendMessage` call can override via its own `truncate`
1922
+ * @param opts.truncate - When `true`, a `MessageBody` above 1 MiB is
1923
+ * truncated (byte-safe) before sending instead of failing at the SDK. This
1924
+ * is the SQS maximum; a queue configured with a lower `MaximumMessageSize`
1925
+ * is not known to the wrapper. Message attributes count toward the limit
1926
+ * too and are not truncated.
1927
+ * Truncating a structured body such as JSON can leave it invalid. Defaults
1928
+ * to `false`. Each `sendMessage` call can override via its own `truncate`
1652
1929
  * option.
1653
1930
  */
1654
1931
  constructor(opts) {
@@ -1758,6 +2035,20 @@ class SQSService {
1758
2035
  }
1759
2036
 
1760
2037
  const GET_PARAMETERS_LIMIT = 10;
2038
+ /**
2039
+ * Every string a caller may have used to request this parameter. SSM answers
2040
+ * with the plain `Name` whatever was requested, so an ARN or a
2041
+ * `name:version` / `name:label` selector can only be matched through `ARN`
2042
+ * and `Selector`. A response carrying a `Selector` is keyed by its selector
2043
+ * forms only, so it can't shadow a request for the unversioned parameter.
2044
+ * `Selector` already carries its leading colon (`:3`, `:prod`).
2045
+ */
2046
+ function requestKeys({ Name, ARN, Selector }) {
2047
+ const identifiers = [Name, ARN].filter((id) => id !== undefined);
2048
+ if (Selector === undefined)
2049
+ return identifiers;
2050
+ return identifiers.map(id => `${id}${Selector}`);
2051
+ }
1761
2052
  /**
1762
2053
  * One failed entry per alias whose path SSM reported as invalid, so two
1763
2054
  * aliases sharing a missing path are both named.
@@ -1857,7 +2148,9 @@ class SSMService {
1857
2148
  * alias in `message`. Request-level SDK exceptions are not wrapped.
1858
2149
  *
1859
2150
  * @param aliases - Record mapping each desired local alias to its SSM
1860
- * parameter name (or ARN).
2151
+ * parameter name, ARN, or a `name:version` / `name:label` selector. The
2152
+ * value is matched back to the response by the name, ARN and selector SSM
2153
+ * reports, so each of those forms resolves to its own parameter.
1861
2154
  * @param opts.required - Throw when any requested parameter does not
1862
2155
  * exist. Defaults to `false`.
1863
2156
  * @returns A record keyed by the same aliases, mapping each to the
@@ -1867,7 +2160,7 @@ class SSMService {
1867
2160
  async getParameters(aliases, opts) {
1868
2161
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1869
2162
  const names = Object.values(aliases);
1870
- const byPath = new Map();
2163
+ const byRequest = new Map();
1871
2164
  const invalidPaths = new Set();
1872
2165
  for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
1873
2166
  const response = await this.client.send(new GetParametersCommand({
@@ -1875,8 +2168,8 @@ class SSMService {
1875
2168
  WithDecryption: true,
1876
2169
  }));
1877
2170
  for (const parameter of response.Parameters ?? []) {
1878
- if (parameter.Name !== undefined)
1879
- byPath.set(parameter.Name, parameter.Value);
2171
+ for (const key of requestKeys(parameter))
2172
+ byRequest.set(key, parameter.Value);
1880
2173
  }
1881
2174
  for (const name of response.InvalidParameters ?? [])
1882
2175
  invalidPaths.add(name);
@@ -1887,7 +2180,7 @@ class SSMService {
1887
2180
  }
1888
2181
  const result = {};
1889
2182
  for (const alias of Object.keys(aliases)) {
1890
- result[alias] = byPath.get(aliases[alias]);
2183
+ result[alias] = byRequest.get(aliases[alias]);
1891
2184
  }
1892
2185
  return result;
1893
2186
  }
@@ -1935,4 +2228,4 @@ class SSMService {
1935
2228
  }
1936
2229
  }
1937
2230
 
1938
- export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, EventBridgeService, LambdaFunctionError, LambdaService, S3Service, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };
2231
+ export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, EventBridgeService, LambdaFunctionError, LambdaService, S3Service, SESService, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };