@aligent/aws-wrappers 0.5.8 → 0.5.10

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 (61) hide show
  1. package/README.md +130 -3
  2. package/cjs/index.cjs +424 -11
  3. package/cjs/package.json +4 -1
  4. package/cjs/src/eventbridge/eventbridge.d.ts +58 -0
  5. package/cjs/src/eventbridge/eventbridge.d.ts.map +1 -0
  6. package/cjs/src/index.d.ts +4 -0
  7. package/cjs/src/index.d.ts.map +1 -1
  8. package/cjs/src/lambda/lambda.d.ts +54 -0
  9. package/cjs/src/lambda/lambda.d.ts.map +1 -0
  10. package/cjs/src/scheduler/scheduler.d.ts +3 -2
  11. package/cjs/src/scheduler/scheduler.d.ts.map +1 -1
  12. package/cjs/src/ses/ses.d.ts +64 -0
  13. package/cjs/src/ses/ses.d.ts.map +1 -0
  14. package/cjs/src/ssm/ssm.d.ts +18 -3
  15. package/cjs/src/ssm/ssm.d.ts.map +1 -1
  16. package/cjs/src/util/batch-operation-error.d.ts +13 -7
  17. package/cjs/src/util/batch-operation-error.d.ts.map +1 -1
  18. package/cjs/src/util/chunk.d.ts +8 -0
  19. package/cjs/src/util/chunk.d.ts.map +1 -1
  20. package/cjs/src/util/lambda-function-error.d.ts +36 -0
  21. package/cjs/src/util/lambda-function-error.d.ts.map +1 -0
  22. package/docs/index/classes/APIGatewayService.md +6 -6
  23. package/docs/index/classes/APIGatewayV2Service.md +5 -5
  24. package/docs/index/classes/BatchOperationError.md +7 -6
  25. package/docs/index/classes/DynamoDBService.md +12 -12
  26. package/docs/index/classes/EventBridgeService.md +99 -0
  27. package/docs/index/classes/LambdaFunctionError.md +283 -0
  28. package/docs/index/classes/LambdaService.md +95 -0
  29. package/docs/index/classes/S3Service.md +15 -15
  30. package/docs/index/classes/SESService.md +123 -0
  31. package/docs/index/classes/SNSService.md +4 -4
  32. package/docs/index/classes/SQSService.md +7 -7
  33. package/docs/index/classes/SSMService.md +33 -10
  34. package/docs/index/classes/SchedulerService.md +14 -13
  35. package/docs/index/classes/SecretsManagerService.md +8 -8
  36. package/docs/index/classes/StepFunctionsService.md +6 -6
  37. package/docs/index/interfaces/BatchFailedEntry.md +6 -5
  38. package/docs/index/interfaces/EmptyBucketPageResult.md +2 -2
  39. package/docs/index/modules.md +4 -0
  40. package/docs/testing/testing/functions/createMockService.md +1 -1
  41. package/esm/index.mjs +421 -12
  42. package/esm/package.json +4 -1
  43. package/esm/src/eventbridge/eventbridge.d.ts +58 -0
  44. package/esm/src/eventbridge/eventbridge.d.ts.map +1 -0
  45. package/esm/src/index.d.ts +4 -0
  46. package/esm/src/index.d.ts.map +1 -1
  47. package/esm/src/lambda/lambda.d.ts +54 -0
  48. package/esm/src/lambda/lambda.d.ts.map +1 -0
  49. package/esm/src/scheduler/scheduler.d.ts +3 -2
  50. package/esm/src/scheduler/scheduler.d.ts.map +1 -1
  51. package/esm/src/ses/ses.d.ts +64 -0
  52. package/esm/src/ses/ses.d.ts.map +1 -0
  53. package/esm/src/ssm/ssm.d.ts +18 -3
  54. package/esm/src/ssm/ssm.d.ts.map +1 -1
  55. package/esm/src/util/batch-operation-error.d.ts +13 -7
  56. package/esm/src/util/batch-operation-error.d.ts.map +1 -1
  57. package/esm/src/util/chunk.d.ts +8 -0
  58. package/esm/src/util/chunk.d.ts.map +1 -1
  59. package/esm/src/util/lambda-function-error.d.ts +36 -0
  60. package/esm/src/util/lambda-function-error.d.ts.map +1 -0
  61. package/package.json +4 -1
@@ -12,9 +12,13 @@
12
12
  - [APIGatewayV2Service](classes/APIGatewayV2Service.md)
13
13
  - [BatchOperationError](classes/BatchOperationError.md)
14
14
  - [DynamoDBService](classes/DynamoDBService.md)
15
+ - [EventBridgeService](classes/EventBridgeService.md)
16
+ - [LambdaFunctionError](classes/LambdaFunctionError.md)
17
+ - [LambdaService](classes/LambdaService.md)
15
18
  - [S3Service](classes/S3Service.md)
16
19
  - [SchedulerService](classes/SchedulerService.md)
