From ddedc4d9604e78d97411e86e3d1a9f0384d5dcc4 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Thu, 12 Oct 2023 01:46:25 +0200 Subject: [PATCH] feat(commons): add esmodule support (#1735) * chore(logger): adapt logger to commons exports * feat(commons): add esmodule support * chore: address sonar findings * chore(commons): exported version * chore: fixed imports in examples * chore(parameters): fixed imports * chore(metrics): fixed imports * chore(tracer): fixed imports * chore(idempotency): fixed imports * chore(commons): test coverage * chore(batch): fix imports --- examples/cdk/functions/common/powertools.ts | 2 +- examples/cdk/functions/get-all-items.ts | 2 +- examples/cdk/functions/get-by-id.ts | 2 +- examples/cdk/functions/uuid.ts | 2 +- examples/sam/src/common/powertools.ts | 2 +- examples/sam/src/get-all-items.ts | 2 +- examples/sam/src/get-by-id.ts | 2 +- examples/sam/src/get-uuid.ts | 2 +- .../batch/tests/unit/BatchProcessor.test.ts | 6 ++-- .../tests/unit/BatchProcessorSync.test.ts | 6 ++-- .../tests/unit/processPartialResponse.test.ts | 22 +++++++----- .../unit/processPartialResponseSync.test.ts | 24 ++++++++----- .../{jest.config.js => jest.config.cjs} | 5 ++- packages/commons/package.json | 36 ++++++++++++++++--- packages/commons/src/awsSdk/index.ts | 2 -- packages/commons/src/awsSdk/utils.ts | 25 ------------- .../userAgentMiddleware.ts => awsSdkUtils.ts} | 29 ++++++++++++--- .../src/config/EnvironmentVariablesService.ts | 2 +- packages/commons/src/config/index.ts | 2 -- .../commons/src/{types/utils.ts => guards.ts} | 7 ---- packages/commons/src/index.ts | 22 +++++++----- .../src/middleware/cleanupMiddlewares.ts | 4 +-- packages/commons/src/middleware/index.ts | 2 -- .../src/samples/resources/contexts/index.ts | 2 +- .../src/samples/resources/events/index.ts | 2 +- .../lambda => types}/LambdaInterface.ts | 0 packages/commons/src/types/index.ts | 4 +++ packages/commons/src/types/json.ts | 6 ++++ packages/commons/src/utils/lambda/index.ts | 1 - .../EnvironmentVariablesService.test.ts | 4 +-- .../tests/unit/LambdaInterface.test.ts | 31 +++++++--------- packages/commons/tests/unit/Utility.test.ts | 2 +- .../{awsSdk.test.ts => awsSdkUtils.test.ts} | 9 +++-- .../tests/unit/cleanupMiddlewares.test.ts | 12 ++++++- .../unit/{utils.test.ts => guards.test.ts} | 8 ++--- packages/commons/tsconfig.esm.json | 11 ++++++ packages/commons/tsconfig.json | 2 +- .../idempotency/src/IdempotencyHandler.ts | 2 +- .../src/middleware/makeHandlerIdempotent.ts | 4 +-- .../src/persistence/BasePersistenceLayer.ts | 2 +- .../src/persistence/IdempotencyRecord.ts | 2 +- .../src/types/IdempotencyOptions.ts | 2 +- .../src/types/IdempotencyRecord.ts | 2 +- .../idempotentDecorator.test.FunctionCode.ts | 2 +- .../tests/unit/idempotencyDecorator.test.ts | 4 +-- .../tests/unit/makeHandlerIdempotent.test.ts | 10 +++--- .../tests/unit/makeIdempotent.test.ts | 10 +++--- packages/logger/jest.config.cjs | 10 ++---- packages/logger/package.json | 3 +- packages/logger/src/Logger.ts | 2 +- packages/logger/src/index.ts | 4 +-- packages/logger/src/middleware/middy.ts | 4 +-- packages/logger/src/types/Logger.ts | 4 +-- .../sampleRate.decorator.test.FunctionCode.ts | 2 +- packages/logger/tests/unit/Logger.test.ts | 7 ++-- .../tests/unit/middleware/middy.test.ts | 2 +- packages/metrics/src/middleware/middy.ts | 4 +-- packages/metrics/src/types/Metrics.ts | 2 +- .../metrics/tests/helpers/metricsUtils.ts | 2 +- packages/metrics/tests/unit/Metrics.test.ts | 2 +- .../tests/unit/middleware/middy.test.ts | 14 ++++---- .../parameters/src/base/transformValue.ts | 2 +- .../src/dynamodb/DynamoDBProvider.ts | 2 +- .../parameters/src/types/AppConfigProvider.ts | 2 +- .../parameters/src/types/DynamoDBProvider.ts | 2 +- packages/parameters/src/types/SSMProvider.ts | 2 +- .../parameters/src/types/SecretsProvider.ts | 2 +- .../tests/unit/getAppConfig.test.ts | 2 +- packages/tracer/src/Tracer.ts | 10 +++--- packages/tracer/src/middleware/middy.ts | 4 +-- packages/tracer/src/types/Tracer.ts | 2 +- packages/tracer/tests/unit/Tracer.test.ts | 2 +- packages/tracer/tests/unit/middy.test.ts | 2 +- 73 files changed, 248 insertions(+), 192 deletions(-) rename packages/commons/{jest.config.js => jest.config.cjs} (83%) delete mode 100644 packages/commons/src/awsSdk/index.ts delete mode 100644 packages/commons/src/awsSdk/utils.ts rename packages/commons/src/{awsSdk/userAgentMiddleware.ts => awsSdkUtils.ts} (63%) delete mode 100644 packages/commons/src/config/index.ts rename packages/commons/src/{types/utils.ts => guards.ts} (81%) delete mode 100644 packages/commons/src/middleware/index.ts rename packages/commons/src/{utils/lambda => types}/LambdaInterface.ts (100%) create mode 100644 packages/commons/src/types/index.ts create mode 100644 packages/commons/src/types/json.ts delete mode 100644 packages/commons/src/utils/lambda/index.ts rename packages/commons/tests/unit/{config => }/EnvironmentVariablesService.test.ts (98%) rename packages/commons/tests/unit/{awsSdk.test.ts => awsSdkUtils.test.ts} (94%) rename packages/commons/tests/unit/{utils.test.ts => guards.test.ts} (95%) create mode 100644 packages/commons/tsconfig.esm.json diff --git a/examples/cdk/functions/common/powertools.ts b/examples/cdk/functions/common/powertools.ts index 01949a91ac..fa0b798afa 100644 --- a/examples/cdk/functions/common/powertools.ts +++ b/examples/cdk/functions/common/powertools.ts @@ -1,7 +1,7 @@ import { Logger } from '@aws-lambda-powertools/logger'; import { Metrics } from '@aws-lambda-powertools/metrics'; import { Tracer } from '@aws-lambda-powertools/tracer'; -import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version'; +import { PT_VERSION } from '@aws-lambda-powertools/commons'; const defaultValues = { region: process.env.AWS_REGION || 'N/A', diff --git a/examples/cdk/functions/get-all-items.ts b/examples/cdk/functions/get-all-items.ts index 7fe222d773..77be4ae4d8 100644 --- a/examples/cdk/functions/get-all-items.ts +++ b/examples/cdk/functions/get-all-items.ts @@ -1,4 +1,4 @@ -import { injectLambdaContext } from '@aws-lambda-powertools/logger'; +import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'; import { logMetrics } from '@aws-lambda-powertools/metrics'; import { captureLambdaHandler } from '@aws-lambda-powertools/tracer'; import { ScanCommand } from '@aws-sdk/lib-dynamodb'; diff --git a/examples/cdk/functions/get-by-id.ts b/examples/cdk/functions/get-by-id.ts index 88e76511a1..f35c053eef 100644 --- a/examples/cdk/functions/get-by-id.ts +++ b/examples/cdk/functions/get-by-id.ts @@ -1,4 +1,4 @@ -import { LambdaInterface } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; import { GetCommand } from '@aws-sdk/lib-dynamodb'; import { APIGatewayProxyEvent, diff --git a/examples/cdk/functions/uuid.ts b/examples/cdk/functions/uuid.ts index 58e017dbea..04ab559e1f 100644 --- a/examples/cdk/functions/uuid.ts +++ b/examples/cdk/functions/uuid.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; -exports.handler = async (_event) => { +exports.handler = async () => { return { statusCode: 200, body: JSON.stringify(randomUUID()), diff --git a/examples/sam/src/common/powertools.ts b/examples/sam/src/common/powertools.ts index 01949a91ac..fa0b798afa 100644 --- a/examples/sam/src/common/powertools.ts +++ b/examples/sam/src/common/powertools.ts @@ -1,7 +1,7 @@ import { Logger } from '@aws-lambda-powertools/logger'; import { Metrics } from '@aws-lambda-powertools/metrics'; import { Tracer } from '@aws-lambda-powertools/tracer'; -import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version'; +import { PT_VERSION } from '@aws-lambda-powertools/commons'; const defaultValues = { region: process.env.AWS_REGION || 'N/A', diff --git a/examples/sam/src/get-all-items.ts b/examples/sam/src/get-all-items.ts index a43b3f3c1e..aea7b4a817 100644 --- a/examples/sam/src/get-all-items.ts +++ b/examples/sam/src/get-all-items.ts @@ -7,7 +7,7 @@ import middy from '@middy/core'; import { tableName } from './common/constants'; import { logger, tracer, metrics } from './common/powertools'; import { logMetrics } from '@aws-lambda-powertools/metrics'; -import { injectLambdaContext } from '@aws-lambda-powertools/logger'; +import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'; import { captureLambdaHandler } from '@aws-lambda-powertools/tracer'; import { docClient } from './common/dynamodb-client'; import { ScanCommand } from '@aws-sdk/lib-dynamodb'; diff --git a/examples/sam/src/get-by-id.ts b/examples/sam/src/get-by-id.ts index 88e76511a1..f35c053eef 100644 --- a/examples/sam/src/get-by-id.ts +++ b/examples/sam/src/get-by-id.ts @@ -1,4 +1,4 @@ -import { LambdaInterface } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; import { GetCommand } from '@aws-sdk/lib-dynamodb'; import { APIGatewayProxyEvent, diff --git a/examples/sam/src/get-uuid.ts b/examples/sam/src/get-uuid.ts index 58e017dbea..04ab559e1f 100644 --- a/examples/sam/src/get-uuid.ts +++ b/examples/sam/src/get-uuid.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; -exports.handler = async (_event) => { +exports.handler = async () => { return { statusCode: 200, body: JSON.stringify(randomUUID()), diff --git a/packages/batch/tests/unit/BatchProcessor.test.ts b/packages/batch/tests/unit/BatchProcessor.test.ts index 99cb2245e5..3243c1a4a0 100644 --- a/packages/batch/tests/unit/BatchProcessor.test.ts +++ b/packages/batch/tests/unit/BatchProcessor.test.ts @@ -4,7 +4,7 @@ * @group unit/batch/class/asyncBatchProcessor */ import type { Context } from 'aws-lambda'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; +import { ContextExamples as dummyContext } from '@aws-lambda-powertools/commons'; import { BatchProcessor } from '../../src/BatchProcessor'; import { EventType } from '../../src/constants'; import { BatchProcessingError, FullBatchFailureError } from '../../src/errors'; @@ -23,7 +23,9 @@ import { describe('Class: AsyncBatchProcessor', () => { const ENVIRONMENT_VARIABLES = process.env; - const options: BatchProcessingOptions = { context: dummyContext }; + const options: BatchProcessingOptions = { + context: dummyContext.helloworldContext, + }; beforeEach(() => { jest.clearAllMocks(); diff --git a/packages/batch/tests/unit/BatchProcessorSync.test.ts b/packages/batch/tests/unit/BatchProcessorSync.test.ts index 4f77d299cc..506e192d02 100644 --- a/packages/batch/tests/unit/BatchProcessorSync.test.ts +++ b/packages/batch/tests/unit/BatchProcessorSync.test.ts @@ -4,7 +4,7 @@ * @group unit/batch/class/batchprocessor */ import type { Context } from 'aws-lambda'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; +import { ContextExamples as dummyContext } from '@aws-lambda-powertools/commons'; import { BatchProcessorSync } from '../../src/BatchProcessorSync'; import { EventType } from '../../src/constants'; import { BatchProcessingError, FullBatchFailureError } from '../../src/errors'; @@ -23,7 +23,9 @@ import { describe('Class: BatchProcessor', () => { const ENVIRONMENT_VARIABLES = process.env; - const options: BatchProcessingOptions = { context: dummyContext }; + const options: BatchProcessingOptions = { + context: dummyContext.helloworldContext, + }; beforeEach(() => { jest.clearAllMocks(); diff --git a/packages/batch/tests/unit/processPartialResponse.test.ts b/packages/batch/tests/unit/processPartialResponse.test.ts index 2dbe585b45..d344eb7883 100644 --- a/packages/batch/tests/unit/processPartialResponse.test.ts +++ b/packages/batch/tests/unit/processPartialResponse.test.ts @@ -9,8 +9,10 @@ import type { KinesisStreamEvent, SQSEvent, } from 'aws-lambda'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; -import { Custom as dummyEvent } from '@aws-lambda-powertools/commons/lib/samples/resources/events'; +import { + ContextExamples as dummyContext, + Events as dummyEvent, +} from '@aws-lambda-powertools/commons'; import { BatchProcessor } from '../../src/BatchProcessor'; import { processPartialResponse } from '../../src/processPartialResponse'; import { EventType } from '../../src/constants'; @@ -33,7 +35,9 @@ import { describe('Function: processPartialResponse()', () => { const ENVIRONMENT_VARIABLES = process.env; const context = dummyContext; - const options: BatchProcessingOptions = { context: dummyContext }; + const options: BatchProcessingOptions = { + context: dummyContext.helloworldContext, + }; beforeEach(() => { jest.clearAllMocks(); @@ -106,7 +110,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = await handler(event, context); + const result = await handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -133,7 +137,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = await handler(event, context); + const result = await handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -160,7 +164,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = await handler(event, context); + const result = await handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -169,7 +173,7 @@ describe('Function: processPartialResponse()', () => { test('Process partial response through handler for SQS records with incorrect event type', async () => { // Prepare const processor = new BatchProcessor(EventType.SQS); - const event = dummyEvent; + const event = dummyEvent.Custom; const handler = async ( event: SQSEvent, @@ -184,7 +188,7 @@ describe('Function: processPartialResponse()', () => { // Act & Assess await expect(() => - handler(event as unknown as SQSEvent, context) + handler(event as unknown as SQSEvent, context.helloworldContext) ).rejects.toThrowError( `Unexpected batch type. Possible values are: ${Object.keys( EventType @@ -216,7 +220,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = await handler(event, context); + const result = await handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); diff --git a/packages/batch/tests/unit/processPartialResponseSync.test.ts b/packages/batch/tests/unit/processPartialResponseSync.test.ts index 4c3e9a47a5..426428f5d4 100644 --- a/packages/batch/tests/unit/processPartialResponseSync.test.ts +++ b/packages/batch/tests/unit/processPartialResponseSync.test.ts @@ -9,8 +9,10 @@ import type { KinesisStreamEvent, SQSEvent, } from 'aws-lambda'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; -import { Custom as dummyEvent } from '@aws-lambda-powertools/commons/lib/samples/resources/events'; +import { + ContextExamples as dummyContext, + Events as dummyEvent, +} from '@aws-lambda-powertools/commons'; import { BatchProcessorSync } from '../../src/BatchProcessorSync'; import { processPartialResponseSync } from '../../src/processPartialResponseSync'; import { EventType } from '../../src/constants'; @@ -33,7 +35,9 @@ import { describe('Function: processPartialResponse()', () => { const ENVIRONMENT_VARIABLES = process.env; const context = dummyContext; - const options: BatchProcessingOptions = { context: dummyContext }; + const options: BatchProcessingOptions = { + context: dummyContext.helloworldContext, + }; beforeEach(() => { jest.clearAllMocks(); @@ -106,7 +110,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = handler(event, context); + const result = handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -133,7 +137,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = handler(event, context); + const result = handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -160,7 +164,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = handler(event, context); + const result = handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); @@ -169,7 +173,7 @@ describe('Function: processPartialResponse()', () => { test('Process partial response through handler for SQS records with incorrect event type', () => { // Prepare const processor = new BatchProcessorSync(EventType.SQS); - const event = dummyEvent; + const event = dummyEvent.Custom; const handler = ( event: SQSEvent, @@ -179,7 +183,9 @@ describe('Function: processPartialResponse()', () => { }; // Act & Assess - expect(() => handler(event as unknown as SQSEvent, context)).toThrowError( + expect(() => + handler(event as unknown as SQSEvent, context.helloworldContext) + ).toThrowError( `Unexpected batch type. Possible values are: ${Object.keys( EventType ).join(', ')}` @@ -210,7 +216,7 @@ describe('Function: processPartialResponse()', () => { }; // Act - const result = handler(event, context); + const result = handler(event, context.helloworldContext); // Assess expect(result).toStrictEqual({ batchItemFailures: [] }); diff --git a/packages/commons/jest.config.js b/packages/commons/jest.config.cjs similarity index 83% rename from packages/commons/jest.config.js rename to packages/commons/jest.config.cjs index 512b4ab601..957bbe96d7 100644 --- a/packages/commons/jest.config.js +++ b/packages/commons/jest.config.cjs @@ -4,6 +4,9 @@ module.exports = { color: 'red', }, preset: 'ts-jest', + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, transform: { '^.+\\.ts?$': 'ts-jest', }, @@ -13,7 +16,7 @@ module.exports = { roots: ['/src', '/tests'], testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', - coveragePathIgnorePatterns: ['/node_modules/'], + coveragePathIgnorePatterns: ['/node_modules/', 'src/types/index.ts'], coverageThreshold: { global: { statements: 100, diff --git a/packages/commons/package.json b/packages/commons/package.json index 7c29effb74..8f2c5d4cb4 100644 --- a/packages/commons/package.json +++ b/packages/commons/package.json @@ -16,19 +16,45 @@ "test:e2e": "echo 'Not Applicable'", "watch": "jest --watch", "generateVersionFile": "echo \"// this file is auto generated, do not modify\nexport const PT_VERSION = '$(jq -r '.version' package.json)';\" > src/version.ts", - "build": "tsc --build --force", + "build:cjs": "tsc --build --force && echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json", + "build:esm": "tsc --project tsconfig.esm.json && echo '{ \"type\": \"module\" }' > lib/esm/package.json", + "build": "npm run build:esm & npm run build:cjs", "lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .", "lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .", - "prebuild": "rimraf ./lib", - "prepack": "node ../../.github/scripts/release_patch_package_json.js ." + "prepack": "rimraf ./lib/*.tsbuildinfo && node ../../.github/scripts/release_patch_package_json.js ." }, "lint-staged": { "*.{js,ts}": "npm run lint-fix" }, "homepage": "https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/packages/metrics#readme", "license": "MIT-0", - "main": "./lib/index.js", - "types": "./lib/index.d.ts", + "type": "module", + "exports": { + ".": { + "require": { + "types": "./lib/cjs/index.d.ts", + "default": "./lib/cjs/index.js" + }, + "import": { + "types": "./lib/esm/index.d.ts", + "default": "./lib/esm/index.js" + } + }, + "./types": { + "import": "./lib/esm/types/index.js", + "require": "./lib/cjs/types/index.js" + } + }, + "typesVersions": { + "*": { + "types": [ + "lib/cjs/types/index.d.ts", + "lib/esm/types/index.d.ts" + ] + } + }, + "types": "./lib/cjs/index.d.ts", + "main": "./lib/cjs/index.js", "files": [ "lib" ], diff --git a/packages/commons/src/awsSdk/index.ts b/packages/commons/src/awsSdk/index.ts deleted file mode 100644 index 6a771c2265..0000000000 --- a/packages/commons/src/awsSdk/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { addUserAgentMiddleware } from './userAgentMiddleware'; -export { isSdkClient } from './utils'; diff --git a/packages/commons/src/awsSdk/utils.ts b/packages/commons/src/awsSdk/utils.ts deleted file mode 100644 index 611525abe1..0000000000 --- a/packages/commons/src/awsSdk/utils.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SdkClient } from '../types/awsSdk'; - -/** - * @internal - * Type guard to check if the client provided is a valid AWS SDK v3 client - */ -const isSdkClient = (client: unknown): client is SdkClient => - typeof client === 'object' && - client !== null && - 'send' in client && - typeof client.send === 'function' && - 'config' in client && - client.config !== undefined && - typeof client.config === 'object' && - client.config !== null && - 'middlewareStack' in client && - client.middlewareStack !== undefined && - typeof client.middlewareStack === 'object' && - client.middlewareStack !== null && - 'identify' in client.middlewareStack && - typeof client.middlewareStack.identify === 'function' && - 'addRelativeTo' in client.middlewareStack && - typeof client.middlewareStack.addRelativeTo === 'function'; - -export { isSdkClient }; diff --git a/packages/commons/src/awsSdk/userAgentMiddleware.ts b/packages/commons/src/awsSdkUtils.ts similarity index 63% rename from packages/commons/src/awsSdk/userAgentMiddleware.ts rename to packages/commons/src/awsSdkUtils.ts index fe50e12571..29095c3d37 100644 --- a/packages/commons/src/awsSdk/userAgentMiddleware.ts +++ b/packages/commons/src/awsSdkUtils.ts @@ -1,6 +1,5 @@ -import { PT_VERSION } from '../version'; -import { isSdkClient } from './utils'; -import type { MiddlewareArgsLike } from '../types/awsSdk'; +import { PT_VERSION } from './version.js'; +import type { MiddlewareArgsLike, SdkClient } from './types/awsSdk.js'; /** * @internal @@ -13,6 +12,28 @@ const middlewareOptions = { tags: ['POWERTOOLS', 'USER_AGENT'], }; +/** + * @internal + * Type guard to check if the client provided is a valid AWS SDK v3 client + */ +const isSdkClient = (client: unknown): client is SdkClient => + typeof client === 'object' && + client !== null && + 'send' in client && + typeof client.send === 'function' && + 'config' in client && + client.config !== undefined && + typeof client.config === 'object' && + client.config !== null && + 'middlewareStack' in client && + client.middlewareStack !== undefined && + typeof client.middlewareStack === 'object' && + client.middlewareStack !== null && + 'identify' in client.middlewareStack && + typeof client.middlewareStack.identify === 'function' && + 'addRelativeTo' in client.middlewareStack && + typeof client.middlewareStack.addRelativeTo === 'function'; + /** * @internal * returns a middleware function for the MiddlewareStack, that can be used for the SDK clients @@ -64,4 +85,4 @@ const addUserAgentMiddleware = (client: unknown, feature: string): void => { } }; -export { customUserAgentMiddleware, addUserAgentMiddleware }; +export { customUserAgentMiddleware, addUserAgentMiddleware, isSdkClient }; diff --git a/packages/commons/src/config/EnvironmentVariablesService.ts b/packages/commons/src/config/EnvironmentVariablesService.ts index f222fccfb8..f0f76df291 100644 --- a/packages/commons/src/config/EnvironmentVariablesService.ts +++ b/packages/commons/src/config/EnvironmentVariablesService.ts @@ -1,4 +1,4 @@ -import { ConfigService } from './ConfigService'; +import { ConfigService } from './ConfigService.js'; /** * Class EnvironmentVariablesService diff --git a/packages/commons/src/config/index.ts b/packages/commons/src/config/index.ts deleted file mode 100644 index 1530e49ebf..0000000000 --- a/packages/commons/src/config/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './ConfigService'; -export * from './EnvironmentVariablesService'; diff --git a/packages/commons/src/types/utils.ts b/packages/commons/src/guards.ts similarity index 81% rename from packages/commons/src/types/utils.ts rename to packages/commons/src/guards.ts index 7da5fd17ab..7776280e8b 100644 --- a/packages/commons/src/types/utils.ts +++ b/packages/commons/src/guards.ts @@ -50,10 +50,3 @@ const isString = (value: unknown): value is string => { }; export { isRecord, isString, isTruthy, isNullOrUndefined }; - -type JSONPrimitive = string | number | boolean | null | undefined; -type JSONValue = JSONPrimitive | JSONObject | JSONArray; -type JSONObject = { [key: number | string]: JSONValue }; -type JSONArray = Array; - -export type { JSONPrimitive, JSONValue, JSONObject, JSONArray }; diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts index 0549592bf2..f6ff7df34e 100644 --- a/packages/commons/src/index.ts +++ b/packages/commons/src/index.ts @@ -1,8 +1,14 @@ -export * from './utils/lambda'; -export * from './Utility'; -export * from './config'; -export * as ContextExamples from './samples/resources/contexts'; -export * as Events from './samples/resources/events'; -export * from './types/middy'; -export * from './types/utils'; -export * from './awsSdk'; +export { isRecord, isString, isTruthy, isNullOrUndefined } from './guards.js'; +export { Utility } from './Utility.js'; +export { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js'; +export * as ContextExamples from './samples/resources/contexts/index.js'; +export * as Events from './samples/resources/events/index.js'; +export { addUserAgentMiddleware, isSdkClient } from './awsSdkUtils.js'; +export { cleanupMiddlewares } from './middleware/cleanupMiddlewares.js'; +export { + TRACER_KEY, + LOGGER_KEY, + METRICS_KEY, + IDEMPOTENCY_KEY, +} from './middleware/constants.js'; +export { PT_VERSION } from './version.js'; diff --git a/packages/commons/src/middleware/cleanupMiddlewares.ts b/packages/commons/src/middleware/cleanupMiddlewares.ts index e35719b9d7..4f1046e6f1 100644 --- a/packages/commons/src/middleware/cleanupMiddlewares.ts +++ b/packages/commons/src/middleware/cleanupMiddlewares.ts @@ -3,8 +3,8 @@ import { METRICS_KEY, LOGGER_KEY, IDEMPOTENCY_KEY, -} from './constants'; -import type { MiddyLikeRequest, CleanupFunction } from '../types/middy'; +} from './constants.js'; +import type { MiddyLikeRequest, CleanupFunction } from '../types/middy.js'; // Typeguard to assert that an object is of Function type const isFunction = (obj: unknown): obj is CleanupFunction => { diff --git a/packages/commons/src/middleware/index.ts b/packages/commons/src/middleware/index.ts deleted file mode 100644 index 85f7388af3..0000000000 --- a/packages/commons/src/middleware/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './cleanupMiddlewares'; -export * from './constants'; diff --git a/packages/commons/src/samples/resources/contexts/index.ts b/packages/commons/src/samples/resources/contexts/index.ts index 436927eee2..910f356d2c 100644 --- a/packages/commons/src/samples/resources/contexts/index.ts +++ b/packages/commons/src/samples/resources/contexts/index.ts @@ -1 +1 @@ -export * from './hello-world'; +export * from './hello-world.js'; diff --git a/packages/commons/src/samples/resources/events/index.ts b/packages/commons/src/samples/resources/events/index.ts index 45582e4428..94b087e514 100644 --- a/packages/commons/src/samples/resources/events/index.ts +++ b/packages/commons/src/samples/resources/events/index.ts @@ -1 +1 @@ -export * as Custom from './custom'; +export * as Custom from './custom/index.js'; diff --git a/packages/commons/src/utils/lambda/LambdaInterface.ts b/packages/commons/src/types/LambdaInterface.ts similarity index 100% rename from packages/commons/src/utils/lambda/LambdaInterface.ts rename to packages/commons/src/types/LambdaInterface.ts diff --git a/packages/commons/src/types/index.ts b/packages/commons/src/types/index.ts new file mode 100644 index 0000000000..a3f660eeda --- /dev/null +++ b/packages/commons/src/types/index.ts @@ -0,0 +1,4 @@ +export * from './middy.js'; +export * from './awsSdk.js'; +export * from './json.js'; +export * from './LambdaInterface.js'; diff --git a/packages/commons/src/types/json.ts b/packages/commons/src/types/json.ts new file mode 100644 index 0000000000..765491c699 --- /dev/null +++ b/packages/commons/src/types/json.ts @@ -0,0 +1,6 @@ +type JSONPrimitive = string | number | boolean | null | undefined; +type JSONValue = JSONPrimitive | JSONObject | JSONArray; +type JSONObject = { [key: number | string]: JSONValue }; +type JSONArray = Array; + +export type { JSONPrimitive, JSONValue, JSONObject, JSONArray }; diff --git a/packages/commons/src/utils/lambda/index.ts b/packages/commons/src/utils/lambda/index.ts deleted file mode 100644 index f57f966d0c..0000000000 --- a/packages/commons/src/utils/lambda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './LambdaInterface'; diff --git a/packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts b/packages/commons/tests/unit/EnvironmentVariablesService.test.ts similarity index 98% rename from packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts rename to packages/commons/tests/unit/EnvironmentVariablesService.test.ts index b1e90b6b08..8a5bec93e8 100644 --- a/packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts +++ b/packages/commons/tests/unit/EnvironmentVariablesService.test.ts @@ -1,10 +1,10 @@ /** * Test EnvironmentVariablesService class * - * @group unit/commons/all + * @group unit/commons/environmentService */ -import { EnvironmentVariablesService } from '../../../src/config'; +import { EnvironmentVariablesService } from '../../src/index.js'; describe('Class: EnvironmentVariablesService', () => { const ENVIRONMENT_VARIABLES = process.env; diff --git a/packages/commons/tests/unit/LambdaInterface.test.ts b/packages/commons/tests/unit/LambdaInterface.test.ts index 52049aadc0..376d35bf52 100644 --- a/packages/commons/tests/unit/LambdaInterface.test.ts +++ b/packages/commons/tests/unit/LambdaInterface.test.ts @@ -5,14 +5,15 @@ */ import { Handler } from 'aws-lambda'; import { Callback, Context } from 'aws-lambda'; -import { - ContextExamples, +import { helloworldContext as context } from '../../src/samples/resources/contexts/hello-world'; +import type { SyncHandler, AsyncHandler, LambdaInterface, -} from '../../src'; +} from '../../src/types/index.js'; describe('LambdaInterface with arrow function', () => { + jest.spyOn(console, 'log').mockImplementation(); test('it compiles when given a callback', async () => { class LambdaFunction implements LambdaInterface { public handler: SyncHandler = async ( @@ -28,10 +29,8 @@ describe('LambdaInterface with arrow function', () => { }; } - await new LambdaFunction().handler( - {}, - ContextExamples.helloworldContext, - () => console.log('Lambda invoked!') + new LambdaFunction().handler({}, context, () => + console.log('Lambda invoked!') ); }); @@ -45,7 +44,7 @@ describe('LambdaInterface with arrow function', () => { }; } - await new LambdaFunction().handler({}, ContextExamples.helloworldContext); + await new LambdaFunction().handler({}, context); }); }); @@ -62,10 +61,8 @@ describe('LambdaInterface with standard function', () => { } } - await new LambdaFunction().handler( - {}, - ContextExamples.helloworldContext, - () => console.log('Lambda invoked!') + new LambdaFunction().handler({}, context, () => + console.log('Lambda invoked!') ); }); @@ -80,7 +77,7 @@ describe('LambdaInterface with standard function', () => { } } - await new LambdaFunction().handler({}, ContextExamples.helloworldContext); + await new LambdaFunction().handler({}, context); }); }); @@ -138,7 +135,7 @@ describe('LambdaInterface with decorator', () => { } } - await new LambdaFunction().handler({}, ContextExamples.helloworldContext); + await new LambdaFunction().handler({}, context); }); test('decorator with callback compile', async () => { @@ -154,10 +151,8 @@ describe('LambdaInterface with decorator', () => { } } - await new LambdaFunction().handler( - {}, - ContextExamples.helloworldContext, - () => console.log('Lambda invoked!') + new LambdaFunction().handler({}, context, () => + console.log('Lambda invoked!') ); }); }); diff --git a/packages/commons/tests/unit/Utility.test.ts b/packages/commons/tests/unit/Utility.test.ts index f289d15d85..9e9d18194e 100644 --- a/packages/commons/tests/unit/Utility.test.ts +++ b/packages/commons/tests/unit/Utility.test.ts @@ -3,7 +3,7 @@ * * @group unit/commons/utility */ -import { Utility } from '../../src'; +import { Utility } from '../../src/index.js'; describe('Class: Utility', () => { beforeEach(() => { diff --git a/packages/commons/tests/unit/awsSdk.test.ts b/packages/commons/tests/unit/awsSdkUtils.test.ts similarity index 94% rename from packages/commons/tests/unit/awsSdk.test.ts rename to packages/commons/tests/unit/awsSdkUtils.test.ts index 4ec4a75b99..0a2e4c6cd7 100644 --- a/packages/commons/tests/unit/awsSdk.test.ts +++ b/packages/commons/tests/unit/awsSdkUtils.test.ts @@ -1,6 +1,9 @@ -import { addUserAgentMiddleware, isSdkClient } from '../../src/awsSdk'; -import { PT_VERSION as version } from '../../src/version'; -import { customUserAgentMiddleware } from '../../src/awsSdk/userAgentMiddleware'; +import { + addUserAgentMiddleware, + isSdkClient, + PT_VERSION as version, +} from '../../src/index.js'; +import { customUserAgentMiddleware } from '../../src/awsSdkUtils.js'; describe('Helpers: awsSdk', () => { describe('Function: userAgentMiddleware', () => { diff --git a/packages/commons/tests/unit/cleanupMiddlewares.test.ts b/packages/commons/tests/unit/cleanupMiddlewares.test.ts index 12583d9107..c3f92f965f 100644 --- a/packages/commons/tests/unit/cleanupMiddlewares.test.ts +++ b/packages/commons/tests/unit/cleanupMiddlewares.test.ts @@ -7,7 +7,9 @@ import { cleanupMiddlewares, TRACER_KEY, METRICS_KEY, -} from '../../src/middleware'; + LOGGER_KEY, + IDEMPOTENCY_KEY, +} from '../../src/index.js'; import { helloworldContext as context } from '../../src/samples/resources/contexts/hello-world'; describe('Function: cleanupMiddlewares', () => { @@ -15,6 +17,8 @@ describe('Function: cleanupMiddlewares', () => { // Prepare const mockCleanupFunction1 = jest.fn(); const mockCleanupFunction2 = jest.fn(); + const mockCleanupFunction3 = jest.fn(); + const mockCleanupFunction4 = jest.fn(); const mockRequest = { event: {}, context: context, @@ -23,6 +27,8 @@ describe('Function: cleanupMiddlewares', () => { internal: { [TRACER_KEY]: mockCleanupFunction1, [METRICS_KEY]: mockCleanupFunction2, + [LOGGER_KEY]: mockCleanupFunction3, + [IDEMPOTENCY_KEY]: mockCleanupFunction4, }, }; @@ -34,6 +40,10 @@ describe('Function: cleanupMiddlewares', () => { expect(mockCleanupFunction1).toHaveBeenCalledWith(mockRequest); expect(mockCleanupFunction2).toHaveBeenCalledTimes(1); expect(mockCleanupFunction2).toHaveBeenCalledWith(mockRequest); + expect(mockCleanupFunction3).toHaveBeenCalledTimes(1); + expect(mockCleanupFunction3).toHaveBeenCalledWith(mockRequest); + expect(mockCleanupFunction4).toHaveBeenCalledTimes(1); + expect(mockCleanupFunction4).toHaveBeenCalledWith(mockRequest); }); it('resolves successfully if no cleanup function is present', async () => { // Prepare diff --git a/packages/commons/tests/unit/utils.test.ts b/packages/commons/tests/unit/guards.test.ts similarity index 95% rename from packages/commons/tests/unit/utils.test.ts rename to packages/commons/tests/unit/guards.test.ts index 464b05958f..53e248e643 100644 --- a/packages/commons/tests/unit/utils.test.ts +++ b/packages/commons/tests/unit/guards.test.ts @@ -1,16 +1,16 @@ /** - * Test utils functions + * Test guards functions * - * @group unit/commons/utils + * @group unit/commons/guards */ import { isRecord, isTruthy, isNullOrUndefined, isString, -} from '../../src/types/utils'; +} from '../../src/index.js'; -describe('Functions: utils', () => { +describe('Functions: guards', () => { beforeEach(() => { jest.clearAllMocks(); jest.resetModules(); diff --git a/packages/commons/tsconfig.esm.json b/packages/commons/tsconfig.esm.json new file mode 100644 index 0000000000..9bed8e4da4 --- /dev/null +++ b/packages/commons/tsconfig.esm.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.esm.json", + "compilerOptions": { + "baseUrl": ".", + "outDir": "./lib/esm", + "rootDir": "./src" + }, + "include": [ + "./src/**/*" + ] +} \ No newline at end of file diff --git a/packages/commons/tsconfig.json b/packages/commons/tsconfig.json index 1cb9d72773..5be842b9f8 100644 --- a/packages/commons/tsconfig.json +++ b/packages/commons/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "outDir": "./lib", + "outDir": "./lib/cjs/", "rootDir": "./src", }, "include": [ diff --git a/packages/idempotency/src/IdempotencyHandler.ts b/packages/idempotency/src/IdempotencyHandler.ts index 0808edf999..50facddb08 100644 --- a/packages/idempotency/src/IdempotencyHandler.ts +++ b/packages/idempotency/src/IdempotencyHandler.ts @@ -1,7 +1,7 @@ import type { JSONValue, MiddyLikeRequest, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; import type { AnyFunction, IdempotencyHandlerOptions } from './types'; import { IdempotencyAlreadyInProgressError, diff --git a/packages/idempotency/src/middleware/makeHandlerIdempotent.ts b/packages/idempotency/src/middleware/makeHandlerIdempotent.ts index 25c4525f58..55edb314dc 100644 --- a/packages/idempotency/src/middleware/makeHandlerIdempotent.ts +++ b/packages/idempotency/src/middleware/makeHandlerIdempotent.ts @@ -3,13 +3,13 @@ import { IdempotencyConfig } from '../IdempotencyConfig'; import { cleanupMiddlewares, IDEMPOTENCY_KEY, -} from '@aws-lambda-powertools/commons/lib/middleware'; +} from '@aws-lambda-powertools/commons'; import type { AnyFunction, IdempotencyLambdaHandlerOptions } from '../types'; import type { MiddlewareLikeObj, MiddyLikeRequest, JSONValue, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; /** * @internal diff --git a/packages/idempotency/src/persistence/BasePersistenceLayer.ts b/packages/idempotency/src/persistence/BasePersistenceLayer.ts index 108a7c0adf..96b05fb657 100644 --- a/packages/idempotency/src/persistence/BasePersistenceLayer.ts +++ b/packages/idempotency/src/persistence/BasePersistenceLayer.ts @@ -10,7 +10,7 @@ import { IdempotencyValidationError, } from '../errors'; import { LRUCache } from './LRUCache'; -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; /** * Base class for all persistence layers. This class provides the basic functionality for diff --git a/packages/idempotency/src/persistence/IdempotencyRecord.ts b/packages/idempotency/src/persistence/IdempotencyRecord.ts index 7811bc7413..feb618ddf5 100644 --- a/packages/idempotency/src/persistence/IdempotencyRecord.ts +++ b/packages/idempotency/src/persistence/IdempotencyRecord.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import type { IdempotencyRecordOptions, IdempotencyRecordStatusValue, diff --git a/packages/idempotency/src/types/IdempotencyOptions.ts b/packages/idempotency/src/types/IdempotencyOptions.ts index 959d014321..ea929f765b 100644 --- a/packages/idempotency/src/types/IdempotencyOptions.ts +++ b/packages/idempotency/src/types/IdempotencyOptions.ts @@ -1,7 +1,7 @@ import type { Context } from 'aws-lambda'; import { BasePersistenceLayer } from '../persistence/BasePersistenceLayer'; import { IdempotencyConfig } from '../IdempotencyConfig'; -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; /** * Configuration options for the idempotency utility. diff --git a/packages/idempotency/src/types/IdempotencyRecord.ts b/packages/idempotency/src/types/IdempotencyRecord.ts index 251d9c3c45..b7fc48b0dc 100644 --- a/packages/idempotency/src/types/IdempotencyRecord.ts +++ b/packages/idempotency/src/types/IdempotencyRecord.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import { IdempotencyRecordStatus } from '../constants'; type IdempotencyRecordStatusValue = diff --git a/packages/idempotency/tests/e2e/idempotentDecorator.test.FunctionCode.ts b/packages/idempotency/tests/e2e/idempotentDecorator.test.FunctionCode.ts index 8dd29c0b29..4a6a64f1a9 100644 --- a/packages/idempotency/tests/e2e/idempotentDecorator.test.FunctionCode.ts +++ b/packages/idempotency/tests/e2e/idempotentDecorator.test.FunctionCode.ts @@ -1,5 +1,5 @@ import type { Context } from 'aws-lambda'; -import { LambdaInterface } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; import { idempotent } from '../../src'; import { Logger } from '../../../logger'; import { DynamoDBPersistenceLayer } from '../../src/persistence/DynamoDBPersistenceLayer'; diff --git a/packages/idempotency/tests/unit/idempotencyDecorator.test.ts b/packages/idempotency/tests/unit/idempotencyDecorator.test.ts index 1a293d8569..f12b9ae6d3 100644 --- a/packages/idempotency/tests/unit/idempotencyDecorator.test.ts +++ b/packages/idempotency/tests/unit/idempotencyDecorator.test.ts @@ -15,7 +15,7 @@ import { } from '../../src/errors'; import { IdempotencyConfig } from '../../src'; import { Context } from 'aws-lambda'; -import { helloworldContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; +import { ContextExamples as context } from '@aws-lambda-powertools/commons'; import { IdempotencyRecordStatus } from '../../src/constants'; const mockSaveInProgress = jest @@ -28,7 +28,7 @@ const mockGetRecord = jest .spyOn(BasePersistenceLayer.prototype, 'getRecord') .mockImplementation(); -const dummyContext = helloworldContext; +const dummyContext = context.helloworldContext; const mockConfig: IdempotencyConfig = new IdempotencyConfig({}); diff --git a/packages/idempotency/tests/unit/makeHandlerIdempotent.test.ts b/packages/idempotency/tests/unit/makeHandlerIdempotent.test.ts index db064e6f38..ae628dd121 100644 --- a/packages/idempotency/tests/unit/makeHandlerIdempotent.test.ts +++ b/packages/idempotency/tests/unit/makeHandlerIdempotent.test.ts @@ -4,8 +4,10 @@ * @group unit/idempotency/makeHandlerIdempotent */ import { makeHandlerIdempotent } from '../../src/middleware'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; -import { Custom as dummyEvent } from '@aws-lambda-powertools/commons/lib/samples/resources/events'; +import { + ContextExamples as dummyContext, + Events as dummyEvent, +} from '@aws-lambda-powertools/commons'; import { IdempotencyRecord } from '../../src/persistence'; import { IdempotencyInconsistentStateError, @@ -25,8 +27,8 @@ const remainingTImeInMillis = 1234; describe('Middleware: makeHandlerIdempotent', () => { const ENVIRONMENT_VARIABLES = process.env; - const context = dummyContext; - const event = dummyEvent.CustomEvent; + const context = dummyContext.helloworldContext; + const event = dummyEvent.Custom; beforeEach(() => { jest.clearAllMocks(); diff --git a/packages/idempotency/tests/unit/makeIdempotent.test.ts b/packages/idempotency/tests/unit/makeIdempotent.test.ts index d46bc7ad6b..da7b3ef194 100644 --- a/packages/idempotency/tests/unit/makeIdempotent.test.ts +++ b/packages/idempotency/tests/unit/makeIdempotent.test.ts @@ -11,8 +11,10 @@ import { IdempotencyPersistenceLayerError, } from '../../src/errors'; import { IdempotencyConfig } from '../../src'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts'; -import { Custom as dummyEvent } from '@aws-lambda-powertools/commons/lib/samples/resources/events'; +import { + ContextExamples as dummyContext, + Events as dummyEvent, +} from '@aws-lambda-powertools/commons'; import { MAX_RETRIES, IdempotencyRecordStatus } from '../../src/constants'; import { PersistenceLayerTestClass } from '../helpers/idempotencyUtils'; import type { Context } from 'aws-lambda'; @@ -24,8 +26,8 @@ const remainingTImeInMillis = 1234; describe('Function: makeIdempotent', () => { const ENVIRONMENT_VARIABLES = process.env; - const context = dummyContext; - const event = dummyEvent.CustomEvent; + const context = dummyContext.helloworldContext; + const event = dummyEvent.Custom; beforeEach(() => { jest.clearAllMocks(); diff --git a/packages/logger/jest.config.cjs b/packages/logger/jest.config.cjs index 272f582c6c..deb2a416a5 100644 --- a/packages/logger/jest.config.cjs +++ b/packages/logger/jest.config.cjs @@ -4,17 +4,11 @@ module.exports = { color: 'cyan', }, runner: 'groups', - extensionsToTreatAsEsm: ['.ts'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', }, transform: { - '^.+\\.[tj]sx?$': [ - 'ts-jest', - { - useESM: true, - }, - ], + '^.+\\.ts?$': 'ts-jest', }, moduleFileExtensions: ['js', 'ts'], collectCoverageFrom: ['**/src/**/*.ts', '!**/node_modules/**'], @@ -22,7 +16,7 @@ module.exports = { roots: ['/src', '/tests'], testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', - coveragePathIgnorePatterns: ['/node_modules/', '/types/'], + coveragePathIgnorePatterns: ['/node_modules/', 'src/types/index.ts'], coverageThreshold: { global: { statements: 100, diff --git a/packages/logger/package.json b/packages/logger/package.json index 7bda057739..45bc7cf04d 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -24,8 +24,7 @@ "lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .", "lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .", "prebuild": "rimraf ./lib", - "postbuild": "rimraf ./lib/*.tsbuildinfo", - "prepack": "node ../../.github/scripts/release_patch_package_json.js ." + "prepack": "rimraf ./lib/*.tsbuildinfo && node ../../.github/scripts/release_patch_package_json.js ." }, "lint-staged": { "*.{js,ts}": "npm run lint-fix" diff --git a/packages/logger/src/Logger.ts b/packages/logger/src/Logger.ts index e0f05a225a..f0f9c3179d 100644 --- a/packages/logger/src/Logger.ts +++ b/packages/logger/src/Logger.ts @@ -960,7 +960,7 @@ class Logger extends Utility implements ClassThatLogs { * @returns {void} */ private setLogFormatter(logFormatter?: LogFormatterInterface): void { - this.logFormatter = logFormatter || new PowertoolsLogFormatter(); + this.logFormatter = logFormatter ?? new PowertoolsLogFormatter(); } /** diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts index dfedabfdff..096d26bb30 100644 --- a/packages/logger/src/index.ts +++ b/packages/logger/src/index.ts @@ -1,5 +1,3 @@ export { Logger } from './Logger.js'; -export { injectLambdaContext } from './middleware/middy.js'; -export { PowertoolsLogFormatter } from './formatter/PowertoolsLogFormatter.js'; export { LogFormatter } from './formatter/LogFormatter.js'; -export { LogFormatterInterface } from './formatter/LogFormatterInterface.js'; +export { LogItem } from './log/LogItem.js'; diff --git a/packages/logger/src/middleware/middy.ts b/packages/logger/src/middleware/middy.ts index 9e49dcbf63..7d8b3099da 100644 --- a/packages/logger/src/middleware/middy.ts +++ b/packages/logger/src/middleware/middy.ts @@ -1,11 +1,11 @@ import { Logger } from '../Logger.js'; import { LogAttributes } from '../types/Log.js'; import { HandlerOptions } from '../types/Logger.js'; -import { LOGGER_KEY } from '@aws-lambda-powertools/commons/lib/middleware'; +import { LOGGER_KEY } from '@aws-lambda-powertools/commons'; import type { MiddlewareLikeObj, MiddyLikeRequest, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; /** * A middy middleware that helps emitting CloudWatch EMF metrics in your logs. diff --git a/packages/logger/src/types/Logger.ts b/packages/logger/src/types/Logger.ts index 60f681dc60..193d72daef 100644 --- a/packages/logger/src/types/Logger.ts +++ b/packages/logger/src/types/Logger.ts @@ -1,8 +1,8 @@ -import { +import type { AsyncHandler, LambdaInterface, SyncHandler, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; import { Handler } from 'aws-lambda'; import { ConfigServiceInterface } from '../config/ConfigServiceInterface.js'; import { LogFormatterInterface } from '../formatter/LogFormatterInterface.js'; diff --git a/packages/logger/tests/e2e/sampleRate.decorator.test.FunctionCode.ts b/packages/logger/tests/e2e/sampleRate.decorator.test.FunctionCode.ts index 810e739bdf..32256a17ae 100644 --- a/packages/logger/tests/e2e/sampleRate.decorator.test.FunctionCode.ts +++ b/packages/logger/tests/e2e/sampleRate.decorator.test.FunctionCode.ts @@ -1,7 +1,7 @@ import { Logger } from '../../src'; import { TestEvent, TestOutput } from '../helpers/types'; import { Context } from 'aws-lambda'; -import { LambdaInterface } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; const SAMPLE_RATE = parseFloat(process.env.SAMPLE_RATE || '0.1'); const LOG_MSG = process.env.LOG_MSG || 'Hello World'; diff --git a/packages/logger/tests/unit/Logger.test.ts b/packages/logger/tests/unit/Logger.test.ts index b7af2b1f2e..e93acfb3c2 100644 --- a/packages/logger/tests/unit/Logger.test.ts +++ b/packages/logger/tests/unit/Logger.test.ts @@ -6,13 +6,12 @@ import { ContextExamples as dummyContext, Events as dummyEvent, - LambdaInterface, } from '@aws-lambda-powertools/commons'; -import { Logger } from '../../src/Logger.js'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; +import { Logger, LogFormatter } from '../../src/index.js'; import { ConfigServiceInterface } from '../../src/config/ConfigServiceInterface.js'; import { EnvironmentVariablesService } from '../../src/config/EnvironmentVariablesService.js'; import { PowertoolsLogFormatter } from '../../src/formatter/PowertoolsLogFormatter.js'; -import { LogFormatter } from '../../src/formatter/LogFormatter.js'; import { LogLevelThresholds, LogLevel } from '../../src/types/Log.js'; import { ClassThatLogs, @@ -20,7 +19,7 @@ import { ConstructorOptions, } from '../../src/types/Logger.js'; import type { Context } from 'aws-lambda'; -import { Console } from 'console'; +import { Console } from 'node:console'; const mockDate = new Date(1466424490000); const dateSpy = jest.spyOn(global, 'Date').mockImplementation(() => mockDate); diff --git a/packages/logger/tests/unit/middleware/middy.test.ts b/packages/logger/tests/unit/middleware/middy.test.ts index fec85bb1b4..e3d49c7c77 100644 --- a/packages/logger/tests/unit/middleware/middy.test.ts +++ b/packages/logger/tests/unit/middleware/middy.test.ts @@ -6,8 +6,8 @@ import { ContextExamples as dummyContext, Events as dummyEvent, + cleanupMiddlewares, } from '@aws-lambda-powertools/commons'; -import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; import { ConfigServiceInterface } from '../../../src/config/ConfigServiceInterface.js'; import { EnvironmentVariablesService } from '../../../src/config/EnvironmentVariablesService.js'; import { injectLambdaContext } from '../../../src/middleware/middy.js'; diff --git a/packages/metrics/src/middleware/middy.ts b/packages/metrics/src/middleware/middy.ts index 0da5c04828..5a2bbbaec4 100644 --- a/packages/metrics/src/middleware/middy.ts +++ b/packages/metrics/src/middleware/middy.ts @@ -1,10 +1,10 @@ -import { METRICS_KEY } from '@aws-lambda-powertools/commons/lib/middleware'; +import { METRICS_KEY } from '@aws-lambda-powertools/commons'; import type { Metrics } from '../Metrics'; import type { ExtraOptions } from '../types'; import type { MiddlewareLikeObj, MiddyLikeRequest, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; /** * A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler. diff --git a/packages/metrics/src/types/Metrics.ts b/packages/metrics/src/types/Metrics.ts index ef5e7d5454..73d8b60d10 100644 --- a/packages/metrics/src/types/Metrics.ts +++ b/packages/metrics/src/types/Metrics.ts @@ -3,7 +3,7 @@ import type { LambdaInterface, AsyncHandler, SyncHandler, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; import { ConfigServiceInterface } from '../config'; import { MetricUnit } from './MetricUnit'; import { MetricResolution } from './MetricResolution'; diff --git a/packages/metrics/tests/helpers/metricsUtils.ts b/packages/metrics/tests/helpers/metricsUtils.ts index 674efa370f..ee30e5d289 100644 --- a/packages/metrics/tests/helpers/metricsUtils.ts +++ b/packages/metrics/tests/helpers/metricsUtils.ts @@ -10,7 +10,7 @@ import type { ListMetricsCommandOutput, } from '@aws-sdk/client-cloudwatch'; import type { Context, Handler } from 'aws-lambda'; -import type { LambdaInterface } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; const getMetrics = async ( cloudWatchClient: CloudWatchClient, diff --git a/packages/metrics/tests/unit/Metrics.test.ts b/packages/metrics/tests/unit/Metrics.test.ts index c613b0535d..b358f59541 100644 --- a/packages/metrics/tests/unit/Metrics.test.ts +++ b/packages/metrics/tests/unit/Metrics.test.ts @@ -4,10 +4,10 @@ * @group unit/metrics/class */ import { - LambdaInterface, ContextExamples as dummyContext, Events as dummyEvent, } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; import { MetricResolution, MetricUnits, Metrics } from '../../src/'; import { Context, Handler } from 'aws-lambda'; import { Dimensions, EmfOutput, MetricsOptions } from '../../src/types'; diff --git a/packages/metrics/tests/unit/middleware/middy.test.ts b/packages/metrics/tests/unit/middleware/middy.test.ts index 5c1e22af48..917c14ae4d 100644 --- a/packages/metrics/tests/unit/middleware/middy.test.ts +++ b/packages/metrics/tests/unit/middleware/middy.test.ts @@ -6,9 +6,11 @@ import { Metrics, MetricUnits, logMetrics } from '../../../../metrics/src'; import middy from '@middy/core'; import { ExtraOptions } from '../../../src/types'; -import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; -import { helloworldContext as dummyContext } from '@aws-lambda-powertools/commons/lib/samples/resources/contexts/hello-world'; -import { CustomEvent as dummyEvent } from '@aws-lambda-powertools/commons/lib/samples/resources/events/custom/index'; +import { + cleanupMiddlewares, + ContextExamples as dummyContext, + Events as dummyEvent, +} from '@aws-lambda-powertools/commons'; jest.mock('node:console', () => ({ ...jest.requireActual('node:console'), @@ -73,7 +75,7 @@ describe('Middy middleware', () => { // Act & Assess await expect( - handler(dummyEvent, dummyContext) + handler(dummyEvent, dummyContext.helloworldContext) ).resolves.not.toThrowError(); expect(consoleWarnSpy).toBeCalledTimes(1); expect(consoleWarnSpy).toBeCalledWith( @@ -346,8 +348,8 @@ describe('Middy middleware', () => { .use(myCustomMiddleware()); // Act - await handler({ ...dummyEvent, idx: 0 }, dummyContext); - await handler({ ...dummyEvent, idx: 1 }, dummyContext); + await handler({ ...dummyEvent, idx: 0 }, dummyContext.helloworldContext); + await handler({ ...dummyEvent, idx: 1 }, dummyContext.helloworldContext); // Assess expect(publishStoredMetricsSpy).toBeCalledTimes(2); diff --git a/packages/parameters/src/base/transformValue.ts b/packages/parameters/src/base/transformValue.ts index a3b767ddbd..0d5a175106 100644 --- a/packages/parameters/src/base/transformValue.ts +++ b/packages/parameters/src/base/transformValue.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import { isString } from '@aws-lambda-powertools/commons'; import { fromBase64 } from '@aws-sdk/util-base64-node'; import { TRANSFORM_METHOD_BINARY, TRANSFORM_METHOD_JSON } from '../constants'; diff --git a/packages/parameters/src/dynamodb/DynamoDBProvider.ts b/packages/parameters/src/dynamodb/DynamoDBProvider.ts index 34d7026424..0468c2aab2 100644 --- a/packages/parameters/src/dynamodb/DynamoDBProvider.ts +++ b/packages/parameters/src/dynamodb/DynamoDBProvider.ts @@ -17,7 +17,7 @@ import type { GetItemCommandInput, QueryCommandInput, } from '@aws-sdk/client-dynamodb'; -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; /** * ## Intro diff --git a/packages/parameters/src/types/AppConfigProvider.ts b/packages/parameters/src/types/AppConfigProvider.ts index f20d7d656a..4796db8715 100644 --- a/packages/parameters/src/types/AppConfigProvider.ts +++ b/packages/parameters/src/types/AppConfigProvider.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import type { AppConfigDataClient, AppConfigDataClientConfig, diff --git a/packages/parameters/src/types/DynamoDBProvider.ts b/packages/parameters/src/types/DynamoDBProvider.ts index 53aecfed64..f9c3165807 100644 --- a/packages/parameters/src/types/DynamoDBProvider.ts +++ b/packages/parameters/src/types/DynamoDBProvider.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import type { DynamoDBClient, DynamoDBClientConfig, diff --git a/packages/parameters/src/types/SSMProvider.ts b/packages/parameters/src/types/SSMProvider.ts index cd9267fac7..7802f085a7 100644 --- a/packages/parameters/src/types/SSMProvider.ts +++ b/packages/parameters/src/types/SSMProvider.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import type { GetParameterCommandInput, GetParametersByPathCommandInput, diff --git a/packages/parameters/src/types/SecretsProvider.ts b/packages/parameters/src/types/SecretsProvider.ts index 6d797d37b3..96cd907b2f 100644 --- a/packages/parameters/src/types/SecretsProvider.ts +++ b/packages/parameters/src/types/SecretsProvider.ts @@ -1,4 +1,4 @@ -import type { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; import type { GetSecretValueCommandInput, SecretsManagerClient, diff --git a/packages/parameters/tests/unit/getAppConfig.test.ts b/packages/parameters/tests/unit/getAppConfig.test.ts index 5884a9e30e..3243f38f0b 100644 --- a/packages/parameters/tests/unit/getAppConfig.test.ts +++ b/packages/parameters/tests/unit/getAppConfig.test.ts @@ -18,7 +18,7 @@ import { mockClient } from 'aws-sdk-client-mock'; import 'aws-sdk-client-mock-jest'; import { toBase64 } from '@aws-sdk/util-base64-node'; import { Uint8ArrayBlobAdapter } from '@smithy/util-stream'; -import { JSONValue } from '@aws-lambda-powertools/commons'; +import type { JSONValue } from '@aws-lambda-powertools/commons/types'; describe('Function: getAppConfig', () => { const client = mockClient(AppConfigDataClient); diff --git a/packages/tracer/src/Tracer.ts b/packages/tracer/src/Tracer.ts index 4d1fb11267..1fb152df30 100644 --- a/packages/tracer/src/Tracer.ts +++ b/packages/tracer/src/Tracer.ts @@ -1,9 +1,9 @@ import type { Handler } from 'aws-lambda'; -import { - type AsyncHandler, - type SyncHandler, - Utility, -} from '@aws-lambda-powertools/commons'; +import { Utility } from '@aws-lambda-powertools/commons'; +import type { + AsyncHandler, + SyncHandler, +} from '@aws-lambda-powertools/commons/types'; import type { TracerInterface } from '.'; import { type ConfigServiceInterface, diff --git a/packages/tracer/src/middleware/middy.ts b/packages/tracer/src/middleware/middy.ts index 547561500f..8081985f83 100644 --- a/packages/tracer/src/middleware/middy.ts +++ b/packages/tracer/src/middleware/middy.ts @@ -1,11 +1,11 @@ -import { TRACER_KEY } from '@aws-lambda-powertools/commons/lib/middleware'; +import { TRACER_KEY } from '@aws-lambda-powertools/commons'; import type { Tracer } from '../Tracer'; import type { Segment, Subsegment } from 'aws-xray-sdk-core'; import type { CaptureLambdaHandlerOptions } from '../types'; import type { MiddlewareLikeObj, MiddyLikeRequest, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; /** * A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler. diff --git a/packages/tracer/src/types/Tracer.ts b/packages/tracer/src/types/Tracer.ts index e31c06c4e7..9f15b927ad 100644 --- a/packages/tracer/src/types/Tracer.ts +++ b/packages/tracer/src/types/Tracer.ts @@ -4,7 +4,7 @@ import type { AsyncHandler, LambdaInterface, SyncHandler, -} from '@aws-lambda-powertools/commons'; +} from '@aws-lambda-powertools/commons/types'; /** * Options for the tracer class to be used during initialization. diff --git a/packages/tracer/tests/unit/Tracer.test.ts b/packages/tracer/tests/unit/Tracer.test.ts index 579c150b2a..a1be20a868 100644 --- a/packages/tracer/tests/unit/Tracer.test.ts +++ b/packages/tracer/tests/unit/Tracer.test.ts @@ -6,8 +6,8 @@ import { ContextExamples as dummyContext, Events as dummyEvent, - LambdaInterface, } from '@aws-lambda-powertools/commons'; +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; import { Tracer } from './../../src'; import type { Callback, Context } from 'aws-lambda/handler'; import { diff --git a/packages/tracer/tests/unit/middy.test.ts b/packages/tracer/tests/unit/middy.test.ts index c470b1d25a..9d6504e86b 100644 --- a/packages/tracer/tests/unit/middy.test.ts +++ b/packages/tracer/tests/unit/middy.test.ts @@ -12,7 +12,7 @@ import { setContextMissingStrategy, Subsegment, } from 'aws-xray-sdk-core'; -import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; +import { cleanupMiddlewares } from '@aws-lambda-powertools/commons'; jest.spyOn(console, 'debug').mockImplementation(() => null); jest.spyOn(console, 'warn').mockImplementation(() => null);