17
20
  - [SecretsManagerService](classes/SecretsManagerService.md)
21
+ - [SESService](classes/SESService.md)
18
22
  - [SNSService](classes/SNSService.md)
19
23
  - [SQSService](classes/SQSService.md)
20
24
  - [SSMService](classes/SSMService.md)
@@ -8,7 +8,7 @@
8
8
 
9
9
  > **createMockService**\<`T`, `O`\>(`service`, `overrides`): `T` & `O`
10
10
 
11
- Defined in: [packages/aws-wrappers/src/testing/testing.ts:66](https://github.com/aligent/microservice-development-utilities/blob/8b1bfce9cb585c7bb3b8f4bf6535b1058f295574/packages/aws-wrappers/src/testing/testing.ts#L66)
11
+ Defined in: [packages/aws-wrappers/src/testing/testing.ts:66](https://github.com/aligent/microservice-development-utilities/blob/e278ae3f29a38b1e451dd1bab16695aea28a55c1/packages/aws-wrappers/src/testing/testing.ts#L66)
12
12
 
13
13
  Build a stand-in for a service class from an object of method overrides, for
14
14
  use in unit tests of code that depends on the service.
package/esm/index.mjs CHANGED
@@ -4,10 +4,13 @@ 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
6
  import { DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, DeleteCommand, QueryCommand, ScanCommand, BatchGetCommand, BatchWriteCommand, paginateQuery, paginateScan } from '@aws-sdk/lib-dynamodb';
7
+ import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';
8
+ import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
7
9
  import { S3Client, PutObjectCommand, GetObjectCommand, HeadObjectCommand, CopyObjectCommand, paginateListObjectsV2, DeleteObjectCommand, DeleteObjectsCommand } from '@aws-sdk/client-s3';
8
10
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
9
11
  import { SchedulerClient, CreateScheduleCommand, GetScheduleCommand, UpdateScheduleCommand, DeleteScheduleCommand, paginateListSchedules, CreateScheduleGroupCommand, GetScheduleGroupCommand, DeleteScheduleGroupCommand, paginateListScheduleGroups } from '@aws-sdk/client-scheduler';
10
12
  import { SecretsManagerClient, CreateSecretCommand, UpdateSecretCommand, PutSecretValueCommand, DeleteSecretCommand, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
13
+ import { SESv2Client, SendEmailCommand, SendBulkEmailCommand } from '@aws-sdk/client-sesv2';
11
14
  import { SFNClient, paginateListExecutions, StartExecutionCommand, DescribeExecutionCommand, StopExecutionCommand } from '@aws-sdk/client-sfn';
12
15
  import { SNSClient, PublishCommand, PublishBatchCommand } from '@aws-sdk/client-sns';
13
16
  import { SQSClient, SendMessageCommand, ReceiveMessageCommand, DeleteMessageCommand, SendMessageBatchCommand, DeleteMessageBatchCommand } from '@aws-sdk/client-sqs';
@@ -517,7 +520,8 @@ class DynamoDBService {
517
520
  *
518
521
  * `results` holds the raw SDK output of every chunk, so the outputs of the
519
522
  * entries that succeeded (message ids, sequence numbers) stay readable. The
520
- * one exception is `S3.emptyBucket`, whose `results` are per-page deleted keys.
523
+ * exceptions are `S3.emptyBucket`, whose `results` are per-page deleted keys,
524
+ * and `SSM.getParameters`, whose `results` are empty.
521
525
  * `failed` is the normalised list of rejected entries across all chunks.
522
526
  *
523
527
  * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
@@ -536,8 +540,7 @@ class BatchOperationError extends Error {
536
540
  /**
537
541
  * SQS and SNS report rejected entries under `Failed` on an otherwise
538
542
  * successful response, so a resolved chunk does not mean every entry was
539
- * accepted. Returns `results` untouched when nothing failed; otherwise warns
540
- * and throws a {@link BatchOperationError}.
543
+ * accepted. Extracts those entries and delegates to {@link throwIfAny}.
541
544
  *
542
545
  * Only id, code and message are copied out — never the entry itself — so
543
546
  * neither the error nor the warning can leak a payload.
@@ -564,9 +567,14 @@ function throwIfAnyDeleteErrors(logger, operation, results) {
564
567
  return throwIfAny(logger, operation, results, failed);
565
568
  }
566
569
  /**
567
- * Throws a {@link BatchOperationError} for operations whose `results` aren't a
568
- * plain list of SDK outputs, such as `S3.emptyBucket`. Returns `results`
569
- * untouched when `failed` is empty.
570
+ * Warn-and-throw step for services whose responses don't use the SQS/SNS
571
+ * `Failed` shape and so extract their own rejected entries (`EventBridge.putEvents`),
572
+ * or whose `results` aren't a plain list of SDK outputs (`S3.emptyBucket`).
573
+ * Returns `results` untouched when `failed` is empty.
574
+ *
575
+ * Callers must build `failed` by copying id, code and message explicitly —
576
+ * never by spreading the SDK entry — because it goes straight into the error
577
+ * and the warning.
570
578
  */
571
579
  function throwIfAny(logger, operation, results, failed) {
572
580
  if (failed.length === 0)
@@ -597,6 +605,240 @@ function chunk(items, size) {
597
605
  }
598
606
  return chunks;
599
607
  }
608
+ /**
609
+ * The index, as a string, that an entry had in the list `chunk` split, given
610
+ * its chunk number and its position within that chunk. Batch operations whose
611
+ * entries carry no identifier of their own report failures by this index.
612
+ * `chunk` fills every chunk but the last, so the chunk's offset is the chunk
613
+ * number times the chunk size.
614
+ */
615
+ function originalIndex(chunkIndex, chunkSize, position) {
616
+ return String(chunkIndex * chunkSize + position);
617
+ }
618
+
619
+ const PUT_EVENTS_LIMIT = 10;
620
+ /**
621
+ * `Detail`, `Resources` and the entries themselves are payload carriers, so
622
+ * the INFO line carries only the endpoint id and how many entries were sent.
623
+ */
624
+ function summariseEntries$1({ EndpointId, Entries }) {
625
+ return { EndpointId, entryCount: Entries?.length ?? 0 };
626
+ }
627
+ function extractPutEventsFailures(results) {
628
+ return results.flatMap(extractChunkFailures);
629
+ }
630
+ /**
631
+ * `PutEvents` reports a rejected entry by an error code on the result entry at
632
+ * the same position as the request entry.
633
+ *
634
+ * Copies only code and message out, never the request entry, so neither the
635
+ * error nor the warning can carry event detail.
636
+ */
637
+ function extractChunkFailures(result, chunkIndex) {
638
+ return (result.Entries ?? [])
639
+ .map(({ ErrorCode, ErrorMessage }, position) => ({
640
+ id: originalIndex(chunkIndex, PUT_EVENTS_LIMIT, position),
641
+ code: ErrorCode,
642
+ message: ErrorMessage,
643
+ }))
644
+ .filter(({ code }) => code !== undefined);
645
+ }
646
+ /**
647
+ * Wrapper around the AWS EventBridge client providing structured Powertools
648
+ * logging and X-Ray tracing by default.
649
+ *
650
+ * Where a method's input carries payloads, secret material or PII, the INFO
651
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
652
+ * `TRACE`) log full SDK inputs.
653
+ *
654
+ * Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
655
+ * schedules live in `SchedulerService`.
656
+ */
657
+ class EventBridgeService {
658
+ client;
659
+ logger;
660
+ /**
661
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
662
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
663
+ * @param opts.client - Optional pre-configured `EventBridgeClient`. When
664
+ * supplied, the wrapper does not apply X-Ray instrumentation.
665
+ */
666
+ constructor(opts) {
667
+ this.client = opts?.client ?? xray.captureAWSv3Client(new EventBridgeClient());
668
+ this.logger = opts?.logger ?? new Logger();
669
+ }
670
+ /**
671
+ * Publish events to an event bus. The EventBridge API caps `PutEvents` at
672
+ * 10 entries per request, so this method auto-chunks the caller's `Entries`
673
+ * and sends one request per chunk, returning the array of outputs. The
674
+ * remaining request fields (such as `EndpointId`) are carried onto every
675
+ * chunk.
676
+ *
677
+ * Chunking is by count only. The 256 KB request size limit is not enforced
678
+ * here: a chunk that exceeds it fails at the SDK as a request-level error.
679
+ *
680
+ * Every chunk is sent before the outcome is judged. If EventBridge rejected
681
+ * any entry (it reports an error code on the result entry), a
682
+ * {@link BatchOperationError} is then thrown carrying the per-chunk results
683
+ * and the failed entries. For this method each failed entry's `id` is
684
+ * always set, to the entry's index in the caller's original `Entries` list
685
+ * across all chunks, as a string. Only `id`, `code` and `message` are
686
+ * copied out, so event detail never reaches the error.
687
+ *
688
+ * No retries are performed. Request-level SDK exceptions (throttling,
689
+ * access denied, oversize request) are not wrapped: they propagate
690
+ * unchanged and immediately, so earlier chunks may already have been
691
+ * published.
692
+ *
693
+ * At INFO level the log line includes only the endpoint id and the entry
694
+ * count, because `Detail`, `Resources` and the entries themselves are
695
+ * payload carriers.
696
+ *
697
+ * @param input - PutEventsCommandInput including Entries.
698
+ */
699
+ async putEvents(input) {
700
+ const entries = input.Entries ?? [];
701
+ this.logger.info('Putting EventBridge events', {
702
+ input: redactInput(this.logger, input, summariseEntries$1),
703
+ });
704
+ const results = [];
705
+ for (const batch of chunk(entries, PUT_EVENTS_LIMIT)) {
706
+ results.push(await this.client.send(new PutEventsCommand({ ...input, Entries: batch })));
707
+ }
708
+ return throwIfAny(this.logger, 'EventBridge putEvents', results, extractPutEventsFailures(results));
709
+ }
710
+ }
711
+
712
+ /**
713
+ * Thrown by `LambdaService.invoke` when a synchronous invocation reached the
714
+ * function but the function itself failed. Lambda reports that as an HTTP 200
715
+ * carrying a function error marker, so the SDK does not throw.
716
+ *
717
+ * `functionError` is the SDK's marker (`Handled` or `Unhandled`).
718
+ * `errorType` and `errorMessage` are parsed from the response payload when it
719
+ * has the usual `{ errorType, errorMessage }` JSON shape, otherwise undefined.
720
+ *
721
+ * Deliberately excludes the raw SDK output and the stack trace: either can
722
+ * contain the caller's payload or PII.
723
+ *
724
+ * Match on `name` rather than `instanceof` if both the CJS and ESM builds of
725
+ * this package may be loaded in one process.
726
+ */
727
+ class LambdaFunctionError extends Error {
728
+ functionName;
729
+ functionError;
730
+ name = 'LambdaFunctionError';
731
+ errorType;
732
+ errorMessage;
733
+ constructor(functionName, functionError, payload) {
734
+ super(`Lambda function ${functionName ?? '(unnamed)'} failed (${functionError})`);
735
+ this.functionName = functionName;
736
+ this.functionError = functionError;
737
+ this.errorType = payload.errorType;
738
+ this.errorMessage = payload.errorMessage;
739
+ }
740
+ }
741
+ /**
742
+ * Reads `errorType` and `errorMessage` out of a function error payload.
743
+ * Anything that is not a JSON object with string fields yields undefined for
744
+ * that field rather than failing, because the payload is whatever the invoked
745
+ * function (or runtime) chose to return.
746
+ */
747
+ function parseFunctionErrorPayload(payload) {
748
+ const empty = { errorType: undefined, errorMessage: undefined };
749
+ if (payload === undefined)
750
+ return empty;
751
+ let parsed;
752
+ try {
753
+ parsed = JSON.parse(new TextDecoder().decode(payload));
754
+ }
755
+ catch {
756
+ return empty;
757
+ }
758
+ if (typeof parsed !== 'object' || parsed === null)
759
+ return empty;
760
+ const { errorType, errorMessage } = parsed;
761
+ return {
762
+ errorType: typeof errorType === 'string' ? errorType : undefined,
763
+ errorMessage: typeof errorMessage === 'string' ? errorMessage : undefined,
764
+ };
765
+ }
766
+
767
+ /**
768
+ * `Invoke` inputs carry the invocation `Payload` and the base64 `ClientContext`
769
+ * handed to the function, both of which routinely contain caller data and PII.
770
+ * Everything else identifies the target or how to call it.
771
+ */
772
+ const INVOKE_SAFE_FIELDS = [
773
+ 'FunctionName',
774
+ 'InvocationType',
775
+ 'Qualifier',
776
+ 'LogType',
777
+ 'TenantId',
778
+ ];
779
+ /**
780
+ * Wrapper around the AWS Lambda client providing structured Powertools logging
781
+ * and X-Ray tracing by default.
782
+ *
783
+ * Where a method's input carries payloads, secret material or PII, the INFO
784
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
785
+ * `TRACE`) log full SDK inputs.
786
+ *
787
+ * Covers `invoke` only.
788
+ */
789
+ class LambdaService {
790
+ client;
791
+ logger;
792
+ /**
793
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
794
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
795
+ * @param opts.client - Optional pre-configured `LambdaClient`. When
796
+ * supplied, the wrapper does not apply X-Ray instrumentation.
797
+ */
798
+ constructor(opts) {
799
+ this.client = opts?.client ?? xray.captureAWSv3Client(new LambdaClient());
800
+ this.logger = opts?.logger ?? new Logger();
801
+ }
802
+ /**
803
+ * Invoke a Lambda function. The input is the SDK input unchanged and the
804
+ * output is the SDK output unchanged: `Payload` stays a `Uint8Array` you
805
+ * decode yourself. Choose synchronous, asynchronous or dry-run invocation
806
+ * with `InvocationType`; omitting it means synchronous (`RequestResponse`).
807
+ *
808
+ * Lambda answers HTTP 200 even when the invoked function threw, flagging it
809
+ * with `FunctionError` on the response. If that marker is present this
810
+ * method warns and throws a {@link LambdaFunctionError} carrying the
811
+ * function name, the marker, and the error type and message parsed from the
812
+ * payload when it has the usual JSON shape. The raw output and the stack
813
+ * trace are deliberately left off the error.
814
+ *
815
+ * The marker only appears on synchronous responses, so the check is
816
+ * unconditional: asynchronous (`Event`) and `DryRun` responses return
817
+ * without throwing. Failures of asynchronous invocations are therefore not
818
+ * observable here; they belong to dead-letter queues and destinations on
819
+ * the invoked function. No status code check is added; service-level
820
+ * errors such as throttling are thrown by the SDK and propagate unwrapped.
821
+ *
822
+ * At INFO level the log line includes only the function name, invocation
823
+ * type, qualifier, log type and tenant id. `Payload` and `ClientContext` are
824
+ * omitted, and responses are never logged.
825
+ *
826
+ * @param input - InvokeCommandInput including FunctionName.
827
+ */
828
+ async invoke(input) {
829
+ this.logger.info('Invoking Lambda function', {
830
+ input: redactInput(this.logger, input, INVOKE_SAFE_FIELDS),
831
+ });
832
+ const output = await this.client.send(new InvokeCommand(input));
833
+ if (output.FunctionError === undefined)
834
+ return output;
835
+ this.logger.warn('Lambda invoke function error', {
836
+ functionName: input.FunctionName,
837
+ functionError: output.FunctionError,
838
+ });
839
+ throw new LambdaFunctionError(input.FunctionName, output.FunctionError, parseFunctionErrorPayload(output.Payload));
840
+ }
841
+ }
600
842
 
601
843
  const DEFAULT_PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
602
844
  const DELETE_OBJECTS_BATCH_LIMIT = 1000;
@@ -899,8 +1141,9 @@ function stripTargetInput(input) {
899
1141
  * `TRACE`) log full SDK inputs.
900
1142
  *
901
1143
  * Covers CRUD on schedules and their groups. Named `SchedulerService` (not
902
- * `EventBridgeSchedulerService`) so it doesn't collide with a future wrapper
903
- * over the separate EventBridge bus/rules API (`@aws-sdk/client-eventbridge`).
1144
+ * `EventBridgeSchedulerService`) so it doesn't collide with `EventBridgeService`,
1145
+ * the wrapper over the separate EventBridge bus/rules API
1146
+ * (`@aws-sdk/client-eventbridge`).
904
1147
  *
905
1148
  * `FlexibleTimeWindow` is required by `CreateSchedule` and is passed through
906
1149
  * untouched — the wrapper bakes in no default, so the caller must state their
@@ -1152,6 +1395,139 @@ class SecretsManagerService {
1152
1395
  }
1153
1396
  }
1154
1397
 
1398
+ const SEND_BULK_EMAIL_LIMIT = 50;
1399
+ /**
1400
+ * Sent entries whose result isn't `SUCCESS`, identified by their original
1401
+ * index in the caller's `BulkEmailEntries`. Walks the entries that were sent
1402
+ * rather than the results that came back, so an entry SES returned no result
1403
+ * for counts as failed instead of passing unnoticed. Only status and error are
1404
+ * copied out, never the entry, so no destination can leak.
1405
+ */
1406
+ function extractBulkEmailFailures(sentChunks, results) {
1407
+ return sentChunks.flatMap((sent, chunkIndex) => sent.flatMap((_, entryIndex) => {
1408
+ const result = results[chunkIndex]?.BulkEmailEntryResults?.[entryIndex];
1409
+ if (result?.Status === 'SUCCESS')
1410
+ return [];
1411
+ return [
1412
+ {
1413
+ id: originalIndex(chunkIndex, SEND_BULK_EMAIL_LIMIT, entryIndex),
1414
+ code: result?.Status,
1415
+ message: result?.Error ?? result?.Status ?? 'No status returned for entry',
1416
+ },
1417
+ ];
1418
+ }));
1419
+ }
1420
+ /**
1421
+ * Safe log shape for `sendEmail`. Keeps routing metadata and reduces the
1422
+ * recipients to a count; the sender and reply-to addresses, the subject, the
1423
+ * body and any template data are omitted as PII or payload. The template name
1424
+ * is operational metadata, not PII, so it is kept.
1425
+ */
1426
+ function summariseSendEmail(input) {
1427
+ const { ToAddresses, CcAddresses, BccAddresses } = input.Destination ?? {};
1428
+ return {
1429
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1430
+ ConfigurationSetName: input.ConfigurationSetName,
1431
+ EmailTags: input.EmailTags,
1432
+ EndpointId: input.EndpointId,
1433
+ TenantName: input.TenantName,
1434
+ templateName: input.Content?.Template?.TemplateName,
1435
+ recipientCount: (ToAddresses?.length ?? 0) + (CcAddresses?.length ?? 0) + (BccAddresses?.length ?? 0),
1436
+ };
1437
+ }
1438
+ /**
1439
+ * Safe log shape for `sendBulkEmail`. The entries carry destinations and
1440
+ * replacement data, and the default template data may carry PII, so they are
1441
+ * reduced to a count and the template name.
1442
+ */
1443
+ function summariseSendBulkEmail(input) {
1444
+ return {
1445
+ FromEmailAddressIdentityArn: input.FromEmailAddressIdentityArn,
1446
+ ConfigurationSetName: input.ConfigurationSetName,
1447
+ DefaultEmailTags: input.DefaultEmailTags,
1448
+ EndpointId: input.EndpointId,
1449
+ TenantName: input.TenantName,
1450
+ templateName: input.DefaultContent?.Template?.TemplateName,
1451
+ entryCount: input.BulkEmailEntries?.length ?? 0,
1452
+ };
1453
+ }
1454
+ /**
1455
+ * Wrapper around the AWS SES v2 client providing structured Powertools logging
1456
+ * and X-Ray tracing by default.
1457
+ *
1458
+ * Wraps SES v2 (`@aws-sdk/client-sesv2`), not the legacy v1 API. No defaults
1459
+ * are baked in: every send option, including `FromEmailAddress` and
1460
+ * `ConfigurationSetName`, comes from the caller.
1461
+ *
1462
+ * Where a method's input carries payloads or PII, the INFO log line omits
1463
+ * them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or `TRACE`) log full
1464
+ * SDK inputs.
1465
+ */
1466
+ class SESService {
1467
+ client;
1468
+ logger;
1469
+ /**
1470
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
1471
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
1472
+ * @param opts.client - Optional pre-configured `SESv2Client`. When supplied,
1473
+ * the wrapper does not apply X-Ray instrumentation.
1474
+ */
1475
+ constructor(opts) {
1476
+ this.client = opts?.client ?? xray.captureAWSv3Client(new SESv2Client());
1477
+ this.logger = opts?.logger ?? new Logger();
1478
+ }
1479
+ /**
1480
+ * Send a single email (Simple, Raw or Template content).
1481
+ *
1482
+ * At INFO level the log line includes only routing metadata and a
1483
+ * recipient count; see `summariseSendEmail`.
1484
+ *
1485
+ * Pass-through: SDK exceptions (`MessageRejected`, `SendingPausedException`,
1486
+ * …) propagate unwrapped.
1487
+ *
1488
+ * @returns The SDK output, including `MessageId`.
1489
+ */
1490
+ async sendEmail(input) {
1491
+ this.logger.info('Sending SES email', {
1492
+ input: redactInput(this.logger, input, summariseSendEmail),
1493
+ });
1494
+ return this.client.send(new SendEmailCommand(input));
1495
+ }
1496
+ /**
1497
+ * Send a templated email to many destinations. SES caps `SendBulkEmail`
1498
+ * at 50 entries per request, so this method auto-chunks `BulkEmailEntries`
1499
+ * and sends one request per chunk, in order. Every chunk shares the other
1500
+ * input fields.
1501
+ *
1502
+ * At INFO level the log line includes only routing metadata, the template
1503
+ * name and an entry count; see `summariseSendBulkEmail`.
1504
+ *
1505
+ * SES answers HTTP 200 even when entries fail, so every chunk is sent
1506
+ * before the outcome is judged. If any entry's `Status` isn't `SUCCESS`
1507
+ * (or SES returned no result for it), a {@link BatchOperationError} is thrown whose
1508
+ * `failed[].id` is the entry's original index in `BulkEmailEntries` as a
1509
+ * string, and whose `results` are the per-chunk outputs — so a caller can
1510
+ * retry only the failed indexes. Request-level SDK exceptions are not
1511
+ * wrapped.
1512
+ *
1513
+ * Sending is not idempotent: retrying the whole batch after a throw
1514
+ * re-sends the entries that succeeded.
1515
+ *
1516
+ * @returns One SDK output per request sent.
1517
+ */
1518
+ async sendBulkEmail(input) {
1519
+ this.logger.info('Sending SES bulk email', {
1520
+ input: redactInput(this.logger, input, summariseSendBulkEmail),
1521
+ });
1522
+ const results = [];
1523
+ const sentChunks = chunk(input.BulkEmailEntries ?? [], SEND_BULK_EMAIL_LIMIT);
1524
+ for (const entries of sentChunks) {
1525
+ results.push(await this.client.send(new SendBulkEmailCommand({ ...input, BulkEmailEntries: entries })));
1526
+ }
1527
+ return throwIfAny(this.logger, 'SES sendBulkEmail', results, extractBulkEmailFailures(sentChunks, results));
1528
+ }
1529
+ }
1530
+
1155
1531
  /**
1156
1532
  * Fields safe to log at INFO for `startExecution`. Omits `input` — the SFN
1157
1533
  * execution payload, which routinely carries PII (customer IDs, addresses,
@@ -1521,6 +1897,19 @@ class SQSService {
1521
1897
  }
1522
1898
 
1523
1899
  const GET_PARAMETERS_LIMIT = 10;
1900
+ /**
1901
+ * One failed entry per alias whose path SSM reported as invalid, so two
1902
+ * aliases sharing a missing path are both named.
1903
+ */
1904
+ function missingParameters(aliases, invalidPaths) {
1905
+ return Object.entries(aliases)
1906
+ .filter(([, path]) => invalidPaths.has(path))
1907
+ .map(([alias, path]) => ({
1908
+ id: path,
1909
+ code: 'ParameterNotFound',
1910
+ message: `Parameter not found for alias "${alias}"`,
1911
+ }));
1912
+ }
1524
1913
  /**
1525
1914
  * Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
1526
1915
  * parameter content itself).
@@ -1571,6 +1960,9 @@ class SSMService {
1571
1960
  * @param name - The parameter name (or ARN).
1572
1961
  * @returns The parameter value, or `undefined` if the parameter has no
1573
1962
  * value set.
1963
+ * @throws When the parameter does not exist (the SDK's
1964
+ * `ParameterNotFound`). {@link SSMService.getParameters} instead returns
1965
+ * `undefined` for a missing parameter unless `required` is set.
1574
1966
  */
1575
1967
  async getParameter(name) {
1576
1968
  this.logger.info('Fetching SSM parameter', { input: { name } });
@@ -1595,16 +1987,27 @@ class SSMService {
1595
1987
  * the underlying parameter names and sends one request per chunk,
1596
1988
  * merging the results before building the alias-keyed return value.
1597
1989
  *
1990
+ * Unlike {@link SSMService.getParameter}, which throws when the parameter
1991
+ * does not exist, a missing parameter here maps to `undefined` — so a
1992
+ * typo'd path surfaces later as an undefined value. Pass
1993
+ * `{ required: true }` to fail fast instead: every chunk is still sent,
1994
+ * then a {@link BatchOperationError} is thrown whose `failed` entries
1995
+ * carry each missing path as `id`, the code `ParameterNotFound`, and the
1996
+ * alias in `message`. Request-level SDK exceptions are not wrapped.
1997
+ *
1598
1998
  * @param aliases - Record mapping each desired local alias to its SSM
1599
1999
  * parameter name (or ARN).
2000
+ * @param opts.required - Throw when any requested parameter does not
2001
+ * exist. Defaults to `false`.
1600
2002
  * @returns A record keyed by the same aliases, mapping each to the
1601
- * parameter's value, or `undefined` when the parameter is missing or has
1602
- * no value.
2003
+ * parameter's value, or `undefined` when the parameter is missing (unless
2004
+ * `required` is set) or has no value.
1603
2005
  */
1604
- async getParameters(aliases) {
2006
+ async getParameters(aliases, opts) {
1605
2007
  this.logger.info('Fetching SSM parameters', { input: { aliases } });
1606
2008
  const names = Object.values(aliases);
1607
2009
  const byPath = new Map();
2010
+ const invalidPaths = new Set();
1608
2011
  for (const batch of chunk(names, GET_PARAMETERS_LIMIT)) {
1609
2012
  const response = await this.client.send(new GetParametersCommand({
1610
2013
  Names: batch,
@@ -1614,6 +2017,12 @@ class SSMService {
1614
2017
  if (parameter.Name !== undefined)
1615
2018
  byPath.set(parameter.Name, parameter.Value);
1616
2019
  }
2020
+ for (const name of response.InvalidParameters ?? [])
2021
+ invalidPaths.add(name);
2022
+ }
2023
+ if (opts?.required) {
2024
+ // No per-chunk results: the SDK output of a failed lookup adds nothing
2025
+ throwIfAny(this.logger, 'SSM getParameters', [], missingParameters(aliases, invalidPaths));
1617
2026
  }
1618
2027
  const result = {};
1619
2028
  for (const alias of Object.keys(aliases)) {
@@ -1665,4 +2074,4 @@ class SSMService {
1665
2074
  }
1666
2075
  }
1667
2076
 
1668
- export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, S3Service, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };
2077
+ export { APIGatewayService, APIGatewayV2Service, BatchOperationError, DynamoDBService, EventBridgeService, LambdaFunctionError, LambdaService, S3Service, SESService, SNSService, SQSService, SSMService, SchedulerService, SecretsManagerService, StepFunctionsService };
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/aws-wrappers",
3
- "version": "0.5.8",
3
+ "version": "0.5.10",
4
4
  "description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -47,9 +47,12 @@
47
47
  "@aws-sdk/client-api-gateway": "^3.1160.0",
48
48
  "@aws-sdk/client-apigatewayv2": "^3.1160.0",
49
49
  "@aws-sdk/client-dynamodb": "^3.1160.0",
50
+ "@aws-sdk/client-eventbridge": "^3.1160.0",
51
+ "@aws-sdk/client-lambda": "^3.1160.0",
50
52
  "@aws-sdk/client-s3": "^3.1160.0",
51
53
  "@aws-sdk/client-scheduler": "^3.1160.0",
52
54
  "@aws-sdk/client-secrets-manager": "^3.1160.0",
55
+ "@aws-sdk/client-sesv2": "^3.1160.0",
53
56
  "@aws-sdk/client-sfn": "^3.1160.0",
54
57
  "@aws-sdk/client-sns": "^3.1160.0",
55
58
  "@aws-sdk/client-sqs": "^3.1160.0",
@@ -0,0 +1,58 @@
1
+ import type { LoggerInterface } from '@aws-lambda-powertools/logger/types';
2
+ import { EventBridgeClient, PutEventsCommandInput, PutEventsCommandOutput } from '@aws-sdk/client-eventbridge';
3
+ /**
4
+ * Wrapper around the AWS EventBridge client providing structured Powertools
5
+ * logging and X-Ray tracing by default.
6
+ *
7
+ * Where a method's input carries payloads, secret material or PII, the INFO
8
+ * log line omits them; the verbose levels (`POWERTOOLS_LOG_LEVEL=DEBUG` or
9
+ * `TRACE`) log full SDK inputs.
10
+ *
11
+ * Covers `putEvents` only. Named `EventBridgeService` for the event bus API;
12
+ * schedules live in `SchedulerService`.
13
+ */
14
+ export declare class EventBridgeService {
15
+ private readonly client;
16
+ private readonly logger;
17
+ /**
18
+ * @param opts.logger - Optional Powertools logger. Defaults to `new Logger()`,
19
+ * which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
20
+ * @param opts.client - Optional pre-configured `EventBridgeClient`. When
21
+ * supplied, the wrapper does not apply X-Ray instrumentation.
22
+ */
23
+ constructor(opts?: {
24
+ logger?: LoggerInterface;
25
+ client?: EventBridgeClient;
26
+ });
27
+ /**
28
+ * Publish events to an event bus. The EventBridge API caps `PutEvents` at
29
+ * 10 entries per request, so this method auto-chunks the caller's `Entries`
30
+ * and sends one request per chunk, returning the array of outputs. The
31
+ * remaining request fields (such as `EndpointId`) are carried onto every
32
+ * chunk.
33
+ *
34
+ * Chunking is by count only. The 256 KB request size limit is not enforced
35
+ * here: a chunk that exceeds it fails at the SDK as a request-level error.
36
+ *
37
+ * Every chunk is sent before the outcome is judged. If EventBridge rejected
38
+ * any entry (it reports an error code on the result entry), a
39
+ * {@link BatchOperationError} is then thrown carrying the per-chunk results
40
+ * and the failed entries. For this method each failed entry's `id` is
41
+ * always set, to the entry's index in the caller's original `Entries` list
42
+ * across all chunks, as a string. Only `id`, `code` and `message` are
43
+ * copied out, so event detail never reaches the error.
44
+ *
45
+ * No retries are performed. Request-level SDK exceptions (throttling,
46
+ * access denied, oversize request) are not wrapped: they propagate
47
+ * unchanged and immediately, so earlier chunks may already have been
48
+ * published.
49
+ *
50
+ * At INFO level the log line includes only the endpoint id and the entry
51
+ * count, because `Detail`, `Resources` and the entries themselves are
52
+ * payload carriers.
53
+ *
54
+ * @param input - PutEventsCommandInput including Entries.
55
+ */
56
+ putEvents(input: PutEventsCommandInput): Promise<PutEventsCommandOutput[]>;
57
+ }
58
+ //# sourceMappingURL=eventbridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventbridge.d.ts","sourceRoot":"","sources":["../../../../src/eventbridge/eventbridge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EACH,iBAAiB,EAEjB,qBAAqB,EACrB,sBAAsB,EAEzB,MAAM,6BAA6B,CAAC;AAwCrC;;;;;;;;;;GAUG;AACH,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;IAEzC;;;;;OAKG;gBACS,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,eAAe,CAAC;QAAC,MAAM,CAAC,EAAE,iBAAiB,CAAA;KAAE;IAK3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACG,SAAS,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,EAAE,CAAC;CAkBnF"}
@@ -1,14 +1,18 @@
1
1
  export { APIGatewayV2Service } from './api-gateway-v2/api-gateway-v2.js';
2
2
  export { APIGatewayService } from './api-gateway/api-gateway.js';
3
3
  export { DynamoDBService } from './dynamodb/dynamodb.js';
4
+ export { EventBridgeService } from './eventbridge/eventbridge.js';
5
+ export { LambdaService } from './lambda/lambda.js';
4
6
  export { S3Service } from './s3/s3.js';
5
7
  export type { EmptyBucketPageResult } from './s3/s3.js';
6
8
  export { SchedulerService } from './scheduler/scheduler.js';
7
9
  export { SecretsManagerService } from './secrets-manager/secrets-manager.js';
10
+ export { SESService } from './ses/ses.js';
8
11
  export { StepFunctionsService } from './sfn/sfn.js';
9
12
  export { SNSService } from './sns/sns.js';
10
13
  export { SQSService } from './sqs/sqs.js';
11
14
  export { SSMService } from './ssm/ssm.js';
12
15
  export { BatchOperationError } from './util/batch-operation-error.js';
13
16
  export type { BatchFailedEntry } from './util/batch-operation-error.js';
17
+ export { LambdaFunctionError } from './util/lambda-function-error.js';
14
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,YAAY,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,YAAY,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC"}