From 47e822d638941bc0e77e59a0a8d96f6fb6b45e0c Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 09:11:59 -0500 Subject: [PATCH 01/45] chore: Switch release back to conventional commits (#12463) --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index fa2ede587c3..708f3fd7f38 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "unlink-all": "lerna exec --no-bail --parallel -- yarn unlink; exit 0", "publish:preid": "./scripts/preid-env-vars-exist.sh && lerna publish --canary --force-publish --dist-tag=${PREID_PREFIX} --preid=${PREID_PREFIX}${PREID_HASH_SUFFIX} --yes", "publish:main": "lerna publish --canary --force-publish --dist-tag=unstable --preid=unstable${PREID_HASH_SUFFIX} --yes", - "publish:release": "lerna publish from-package --dist-tag=v6 --message 'chore(release): Publish [ci skip]' --yes", + "publish:release": "lerna publish --conventional-commits --dist-tag=v6 --message 'chore(release): Publish [ci skip]' --yes", "publish:verdaccio": "lerna publish --canary --force-publish --no-push --dist-tag=unstable --preid=unstable --yes", "ts-coverage": "lerna run ts-coverage", "prepare": "./scripts/set-preid-versions.sh" From 9d6c0b2bb088112f08013d9ba3fc1f55d9ac89ab Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 09:34:28 -0500 Subject: [PATCH 02/45] chore: Re-enable OSX pre-build (#12460) --- .github/workflows/callable-release-verification.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/callable-release-verification.yml b/.github/workflows/callable-release-verification.yml index 3d270d97521..30fd4b0c7e0 100644 --- a/.github/workflows/callable-release-verification.yml +++ b/.github/workflows/callable-release-verification.yml @@ -7,16 +7,16 @@ jobs: uses: ./.github/workflows/callable-prebuild-amplify-js.yml with: runs_on: ubuntu-latest - # prebuild-macos: - # uses: ./.github/workflows/callable-prebuild-amplify-js.yml - # with: - # runs_on: macos-latest + prebuild-macos: + uses: ./.github/workflows/callable-prebuild-amplify-js.yml + with: + runs_on: macos-latest prebuild-samples-staging: secrets: inherit uses: ./.github/workflows/callable-prebuild-samples-staging.yml e2e: needs: - # - prebuild-macos + - prebuild-macos - prebuild-ubuntu - prebuild-samples-staging secrets: inherit From 661ac60838369043f7df911600df11acc90844a0 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 09:50:56 -0500 Subject: [PATCH 03/45] chore: Restrict staging branch checkout logic (#12465) --- .github/actions/setup-samples-staging/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/setup-samples-staging/action.yml b/.github/actions/setup-samples-staging/action.yml index bc91886e224..508e36b4ed7 100644 --- a/.github/actions/setup-samples-staging/action.yml +++ b/.github/actions/setup-samples-staging/action.yml @@ -34,7 +34,7 @@ runs: env: BRANCH: ${{ github.ref_name }} run: | - if git ls-remote --exit-code --heads origin $BRANCH >/dev/null 2>&1; then + if git ls-remote origin $BRANCH | grep -q refs/heads/next/$BRANCH$; then # Branch exists, checkout and echo success message git fetch origin $BRANCH git checkout $BRANCH From feaecfd6a49d1bb06b91d1bb3fb860e130cc1a77 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 27 Oct 2023 13:30:23 -0700 Subject: [PATCH 04/45] feat(adapter-nextjs)!: introduce createServerRunner and remove withAmplify --- .../api/generateServerClient.test.ts | 25 ++- .../__tests__/createServerRunner.test.ts | 166 ++++++++++++++++++ .../runWithAmplifyServerContext.test.ts | 130 -------------- ...torageAdapterFromNextServerContext.test.ts | 2 +- .../__tests__/utils/getAmplifyConfig.test.ts | 43 +---- .../__tests__/withAmplify.test.ts | 92 ---------- packages/adapter-nextjs/api/package.json | 8 +- packages/adapter-nextjs/package.json | 14 +- .../src/api/createServerRunnerForAPI.ts | 21 +++ .../src/api/generateServerClient.ts | 44 +++-- .../adapter-nextjs/src/createServerRunner.ts | 28 +++ packages/adapter-nextjs/src/index.ts | 2 +- .../src/runWithAmplifyServerContext.ts | 103 ----------- .../adapter-nextjs/src/types/NextServer.ts | 14 ++ .../createRunWithAmplifyServerContext.ts | 61 +++++++ .../src/utils/getAmplifyConfig.ts | 36 +--- packages/adapter-nextjs/src/utils/index.ts | 2 +- packages/adapter-nextjs/src/withAmplify.ts | 36 ---- .../adapter-nextjs/with-amplify/package.json | 7 - 19 files changed, 349 insertions(+), 485 deletions(-) create mode 100644 packages/adapter-nextjs/__tests__/createServerRunner.test.ts delete mode 100644 packages/adapter-nextjs/__tests__/runWithAmplifyServerContext.test.ts delete mode 100644 packages/adapter-nextjs/__tests__/withAmplify.test.ts create mode 100644 packages/adapter-nextjs/src/api/createServerRunnerForAPI.ts create mode 100644 packages/adapter-nextjs/src/createServerRunner.ts delete mode 100644 packages/adapter-nextjs/src/runWithAmplifyServerContext.ts create mode 100644 packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts delete mode 100644 packages/adapter-nextjs/src/withAmplify.ts delete mode 100644 packages/adapter-nextjs/with-amplify/package.json diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index 22dc985bf04..2871b6b919e 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -3,9 +3,12 @@ import { generateServerClientUsingCookies, generateServerClient, } from '../../src/api'; -import { runWithAmplifyServerContext } from './../../src'; -import { getAmplifyConfig } from '../../src/utils'; +import { + getAmplifyConfig, + createRunWithAmplifyServerContext, +} from '../../src/utils'; import { NextApiRequestMock, NextApiResponseMock } from '../mocks/headers'; +import { createServerRunnerForAPI } from '../../src/api/createServerRunnerForAPI'; const headers = import('next/headers'); (global as any).Headers = jest.requireActual('node-fetch').Headers; @@ -29,6 +32,7 @@ const mockAmplifyConfig: ResourcesConfig = { }; jest.mock('../../src/utils', () => ({ + createRunWithAmplifyServerContext: jest.fn(() => jest.fn()), getAmplifyConfig: jest.fn(() => mockAmplifyConfig), createCookieStorageAdapterFromNextServerContext: jest.fn(), })); @@ -36,6 +40,8 @@ jest.mock('../../src/utils', () => ({ jest.mock('aws-amplify/adapter-core'); const mockGetAmplifyConfig = getAmplifyConfig as jest.Mock; +const mockCreateRunWithAmplifyServerContext = + createRunWithAmplifyServerContext as jest.Mock; describe('generateServerClientUsingCookies', () => { it('should throw error when used with req/res', async () => { @@ -52,11 +58,13 @@ describe('generateServerClientUsingCookies', () => { }).toThrowError(); }); - it('should call getAmlifyConfig', async () => { + it('should call createRunWithAmplifyServerContext to create runWithAmplifyServerContext function', async () => { const cookies = (await headers).cookies; - generateServerClientUsingCookies({ cookies }); - expect(mockGetAmplifyConfig).toHaveBeenCalled(); + generateServerClientUsingCookies({ config: mockAmplifyConfig, cookies }); + expect(mockCreateRunWithAmplifyServerContext).toHaveBeenCalledWith({ + config: mockAmplifyConfig, + }); }); }); @@ -67,12 +75,15 @@ describe('generateServerClient', () => { }); it('should call getAmlifyConfig', async () => { - generateServerClient(); + generateServerClient({ config: mockAmplifyConfig }); expect(mockGetAmplifyConfig).toHaveBeenCalled(); }); // TODO: figure out proper mocks and unskip it.skip('wrapped client.graphql should pass context through', async () => { + const { runWithAmplifyServerContext } = createServerRunnerForAPI({ + config: mockAmplifyConfig, + }); const mockedReq = new NextApiRequestMock(); const mockedRes = NextApiResponseMock; @@ -86,7 +97,7 @@ describe('generateServerClient', () => { getAmplifyServerContext: () => {}, })); - const client = generateServerClient(); + const client = generateServerClient({ config: mockAmplifyConfig }); await runWithAmplifyServerContext({ nextServerContext: { diff --git a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts new file mode 100644 index 00000000000..3df244366d5 --- /dev/null +++ b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts @@ -0,0 +1,166 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ResourcesConfig, sharedInMemoryStorage } from '@aws-amplify/core'; +import { NextServer } from '../src/types'; + +const mockAmplifyConfig: ResourcesConfig = { + Auth: { + Cognito: { + identityPoolId: '123', + userPoolId: 'abc', + userPoolClientId: 'def', + }, + }, + Storage: { + S3: { + bucket: 'bucket', + region: 'us-east-1', + }, + }, +}; + +jest.mock( + '../src/utils/createCookieStorageAdapterFromNextServerContext', + () => ({ + createCookieStorageAdapterFromNextServerContext: jest.fn(), + }) +); + +describe('createServerRunner', () => { + let createServerRunner; + + const mockParseAWSExports = jest.fn(); + const mockCreateAWSCredentialsAndIdentityIdProvider = jest.fn(); + const mockCreateKeyValueStorageFromCookieStorageAdapter = jest.fn(); + const mockCreateUserPoolsTokenProvider = jest.fn(); + const mockRunWithAmplifyServerContextCore = jest.fn(); + + beforeEach(() => { + jest.resetModules(); + jest.doMock('aws-amplify/adapter-core', () => ({ + createAWSCredentialsAndIdentityIdProvider: + mockCreateAWSCredentialsAndIdentityIdProvider, + createKeyValueStorageFromCookieStorageAdapter: + mockCreateKeyValueStorageFromCookieStorageAdapter, + createUserPoolsTokenProvider: mockCreateUserPoolsTokenProvider, + runWithAmplifyServerContext: mockRunWithAmplifyServerContextCore, + })); + jest.doMock('@aws-amplify/core/internals/utils', () => ({ + parseAWSExports: mockParseAWSExports, + })); + + createServerRunner = require('../src').createServerRunner; + }); + + afterEach(() => { + mockParseAWSExports.mockClear(); + mockCreateAWSCredentialsAndIdentityIdProvider.mockClear(); + mockCreateKeyValueStorageFromCookieStorageAdapter.mockClear(); + mockCreateUserPoolsTokenProvider.mockClear(); + mockRunWithAmplifyServerContextCore.mockClear(); + }); + + it('calls parseAWSExports when the config object is imported from amplify configuration file', () => { + createServerRunner({ config: { aws_project_region: 'us-west-2' } }); + expect(mockParseAWSExports).toHaveBeenCalled(); + }); + + it('returns runWithAmplifyServerContext function', () => { + const result = createServerRunner({ config: mockAmplifyConfig }); + expect(result).toMatchObject({ + runWithAmplifyServerContext: expect.any(Function), + }); + }); + + it('throws when get called more than once', () => { + createServerRunner({ config: mockAmplifyConfig }); + expect(() => createServerRunner({ config: mockAmplifyConfig })).toThrow(); + }); + + describe('runWithAmplifyServerContext', () => { + describe('when amplifyConfig.Auth is not defined', () => { + it('should call runWithAmplifyServerContextCore without Auth library options', () => { + const mockAmplifyConfig: ResourcesConfig = { + Analytics: { + Pinpoint: { + appId: 'app-id', + region: 'region', + }, + }, + }; + const { runWithAmplifyServerContext } = createServerRunner({ + config: mockAmplifyConfig, + }); + const operation = jest.fn(); + runWithAmplifyServerContext({ operation, nextServerContext: null }); + expect(mockRunWithAmplifyServerContextCore).toHaveBeenCalledWith( + mockAmplifyConfig, + {}, + operation + ); + }); + }); + + describe('when amplifyConfig.Auth is defined', () => { + describe('when nextServerContext is null (opt-in unauthenticated role)', () => { + it('should create auth providers with sharedInMemoryStorage', () => { + const { runWithAmplifyServerContext } = createServerRunner({ + config: mockAmplifyConfig, + }); + const operation = jest.fn(); + runWithAmplifyServerContext({ operation, nextServerContext: null }); + expect( + mockCreateAWSCredentialsAndIdentityIdProvider + ).toHaveBeenCalledWith(mockAmplifyConfig.Auth, sharedInMemoryStorage); + expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( + mockAmplifyConfig.Auth, + sharedInMemoryStorage + ); + }); + }); + + describe('when nextServerContext is not null', () => { + it('should create auth providers with cookie storage adapter', () => { + const operation = jest.fn(); + const mockCookieStorageAdapter = { + get: jest.fn(), + set: jest.fn(), + remove: jest.fn(), + }; + mockCreateKeyValueStorageFromCookieStorageAdapter.mockReturnValueOnce( + mockCookieStorageAdapter + ); + const mockNextServerContext = { + req: { + headers: { + cookie: 'cookie', + }, + }, + res: { + setHeader: jest.fn(), + }, + }; + const { runWithAmplifyServerContext } = createServerRunner({ + config: mockAmplifyConfig, + }); + runWithAmplifyServerContext({ + operation, + nextServerContext: + mockNextServerContext as unknown as NextServer.Context, + }); + expect( + mockCreateAWSCredentialsAndIdentityIdProvider + ).toHaveBeenCalledWith( + mockAmplifyConfig.Auth, + mockCookieStorageAdapter + ); + expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( + mockAmplifyConfig.Auth, + mockCookieStorageAdapter + ); + }); + }); + }); + }); +}); diff --git a/packages/adapter-nextjs/__tests__/runWithAmplifyServerContext.test.ts b/packages/adapter-nextjs/__tests__/runWithAmplifyServerContext.test.ts deleted file mode 100644 index 2878eaf2de0..00000000000 --- a/packages/adapter-nextjs/__tests__/runWithAmplifyServerContext.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { ResourcesConfig, sharedInMemoryStorage } from '@aws-amplify/core'; -import { - createAWSCredentialsAndIdentityIdProvider, - createKeyValueStorageFromCookieStorageAdapter, - createUserPoolsTokenProvider, - runWithAmplifyServerContext as runWithAmplifyServerContextCore, -} from 'aws-amplify/adapter-core'; -import { runWithAmplifyServerContext } from '../src'; -import { getAmplifyConfig } from '../src/utils'; -import { NextServer } from '../src/types'; - -const mockAmplifyConfig: ResourcesConfig = { - Auth: { - Cognito: { - identityPoolId: '123', - userPoolId: 'abc', - userPoolClientId: 'def', - }, - }, - Storage: { - S3: { - bucket: 'bucket', - region: 'us-east-1', - }, - }, -}; - -jest.mock('../src/utils', () => ({ - getAmplifyConfig: jest.fn(() => mockAmplifyConfig), - createCookieStorageAdapterFromNextServerContext: jest.fn(), -})); -jest.mock('aws-amplify/adapter-core'); - -const mockGetAmplifyConfig = getAmplifyConfig as jest.Mock; -const mockRunWithAmplifyServerContextCore = - runWithAmplifyServerContextCore as jest.Mock; - -const mockCreateAWSCredentialsAndIdentityIdProvider = - createAWSCredentialsAndIdentityIdProvider as jest.Mock; -const mockCreateKeyValueStorageFromCookieStorageAdapter = - createKeyValueStorageFromCookieStorageAdapter as jest.Mock; -const mockCreateUserPoolsTokenProvider = - createUserPoolsTokenProvider as jest.Mock; - -describe('runWithAmplifyServerContext', () => { - it('should call getAmlifyConfig', async () => { - const operation = jest.fn(); - await runWithAmplifyServerContext({ operation, nextServerContext: null }); - expect(mockGetAmplifyConfig).toHaveBeenCalled(); - }); - - describe('when amplifyConfig.Auth is not defined', () => { - it('should call runWithAmplifyServerContextCore without Auth library options', () => { - const mockAmplifyConfig: ResourcesConfig = { - Analytics: { - Pinpoint: { - appId: 'app-id', - region: 'region', - }, - }, - }; - mockGetAmplifyConfig.mockReturnValueOnce(mockAmplifyConfig); - const operation = jest.fn(); - runWithAmplifyServerContext({ operation, nextServerContext: null }); - expect(mockRunWithAmplifyServerContextCore).toHaveBeenCalledWith( - mockAmplifyConfig, - {}, - operation - ); - }); - }); - - describe('when amplifyConfig.Auth is defined', () => { - describe('when nextServerContext is null (opt-in unauthenticated role)', () => { - it('should create auth providers with sharedInMemoryStorage', () => { - const operation = jest.fn(); - runWithAmplifyServerContext({ operation, nextServerContext: null }); - expect( - mockCreateAWSCredentialsAndIdentityIdProvider - ).toHaveBeenCalledWith(mockAmplifyConfig.Auth, sharedInMemoryStorage); - expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( - mockAmplifyConfig.Auth, - sharedInMemoryStorage - ); - }); - }); - - describe('when nextServerContext is not null', () => { - it('should create auth providers with cookie storage adapter', () => { - const operation = jest.fn(); - const mockCookieStorageAdapter = { - get: jest.fn(), - set: jest.fn(), - remove: jest.fn(), - }; - mockCreateKeyValueStorageFromCookieStorageAdapter.mockReturnValueOnce( - mockCookieStorageAdapter - ); - const mockNextServerContext = { - req: { - headers: { - cookie: 'cookie', - }, - }, - res: { - setHeader: jest.fn(), - }, - }; - runWithAmplifyServerContext({ - operation, - nextServerContext: - mockNextServerContext as unknown as NextServer.Context, - }); - expect( - mockCreateAWSCredentialsAndIdentityIdProvider - ).toHaveBeenCalledWith( - mockAmplifyConfig.Auth, - mockCookieStorageAdapter - ); - expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( - mockAmplifyConfig.Auth, - mockCookieStorageAdapter - ); - }); - }); - }); -}); diff --git a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts index 44d2509459f..0dda7a31726 100644 --- a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts @@ -8,7 +8,7 @@ enableFetchMocks(); import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; -import { createCookieStorageAdapterFromNextServerContext } from '../../src/utils'; +import { createCookieStorageAdapterFromNextServerContext } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; import { DATE_IN_THE_PAST } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; import { IncomingMessage, ServerResponse } from 'http'; import { Socket } from 'net'; diff --git a/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts b/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts index 716e73072f5..14532cec5b3 100644 --- a/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/getAmplifyConfig.test.ts @@ -1,16 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import getConfig from 'next/config'; -import { parseAWSExports } from '@aws-amplify/core/internals/utils'; import { getAmplifyConfig } from '../../src/utils/getAmplifyConfig'; -jest.mock('next/config'); -jest.mock('@aws-amplify/core/internals/utils'); - -const mockGetConfig = getConfig as jest.Mock; -const mockParseAWSExports = parseAWSExports as jest.Mock; - describe('getAmplifyConfig', () => { const mockLegacyConfig = { aws_project_region: 'us-west-2', @@ -48,38 +40,7 @@ describe('getAmplifyConfig', () => { }, }; - beforeEach(() => { - mockGetConfig.mockReturnValue({}); - delete process.env.amplifyConfig; - }); - - it('should return amplifyConfig from env vars', () => { - process.env.amplifyConfig = JSON.stringify(mockAmplifyConfig); - - const result = getAmplifyConfig(); - expect(result).toEqual(mockAmplifyConfig); - }); - - it('should invoke parseAWSConfig when using the legacy shaped config', () => { - process.env.amplifyConfig = JSON.stringify(mockLegacyConfig); - - getAmplifyConfig(); - expect(mockParseAWSExports).toHaveBeenCalledWith(mockLegacyConfig); - }); - - it('should attempt to get amplifyConfig via getConfig provided by Next.js as a fallback', () => { - mockGetConfig.mockReturnValueOnce({ - serverRuntimeConfig: { - amplifyConfig: JSON.stringify(mockAmplifyConfig), - }, - }); - - const result = getAmplifyConfig(); - expect(result).toEqual(mockAmplifyConfig); - }); - - it('should throw error when amplifyConfig is not found from env vars', () => { - mockGetConfig.mockReturnValueOnce(undefined); - expect(() => getAmplifyConfig()).toThrow(); + it('returns config object that conforms to ResourcesConfig', () => { + expect(getAmplifyConfig(mockLegacyConfig)).toMatchObject(mockAmplifyConfig); }); }); diff --git a/packages/adapter-nextjs/__tests__/withAmplify.test.ts b/packages/adapter-nextjs/__tests__/withAmplify.test.ts deleted file mode 100644 index 2417db0099a..00000000000 --- a/packages/adapter-nextjs/__tests__/withAmplify.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { ResourcesConfig } from 'aws-amplify'; -import { withAmplify } from '../src/withAmplify'; - -const mockAmplifyConfig: ResourcesConfig = { - Auth: { - Cognito: { - identityPoolId: '123', - userPoolId: 'abc', - userPoolClientId: 'def', - }, - }, - Storage: { - S3: { - bucket: 'bucket', - region: 'us-east-1', - }, - }, -}; -const mockLegacyConfig = { - aws_project_region: 'us-west-2', - aws_cognito_identity_pool_id: 'aws_cognito_identity_pool_id', - aws_cognito_region: 'aws_cognito_region', - aws_user_pools_id: 'aws_user_pools_id', - aws_user_pools_web_client_id: 'aws_user_pools_web_client_id', - oauth: {}, - aws_cognito_username_attributes: [], - aws_cognito_social_providers: [], - aws_cognito_signup_attributes: [], - aws_cognito_mfa_configuration: 'OFF', - aws_cognito_mfa_types: ['SMS'], - aws_cognito_password_protection_settings: { - passwordPolicyMinLength: 8, - passwordPolicyCharacters: [], - }, - aws_cognito_verification_mechanisms: ['PHONE_NUMBER'], -}; - -describe('withAmplify', () => { - it('should add amplifyConfig to nextConfig.env', () => { - const nextConfig = {}; - const result = withAmplify(nextConfig, mockAmplifyConfig); - - expect(result).toEqual({ - env: { - amplifyConfig: JSON.stringify(mockAmplifyConfig), - }, - serverRuntimeConfig: { - amplifyConfig: JSON.stringify(mockAmplifyConfig), - }, - }); - }); - - it('should add amplifyConfig (legacy CLI shaped) to nextConfig.env', () => { - const nextConfig = {}; - const result = withAmplify(nextConfig, mockLegacyConfig); - - expect(result).toEqual({ - env: { - amplifyConfig: JSON.stringify(mockLegacyConfig), - }, - serverRuntimeConfig: { - amplifyConfig: JSON.stringify(mockLegacyConfig), - }, - }); - }); - - it('should merge amplifyConfig to nextConfig.env (if this key has already defined)', () => { - const nextConfig = { - env: { - existingKey: '123', - }, - serverRuntimeConfig: { - myKey: 'myValue', - }, - }; - const result = withAmplify(nextConfig, mockAmplifyConfig); - - expect(result).toEqual({ - env: { - existingKey: '123', - amplifyConfig: JSON.stringify(mockAmplifyConfig), - }, - serverRuntimeConfig: { - myKey: 'myValue', - amplifyConfig: JSON.stringify(mockAmplifyConfig), - }, - }); - }); -}); diff --git a/packages/adapter-nextjs/api/package.json b/packages/adapter-nextjs/api/package.json index d6ab2264f24..513f32bb0d8 100644 --- a/packages/adapter-nextjs/api/package.json +++ b/packages/adapter-nextjs/api/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/adapter-nextjs/api", - "main": "../lib/api/generateServerClient.js", - "browser": "../lib-esm/api/generateServerClient.js", - "module": "../lib-esm/api/generateServerClient.js", - "typings": "../lib-esm/api/generateServerClient.d.ts" + "main": "../lib/api/index.js", + "browser": "../lib-esm/api/index.js", + "module": "../lib-esm/api/index.js", + "typings": "../lib-esm/api/index.d.ts" } diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 839cf423718..9bac9ec7c1c 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -33,15 +33,10 @@ "import": "./lib-esm/index.js", "require": "./lib/index.js" }, - "./with-amplify": { - "types": "./lib-esm/withAmplify.d.ts", - "import": "./lib-esm/withAmplify.js", - "require": "./lib/withAmplify.js" - }, "./api": { - "types": "./lib-esm/api/generateServerClient.d.ts", - "import": "./lib-esm/api/generateServerClient.js", - "require": "./lib/api/generateServerClient.js" + "types": "./lib-esm/api/index.d.ts", + "import": "./lib-esm/api/index.js", + "require": "./lib/api/index.js" }, "./internals": { "types": "./lib-esm/internals/index.d.ts", @@ -63,7 +58,8 @@ "/node_modules/", "dist", "lib", - "lib-esm" + "lib-esm", + "__tests__/mocks" ], "coverageThreshold": { "global": { diff --git a/packages/adapter-nextjs/src/api/createServerRunnerForAPI.ts b/packages/adapter-nextjs/src/api/createServerRunnerForAPI.ts new file mode 100644 index 00000000000..e9e7c8df222 --- /dev/null +++ b/packages/adapter-nextjs/src/api/createServerRunnerForAPI.ts @@ -0,0 +1,21 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ResourcesConfig } from '@aws-amplify/core'; +import { createRunWithAmplifyServerContext, getAmplifyConfig } from '../utils'; +import { NextServer } from '../types'; + +export const createServerRunnerForAPI = ({ + config, +}: NextServer.CreateServerRunnerInput): NextServer.CreateServerRunnerOutput & { + resourcesConfig: ResourcesConfig; +} => { + const amplifyConfig = getAmplifyConfig(config); + + return { + runWithAmplifyServerContext: createRunWithAmplifyServerContext({ + config: amplifyConfig, + }), + resourcesConfig: amplifyConfig, + }; +}; diff --git a/packages/adapter-nextjs/src/api/generateServerClient.ts b/packages/adapter-nextjs/src/api/generateServerClient.ts index 7373556628a..6aa79ac2757 100644 --- a/packages/adapter-nextjs/src/api/generateServerClient.ts +++ b/packages/adapter-nextjs/src/api/generateServerClient.ts @@ -13,10 +13,9 @@ import { GraphQLMethodSSR, __amplify, } from '@aws-amplify/api-graphql'; - -import { runWithAmplifyServerContext } from '../runWithAmplifyServerContext'; -import { getAmplifyConfig } from '../utils'; import { NextServer } from '../types'; +import { createServerRunnerForAPI } from './createServerRunnerForAPI'; +import { getAmplifyConfig } from '../utils'; /** * Generates an API client that can be used inside a Next.js Server Component with Dynamic Rendering @@ -31,37 +30,37 @@ import { NextServer } from '../types'; */ export function generateServerClientUsingCookies< T extends Record = never ->(nextServerContext: NextServer.ServerComponentContext): V6Client { - if ( - !nextServerContext.cookies || - (nextServerContext as any).request !== undefined - ) { +>({ + config, + cookies, +}: NextServer.ServerComponentContext & + NextServer.CreateServerRunnerInput): V6Client { + if (typeof cookies !== 'function') { throw new AmplifyServerContextError({ message: - 'generateServerClientUsingCookies is only compatible with the `cookies` Dynamic Function available in Server Components', + 'generateServerClientUsingCookies is only compatible with the `cookies` Dynamic Function available in Server Components.', // TODO: link to docs recoverySuggestion: - 'use `generateServerClient` inside of runWithAmplifyServerContext with the `request` object', + 'use `generateServerClient` inside of `runWithAmplifyServerContext` with the `request` object.', }); } + const { runWithAmplifyServerContext, resourcesConfig } = + createServerRunnerForAPI({ config }); + // This function reference gets passed down to InternalGraphQLAPI.ts.graphql // where this._graphql is passed in as the `fn` argument // causing it to always get invoked inside `runWithAmplifyServerContext` const getAmplify = (fn: (amplify: any) => Promise) => runWithAmplifyServerContext({ - nextServerContext, + nextServerContext: { cookies }, operation: contextSpec => fn(getAmplifyServerContext(contextSpec).amplify), }); - // retrieve general SSR config. This is used only to retrieve the - // modelIntroSchema for future model-based use cases - const config = getAmplifyConfig(); - return internalGenerateClient>({ amplify: getAmplify, - config, + config: resourcesConfig, }); } @@ -83,25 +82,22 @@ export function generateServerClientUsingCookies< }) * ``` */ -export function generateServerClient< - T extends Record = never ->(): V6ClientSSR { - const config = getAmplifyConfig(); - +export function generateServerClient = never>({ + config, +}: NextServer.CreateServerRunnerInput): V6ClientSSR { + const amplifyConfig = getAmplifyConfig(config); // passing `null` instance because each (future model) method must retrieve a valid instance // from server context const client = internalGenerateClient>({ amplify: null, - config, + config: amplifyConfig, }); // TODO: improve this and the next type const prevGraphql = client.graphql as unknown as GraphQLMethod; const wrappedGraphql = (contextSpec, options, additionalHeaders?) => { - console.log('inside wrapped'); const amplifyInstance = getAmplifyServerContext(contextSpec).amplify; - console.log('instance', amplifyInstance); return prevGraphql.call( { [__amplify]: amplifyInstance }, options, diff --git a/packages/adapter-nextjs/src/createServerRunner.ts b/packages/adapter-nextjs/src/createServerRunner.ts new file mode 100644 index 00000000000..f6d39566b56 --- /dev/null +++ b/packages/adapter-nextjs/src/createServerRunner.ts @@ -0,0 +1,28 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ResourcesConfig } from '@aws-amplify/core'; +import { parseAWSExports } from '@aws-amplify/core/internals/utils'; +import { AmplifyServerContextError } from '@aws-amplify/core/internals/adapter-core'; +import { createRunWithAmplifyServerContext, getAmplifyConfig } from './utils'; +import { NextServer } from './types'; + +let amplifyConfig: ResourcesConfig | undefined; + +export const createServerRunner: NextServer.CreateServerRunner = ({ + config, +}) => { + if (amplifyConfig) { + throw new AmplifyServerContextError({ + message: '`createServerRunner` needs to be called only once.', + }); + } + + amplifyConfig = getAmplifyConfig(config); + + return { + runWithAmplifyServerContext: createRunWithAmplifyServerContext({ + config: amplifyConfig, + }), + }; +}; diff --git a/packages/adapter-nextjs/src/index.ts b/packages/adapter-nextjs/src/index.ts index 0c0042b0115..14ec009a4a7 100644 --- a/packages/adapter-nextjs/src/index.ts +++ b/packages/adapter-nextjs/src/index.ts @@ -1,4 +1,4 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export { runWithAmplifyServerContext } from './runWithAmplifyServerContext'; +export { createServerRunner } from './createServerRunner'; diff --git a/packages/adapter-nextjs/src/runWithAmplifyServerContext.ts b/packages/adapter-nextjs/src/runWithAmplifyServerContext.ts deleted file mode 100644 index 8fdf96dbce8..00000000000 --- a/packages/adapter-nextjs/src/runWithAmplifyServerContext.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { NextServer } from './types'; -import { - createCookieStorageAdapterFromNextServerContext, - getAmplifyConfig, -} from './utils'; -import { sharedInMemoryStorage } from '@aws-amplify/core'; -import { - createAWSCredentialsAndIdentityIdProvider, - createKeyValueStorageFromCookieStorageAdapter, - createUserPoolsTokenProvider, - runWithAmplifyServerContext as runWithAmplifyServerContextCore, -} from 'aws-amplify/adapter-core'; - -/** - * Runs the {@link operation} with the the context created from the {@link nextServerContext}. - * - * @param input The input to call the {@link runWithAmplifyServerContext}. - * @param input.nextServerContext The Next.js server context. It varies depends - * where the {@link runWithAmplifyServerContext} is being called. - * - In the [middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware): - * the context consists of an instance of the `NextRequest` and an instance - * of the `NextResponse`. - * - In a [Page server component](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#pages): - * the context is the [`cookies`](https://nextjs.org/docs/app/api-reference/functions/cookies) - * function provided by Next.js. - * - In a [Route Handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers): - * the context can be the [`cookies`](https://nextjs.org/docs/app/api-reference/functions/cookies) - * function or a combination of an instance of the `NextRequest` and an instance - * of the `NextResponse`. - * - In a [Server Action](https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations#how-server-actions-work): - * the context is the [`cookies`](https://nextjs.org/docs/app/api-reference/functions/cookies) - * function provided by Next.js. - * @param input.operation The function that contains the business logic calling - * Amplify APIs. It expects a `contextSpec` parameter. - * @returns The result returned by the {@link operation}. - * @example - * // Use the `fetchAuthSession` API in the Next.js `middleware`. - * import { NextRequest, NextResponse } from "next/server"; - * import { fetchAuthSession } from "aws-amplify/auth/server"; - * import { runWithAmplifyServerContext } from "@aws-amplify/adapter-nextjs"; - - * export async function middleware(request: NextRequest) { - * const response = NextResponse.next(); - * const authenticated = await runWithAmplifyServerContext({ - * nextServerContext: { request, response }, - * operation: async (contextSpec) => { - * const session = await fetchAuthSession(contextSpec); - * return session.tokens !== undefined; - * } - * }); - * if (authenticated) { - * return response; - * } - * return NextResponse.redirect(new URL('/sign-in', request.url)); - * } - */ -export const runWithAmplifyServerContext: NextServer.RunOperationWithContext = - async ({ nextServerContext, operation }) => { - // 1. get amplify config from env vars - // 2. create key-value storage from nextServerContext - // 3. create credentials provider - // 4. create token provider - // 5. call low level runWithAmplifyServerContext - const amplifyConfig = getAmplifyConfig(); - - // When the Auth config is presented, attempt to create a Amplify server - // context with token and credentials provider. - if (amplifyConfig.Auth) { - const keyValueStorage = - // When `null` is passed as the value of `nextServerContext`, opt-in - // unauthenticated role (primarily for static rendering). It's - // safe to use the singleton `MemoryKeyValueStorage` here, as the - // static rendering uses the same unauthenticated role cross-sever. - nextServerContext === null - ? sharedInMemoryStorage - : createKeyValueStorageFromCookieStorageAdapter( - createCookieStorageAdapterFromNextServerContext(nextServerContext) - ); - const credentialsProvider = createAWSCredentialsAndIdentityIdProvider( - amplifyConfig.Auth, - keyValueStorage - ); - const tokenProvider = createUserPoolsTokenProvider( - amplifyConfig.Auth, - keyValueStorage - ); - - return runWithAmplifyServerContextCore( - amplifyConfig, - { - Auth: { credentialsProvider, tokenProvider }, - }, - operation - ); - } - - // Otherwise it may be the case that auth is not used, e.g. API key. - // Omitting the `Auth` in the second parameter. - return runWithAmplifyServerContextCore(amplifyConfig, {}, operation); - }; diff --git a/packages/adapter-nextjs/src/types/NextServer.ts b/packages/adapter-nextjs/src/types/NextServer.ts index ed9f31ba606..78496433092 100644 --- a/packages/adapter-nextjs/src/types/NextServer.ts +++ b/packages/adapter-nextjs/src/types/NextServer.ts @@ -4,7 +4,9 @@ import { GetServerSidePropsContext as NextGetServerSidePropsContext } from 'next'; import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; +import { LegacyConfig } from 'aws-amplify/adapter-core'; import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core'; +import { ResourcesConfig } from '@aws-amplify/core'; export namespace NextServer { /** @@ -75,4 +77,16 @@ export namespace NextServer { input: RunWithContextInput ): Promise; } + + export interface CreateServerRunnerInput { + config: ResourcesConfig | LegacyConfig; + } + + export interface CreateServerRunnerOutput { + runWithAmplifyServerContext: RunOperationWithContext; + } + + export interface CreateServerRunner { + (input: CreateServerRunnerInput): CreateServerRunnerOutput; + } } diff --git a/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts b/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts new file mode 100644 index 00000000000..6362d1149a8 --- /dev/null +++ b/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts @@ -0,0 +1,61 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ResourcesConfig, sharedInMemoryStorage } from '@aws-amplify/core'; +import { + createAWSCredentialsAndIdentityIdProvider, + createKeyValueStorageFromCookieStorageAdapter, + createUserPoolsTokenProvider, + runWithAmplifyServerContext as runWithAmplifyServerContextCore, +} from 'aws-amplify/adapter-core'; + +import { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext'; +import { NextServer } from '../types'; + +export const createRunWithAmplifyServerContext = ({ + config: resourcesConfig, +}: { + config: ResourcesConfig; +}) => { + const runWithAmplifyServerContext: NextServer.RunOperationWithContext = + async ({ nextServerContext, operation }) => { + // When the Auth config is presented, attempt to create a Amplify server + // context with token and credentials provider. + if (resourcesConfig.Auth) { + const keyValueStorage = + // When `null` is passed as the value of `nextServerContext`, opt-in + // unauthenticated role (primarily for static rendering). It's + // safe to use the singleton `MemoryKeyValueStorage` here, as the + // static rendering uses the same unauthenticated role cross-sever. + nextServerContext === null + ? sharedInMemoryStorage + : createKeyValueStorageFromCookieStorageAdapter( + createCookieStorageAdapterFromNextServerContext( + nextServerContext + ) + ); + const credentialsProvider = createAWSCredentialsAndIdentityIdProvider( + resourcesConfig.Auth, + keyValueStorage + ); + const tokenProvider = createUserPoolsTokenProvider( + resourcesConfig.Auth, + keyValueStorage + ); + + return runWithAmplifyServerContextCore( + resourcesConfig, + { + Auth: { credentialsProvider, tokenProvider }, + }, + operation + ); + } + + // Otherwise it may be the case that auth is not used, e.g. API key. + // Omitting the `Auth` in the second parameter. + return runWithAmplifyServerContextCore(resourcesConfig, {}, operation); + }; + + return runWithAmplifyServerContext; +}; diff --git a/packages/adapter-nextjs/src/utils/getAmplifyConfig.ts b/packages/adapter-nextjs/src/utils/getAmplifyConfig.ts index e570586fd5b..f3f16dbb868 100644 --- a/packages/adapter-nextjs/src/utils/getAmplifyConfig.ts +++ b/packages/adapter-nextjs/src/utils/getAmplifyConfig.ts @@ -2,34 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { ResourcesConfig } from 'aws-amplify'; +import { LegacyConfig } from 'aws-amplify/adapter-core'; import { parseAWSExports } from '@aws-amplify/core/internals/utils'; -import { AmplifyServerContextError } from '@aws-amplify/core/internals/adapter-core'; -import getConfig from 'next/config'; -export const getAmplifyConfig = (): ResourcesConfig => { - let configStr = process.env.amplifyConfig; - - // With a Next.js app that uses the Pages Router, the key-value pairs - // listed under the `env` field in the `next.config.js` is not accessible - // via process.env. at some occasion. Using the following as a fallback - // See: https://github.com/vercel/next.js/issues/39299 - if (!configStr) { - const { serverRuntimeConfig } = getConfig() ?? {}; - configStr = serverRuntimeConfig?.amplifyConfig; - } - - if (!configStr) { - throw new AmplifyServerContextError({ - message: 'Amplify configuration is missing from `process.env`.', - recoverySuggestion: - 'Ensure to use `withAmplify` function in your `next.config.js`.', - }); - } - - const configObject = JSON.parse(configStr); - - // TODO(HuiSF): adds ResourcesConfig validation when it has one. - return Object.keys(configObject).some(key => key.startsWith('aws_')) - ? parseAWSExports(configObject) - : configObject; -}; +export const getAmplifyConfig = ( + config: ResourcesConfig | LegacyConfig +): ResourcesConfig => + Object.keys(config).some(key => key.startsWith('aws_')) + ? parseAWSExports(config) + : (config as ResourcesConfig); diff --git a/packages/adapter-nextjs/src/utils/index.ts b/packages/adapter-nextjs/src/utils/index.ts index e948f894c9a..e5fd9bb5f87 100644 --- a/packages/adapter-nextjs/src/utils/index.ts +++ b/packages/adapter-nextjs/src/utils/index.ts @@ -2,4 +2,4 @@ // SPDX-License-Identifier: Apache-2.0 export { getAmplifyConfig } from './getAmplifyConfig'; -export { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext'; +export { createRunWithAmplifyServerContext } from './createRunWithAmplifyServerContext'; diff --git a/packages/adapter-nextjs/src/withAmplify.ts b/packages/adapter-nextjs/src/withAmplify.ts deleted file mode 100644 index a6bd111a0d2..00000000000 --- a/packages/adapter-nextjs/src/withAmplify.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { ResourcesConfig } from 'aws-amplify'; -import { LegacyConfig } from 'aws-amplify/adapter-core'; -import { NextConfig } from 'next'; - -// NOTE: this function is exported from the subpath `/with-amplify`. -// The reason is that this function is called in the `next.config.js` which -// is not being transpiled by Next.js. - -/** - * Merges the `amplifyConfig` into the `nextConfig.env`. - * - * @param nextConfig The next config for a Next.js app. - * @param amplifyConfig The Amplify configuration. - * - * @returns The updated `nextConfig`. - */ -export const withAmplify = ( - nextConfig: NextConfig, - amplifyConfig: ResourcesConfig | LegacyConfig -) => { - const configStr = JSON.stringify(amplifyConfig); - nextConfig.env = { - ...nextConfig.env, - amplifyConfig: configStr, - }; - - nextConfig.serverRuntimeConfig = { - ...nextConfig.serverRuntimeConfig, - amplifyConfig: configStr, - }; - - return nextConfig; -}; diff --git a/packages/adapter-nextjs/with-amplify/package.json b/packages/adapter-nextjs/with-amplify/package.json deleted file mode 100644 index 4f35a31b04c..00000000000 --- a/packages/adapter-nextjs/with-amplify/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@aws-amplify/adapter-nextjs/with-amplify", - "main": "../lib/withAmplify.js", - "browser": "../lib-esm/withAmplify.js", - "module": "../lib-esm/withAmplify.js", - "typings": "../lib-esm/withAmplify.d.ts" -} From 702ee71dcd788e61b752b1bb77e0f7f27e6e5bd9 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 27 Oct 2023 15:00:54 -0700 Subject: [PATCH 05/45] chore(adapter-nextjs)!: rename generateServerClient to generateServerClientUsingReqRes --- .../__tests__/api/generateServerClient.test.ts | 8 +++++--- packages/adapter-nextjs/src/api/generateServerClient.ts | 6 +++--- packages/adapter-nextjs/src/api/index.ts | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index 2871b6b919e..8920cc3022a 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -1,7 +1,7 @@ import { ResourcesConfig } from '@aws-amplify/core'; import { generateServerClientUsingCookies, - generateServerClient, + generateServerClientUsingReqRes, } from '../../src/api'; import { getAmplifyConfig, @@ -75,7 +75,7 @@ describe('generateServerClient', () => { }); it('should call getAmlifyConfig', async () => { - generateServerClient({ config: mockAmplifyConfig }); + generateServerClientUsingReqRes({ config: mockAmplifyConfig }); expect(mockGetAmplifyConfig).toHaveBeenCalled(); }); @@ -97,7 +97,9 @@ describe('generateServerClient', () => { getAmplifyServerContext: () => {}, })); - const client = generateServerClient({ config: mockAmplifyConfig }); + const client = generateServerClientUsingReqRes({ + config: mockAmplifyConfig, + }); await runWithAmplifyServerContext({ nextServerContext: { diff --git a/packages/adapter-nextjs/src/api/generateServerClient.ts b/packages/adapter-nextjs/src/api/generateServerClient.ts index 6aa79ac2757..8c43c86e604 100644 --- a/packages/adapter-nextjs/src/api/generateServerClient.ts +++ b/packages/adapter-nextjs/src/api/generateServerClient.ts @@ -82,9 +82,9 @@ export function generateServerClientUsingCookies< }) * ``` */ -export function generateServerClient = never>({ - config, -}: NextServer.CreateServerRunnerInput): V6ClientSSR { +export function generateServerClientUsingReqRes< + T extends Record = never +>({ config }: NextServer.CreateServerRunnerInput): V6ClientSSR { const amplifyConfig = getAmplifyConfig(config); // passing `null` instance because each (future model) method must retrieve a valid instance // from server context diff --git a/packages/adapter-nextjs/src/api/index.ts b/packages/adapter-nextjs/src/api/index.ts index c8421e21667..7ef19ce221a 100644 --- a/packages/adapter-nextjs/src/api/index.ts +++ b/packages/adapter-nextjs/src/api/index.ts @@ -2,6 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 export { - generateServerClient, + generateServerClientUsingReqRes, generateServerClientUsingCookies, } from './generateServerClient'; From 48c195d3191547e241ba6b1b5bb0f44be48aa49f Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 30 Oct 2023 09:16:52 -0700 Subject: [PATCH 06/45] chore(adapter-nextjs): make package public --- packages/adapter-nextjs/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 9bac9ec7c1c..017555dc288 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -1,6 +1,5 @@ { "author": "Amazon Web Services", - "private": true, "name": "@aws-amplify/adapter-nextjs", "description": "The adapter for the supporting of using Amplify APIs in Next.js.", "peerDependencies": { From db86d67bac5d9193648c0988433ce3a31f5a21e5 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 12:14:08 -0500 Subject: [PATCH 07/45] chore: Re-enables SSR tests (#12468) --- .github/integ-config/integ-all.yml | 32 +++++++++++++++--------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/integ-config/integ-all.yml b/.github/integ-config/integ-all.yml index 02e02318e00..b027d310dbe 100644 --- a/.github/integ-config/integ-all.yml +++ b/.github/integ-config/integ-all.yml @@ -492,22 +492,22 @@ tests: sample_name: [delete-user] spec: delete-user browser: *minimal_browser_list - # - test_name: integ_next_auth_authenticator_and_ssr_page - # desc: 'Authenticator and SSR page' - # framework: next - # category: auth - # sample_name: [auth-ssr] - # spec: auth-ssr - # browser: [chrome] - # - test_name: integ_next_auth_authenticator_and_rsc_page - # desc: 'Authenticator and RSC page' - # framework: next - # category: auth - # sample_name: [auth-rsc] - # spec: auth-rsc - # browser: [chrome] - # timeout_minutes: 45 - # retry_count: 10 + - test_name: integ_next_auth_authenticator_and_ssr_page + desc: 'Authenticator and SSR page' + framework: next + category: auth + sample_name: [auth-ssr] + spec: auth-ssr + browser: [chrome] + - test_name: integ_next_auth_authenticator_and_rsc_page + desc: 'Authenticator and RSC page' + framework: next + category: auth + sample_name: [auth-rsc] + spec: auth-rsc + browser: [chrome] + timeout_minutes: 45 + retry_count: 10 # DISABLED Angular/Vue tests: # TODO: delete tests or add custom ui logic to support them. From b63359a0acd1c8266161e2816ac56753b2746f12 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 14:12:13 -0500 Subject: [PATCH 08/45] fix: Check for OAuth URLs before splitting (#12469) --- .../core/__tests__/parseAWSExports.test.ts | 38 +++++++++++++++++++ packages/core/src/parseAWSExports.ts | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/core/__tests__/parseAWSExports.test.ts b/packages/core/__tests__/parseAWSExports.test.ts index d17c97909dd..4dbe05a4221 100644 --- a/packages/core/__tests__/parseAWSExports.test.ts +++ b/packages/core/__tests__/parseAWSExports.test.ts @@ -236,4 +236,42 @@ describe('Parser', () => { }, }); }); + + it('should handle missing `redirectSignIn` or `redirectSignOut` configuration', () => { + expect( + parseAWSExports({ + aws_user_pools_id: userPoolId, + oauth: { + domain: oAuthDomain, + scope: oAuthScopes, + responseType: oAuthResponseType, + }, + }) + ).toStrictEqual({ + Auth: { + Cognito: { + allowGuestAccess: true, + identityPoolId: undefined, + loginWith: { + email: false, + oauth: { + domain: oAuthDomain, + redirectSignIn: [], + redirectSignOut: [], + responseType: oAuthResponseType, + scopes: oAuthScopes, + }, + phone: false, + username: true, + }, + mfa: undefined, + passwordFormat: undefined, + signUpVerificationMethod: undefined, + userAttributes: [], + userPoolClientId: undefined, + userPoolId: userPoolId, + }, + }, + }); + }); }); diff --git a/packages/core/src/parseAWSExports.ts b/packages/core/src/parseAWSExports.ts index 1ec3bfa551d..51719f0410e 100644 --- a/packages/core/src/parseAWSExports.ts +++ b/packages/core/src/parseAWSExports.ts @@ -276,7 +276,7 @@ export const parseAWSExports = ( }; const getRedirectUrl = (redirectStr: string): string[] => - redirectStr.split(','); + redirectStr?.split(',') ?? []; const getOAuthConfig = ({ domain, From c2423a38a88a0e23b65039ac6c5e346613b6ac52 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 14:41:01 -0500 Subject: [PATCH 09/45] chore: Setup v5 LTS CI infrastructure (#12455) (#12459) --- .../callable-npm-publish-lts-release.yml | 52 +++++++++++++++++++ .../workflows/callable-npm-publish-preid.yml | 2 +- .github/workflows/push-lts-release.yml | 25 +++++++++ package.json | 1 + 4 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/callable-npm-publish-lts-release.yml create mode 100644 .github/workflows/push-lts-release.yml diff --git a/.github/workflows/callable-npm-publish-lts-release.yml b/.github/workflows/callable-npm-publish-lts-release.yml new file mode 100644 index 00000000000..b4db35ab829 --- /dev/null +++ b/.github/workflows/callable-npm-publish-lts-release.yml @@ -0,0 +1,52 @@ +name: Release LTS version to npm and update repository + +on: + workflow_call: + inputs: + target: + required: true + type: string + +jobs: + deploy: + name: Publish to Amplify Package + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@24cb9080177205b6e8c946b17badbe402adc938f # v3.4.0 https://github.com/actions/checkout/commit/24cb9080177205b6e8c946b17badbe402adc938f + with: + path: amplify-js + token: ${{ secrets.GH_TOKEN_AMPLIFY_JS_WRITE }} + + - name: Setup node and build the repository + uses: ./amplify-js/.github/actions/node-and-build + + - name: Run npm publish + uses: ./amplify-js/.github/actions/npm-publish + with: + target: ${{ inputs.target }} + npm_token: ${{ secrets.NPM_TOKEN }} + github_user: ${{ vars.GH_USER}} + github_email: ${{ vars.GH_EMAIL}} + + - name: Set github commit user + env: + GITHUB_EMAIL: ${{ vars.GH_EMAIL }} + GITHUB_USER: ${{ vars.GH_USER }} + run: | + git config --global user.email $GITHUB_EMAIL + git config --global user.name $GITHUB_USER + + - name: Update API documentation + working-directory: ./amplify-js + run: | + yarn run docs + git add ./docs/api/ + git commit -m "chore(release): update API docs [ci skip]" + + - name: Push post release changes + working-directory: ./amplify-js + env: + TARGET_BRANCH: ${{ inputs.target }} + run: | + git push origin $TARGET_BRANCH diff --git a/.github/workflows/callable-npm-publish-preid.yml b/.github/workflows/callable-npm-publish-preid.yml index 8d3af4fbc7c..6152f46f331 100644 --- a/.github/workflows/callable-npm-publish-preid.yml +++ b/.github/workflows/callable-npm-publish-preid.yml @@ -22,7 +22,7 @@ jobs: ALLOW_PROTECTED_PREIDS: ${{ inputs.allow-protected-preid }} PREID: ${{ inputs.preid }} FORBIDDEN_PREIDS: latest - PROTECTED_PREIDS: next unstable + PROTECTED_PREIDS: next unstable stable-5 stable-4 run: | echo "Testing to see if $PREID is in the forbidden list ($FORBIDDEN_PREIDS)" for e in $FORBIDDEN_PREIDS; do [[ $PREID == $e ]] && echo "$PREID is forbidden from preid release" && exit 1; done diff --git a/.github/workflows/push-lts-release.yml b/.github/workflows/push-lts-release.yml new file mode 100644 index 00000000000..00704ba053a --- /dev/null +++ b/.github/workflows/push-lts-release.yml @@ -0,0 +1,25 @@ +name: Push - release from LTS branch to LTS dist tag + +concurrency: + # group name unique for push to push-latest-release + group: push-lts-release-${{ github.ref }} + cancel-in-progress: true + +on: + push: + branches: + - v5-stable + +jobs: + e2e: + secrets: inherit + uses: ./.github/workflows/callable-release-verification.yml + release: + needs: + - e2e + permissions: + contents: write + secrets: inherit + uses: ./.github/workflows/callable-npm-publish-lts-release.yml + with: + target: v5-stable # TODO Update this to support other LTS branches in the future diff --git a/package.json b/package.json index 708f3fd7f38..9fb5f820530 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "publish:preid": "./scripts/preid-env-vars-exist.sh && lerna publish --canary --force-publish --dist-tag=${PREID_PREFIX} --preid=${PREID_PREFIX}${PREID_HASH_SUFFIX} --yes", "publish:main": "lerna publish --canary --force-publish --dist-tag=unstable --preid=unstable${PREID_HASH_SUFFIX} --yes", "publish:release": "lerna publish --conventional-commits --dist-tag=v6 --message 'chore(release): Publish [ci skip]' --yes", + "publish:v5-stable": "lerna publish --conventional-commits --yes --dist-tag=stable-5 --message 'chore(release): Publish [ci skip]' --no-verify-access", "publish:verdaccio": "lerna publish --canary --force-publish --no-push --dist-tag=unstable --preid=unstable --yes", "ts-coverage": "lerna run ts-coverage", "prepare": "./scripts/set-preid-versions.sh" From bd880d3bfc7eb9c501b23f19da7dbe347700f505 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Mon, 30 Oct 2023 15:13:50 -0500 Subject: [PATCH 10/45] chore: Update yarn.lock (#12471) --- yarn.lock | 135 +++++++++++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 78 deletions(-) diff --git a/yarn.lock b/yarn.lock index e91de575389..488a9aa6d4f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4981,9 +4981,9 @@ acorn-walk@^6.0.1: integrity sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA== acorn-walk@^8.0.0: - version "8.2.0" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.2.0.tgz#741210f2e2426454508853a2f44d0ab83b7f69c1" - integrity sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA== + version "8.3.0" + resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.3.0.tgz#2097665af50fd0cf7a2dfccd2b9368964e66540f" + integrity sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA== acorn@^5.5.3: version "5.7.4" @@ -4996,9 +4996,9 @@ acorn@^6.0.1: integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ== acorn@^8.0.4, acorn@^8.7.1, acorn@^8.8.2: - version "8.10.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.10.0.tgz#8be5b3907a67221a81ab23c7889c4c5526b62ec5" - integrity sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw== + version "8.11.2" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.11.2.tgz#ca0d78b51895be5390a5903c5b3bdcdaf78ae40b" + integrity sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w== add-stream@^1.0.0: version "1.0.0" @@ -5383,9 +5383,9 @@ aws4@^1.8.0: integrity sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg== axios@^1.0.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/axios/-/axios-1.5.1.tgz#11fbaa11fc35f431193a9564109c88c1f27b585f" - integrity sha512-Q28iYCWzNHjAm+yEAot5QaAMxhMghWLFVf7rRdwhUI+c2jix2DUXjAHXVi+s1ibs3mjPO/cCgbA++3BjD0vP/A== + version "1.6.0" + resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.0.tgz#f1e5292f26b2fd5c2e66876adc5b06cdbd7d2102" + integrity sha512-EZ1DYihju9pwVB+jg67ogm+Tmqc6JmhamRN6I4Zt8DfZu5lbcQGw3ozH9lFejSJgs/ibaef3A9PMXPLeefFGJg== dependencies: follow-redirects "^1.15.0" form-data "^4.0.0" @@ -5928,9 +5928,9 @@ camelcase@^6.0.0, camelcase@^6.2.0: integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== caniuse-lite@^1.0.30001406, caniuse-lite@^1.0.30001541: - version "1.0.30001554" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001554.tgz#ba80d88dff9acbc0cd4b7535fc30e0191c5e2e2a" - integrity sha512-A2E3U//MBwbJVzebddm1YfNp7Nud5Ip+IPn4BozBmn4KqVX7AvluoIDFWjsv5OkGnKUXQVmMSoMKLa3ScCblcQ== + version "1.0.30001558" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001558.tgz#d2c6e21fdbfe83817f70feab902421a19b7983ee" + integrity sha512-/Et7DwLqpjS47JPEcz6VnxU9PwcIdVi0ciLXRWBQdj1XFye68pSQYpV0QtPTfUKWuOaEig+/Vez2l74eDc1tPQ== capture-exit@^2.0.0: version "2.0.0" @@ -6520,16 +6520,16 @@ copy-descriptor@^0.1.0: integrity sha512-XgZ0pFcakEUlbwQEVNg3+QAis1FyTL3Qel9FYy8pSkQqoG3PNoT0bOCQtOXcOkur21r2Eq2kI+IE+gsmAEVlYw== core-js-compat@^3.31.0, core-js-compat@^3.33.1: - version "3.33.1" - resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.33.1.tgz#debe80464107d75419e00c2ee29f35982118ff84" - integrity sha512-6pYKNOgD/j/bkC5xS5IIg6bncid3rfrI42oBH1SQJbsmYPKF7rhzcFzYCcxYMmNQQ0rCEB8WqpW7QHndOggaeQ== + version "3.33.2" + resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.33.2.tgz#3ea4563bfd015ad4e4b52442865b02c62aba5085" + integrity sha512-axfo+wxFVxnqf8RvxTzoAlzW4gRoacrHeoFlc9n0x50+7BEyZL/Rt3hicaED1/CEd7I6tPCPVUYcJwCMO5XUYw== dependencies: browserslist "^4.22.1" core-js@^3.4: - version "3.33.1" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.33.1.tgz#ef3766cfa382482d0a2c2bc5cb52c6d88805da52" - integrity sha512-qVSq3s+d4+GsqN0teRCJtM6tdEEXyWxjzbhVrCHmBS5ZTM0FS2MOS0D13dUXAWDUN6a+lHI/N1hF9Ytz6iLl9Q== + version "3.33.2" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.33.2.tgz#312bbf6996a3a517c04c99b9909cdd27138d1ceb" + integrity sha512-XeBzWI6QL3nJQiHmdzbAOiMYqjrb7hwU7A39Qhvd/POSa/t9E1AeZyEZx3fNvp/vtM8zXwhoL0FsiS0hD0pruQ== core-util-is@1.0.2: version "1.0.2" @@ -6947,9 +6947,9 @@ ejs@^3.1.7: jake "^10.8.5" electron-to-chromium@^1.4.535: - version "1.4.567" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.567.tgz#c92e8fbc2bd15df3068d92571733a218a5413add" - integrity sha512-8KR114CAYQ4/r5EIEsOmOMqQ9j0MRbJZR3aXD/KFA8RuKzyoUB4XrUCg+l8RUGqTVQgKNIgTpjaG8YHRPAbX2w== + version "1.4.570" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.570.tgz#5fb79061ead248a411bc8532da34d1dbf6ae23c1" + integrity sha512-5GxH0PLSIfXKOUMMHMCT4M0olwj1WwAxsQHzVW5Vh3kbsvGw8b4k7LHQmTLC2aRhsgFzrF57XJomca4XLc/WHA== emoji-regex@^7.0.1: version "7.0.3" @@ -7656,9 +7656,9 @@ flow-enums-runtime@^0.0.5: integrity sha512-PSZF9ZuaZD03sT9YaIs0FrGJ7lSUw7rHZIex+73UYVXg46eL/wxN5PaVcPJFudE2cJu5f0fezitV5aBkLHPUOQ== flow-parser@0.*: - version "0.219.5" - resolved "https://registry.yarnpkg.com/flow-parser/-/flow-parser-0.219.5.tgz#bff08036bd8f2aa7ebfd54a580dc418e37bc9c0e" - integrity sha512-lHx/cl2XjopBx/ma9RYhG7FGj2JLKacoBwtI3leOp8AwRDPGwu6bzJoaCMfIl/sq14KdtY5MGzd5q6nKfGzcuQ== + version "0.220.0" + resolved "https://registry.yarnpkg.com/flow-parser/-/flow-parser-0.220.0.tgz#de184e9da22b47ead09cf40ab4e781a17149017d" + integrity sha512-Fks+nOCqhorp4NpAtAxf09UaR/9xDf3AnU1UkWczmpneoHh06Y3AoEA4tIe2HbYrOHT9JArUgDZpCFhP4clo1A== flow-parser@^0.121.0: version "0.121.0" @@ -8743,19 +8743,12 @@ ip@^2.0.0: resolved "https://registry.yarnpkg.com/ip/-/ip-2.0.0.tgz#4cf4ab182fee2314c75ede1276f8c80b479936da" integrity sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ== -is-accessor-descriptor@^0.1.6: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" - integrity sha512-e1BM1qnDbMRG3ll2U9dSK0UMHuWOs3pY3AtcFsmvwPtKL3MML/Q86i+GilLfvqEs4GW+ExB91tQ3Ig9noDIZ+A== - dependencies: - kind-of "^3.0.2" - -is-accessor-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" - integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== +is-accessor-descriptor@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.1.tgz#3223b10628354644b86260db29b3e693f5ceedd4" + integrity sha512-YBUanLI8Yoihw923YeFUS5fs0fF2f5TSFTNiYAAzhhDscDa3lEqYuz1pDOEP5KvX94I9ey3vsqjJcLVFVU+3QA== dependencies: - kind-of "^6.0.0" + hasown "^2.0.0" is-arguments@^1.0.4: version "1.1.1" @@ -8830,19 +8823,12 @@ is-core-module@^2.13.0, is-core-module@^2.5.0, is-core-module@^2.8.1: dependencies: hasown "^2.0.0" -is-data-descriptor@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" - integrity sha512-+w9D5ulSoBNlmw9OHn3U2v51SyoCd0he+bB3xMl62oijhrspxowjU+AIcDY0N3iEJbUEkB15IlMASQsxYigvXg== - dependencies: - kind-of "^3.0.2" - -is-data-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" - integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== +is-data-descriptor@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.1.tgz#2109164426166d32ea38c405c1e0945d9e6a4eeb" + integrity sha512-bc4NlCDiCr28U4aEsQ3Qs2491gVq4V8G7MQyws968ImqjKuYtTJXrl7Vq7jsN7Ly/C3xj5KWFrY7sHNeDkAzXw== dependencies: - kind-of "^6.0.0" + hasown "^2.0.0" is-date-object@^1.0.1: version "1.0.5" @@ -8852,22 +8838,20 @@ is-date-object@^1.0.1: has-tostringtag "^1.0.0" is-descriptor@^0.1.0: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" - integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== + version "0.1.7" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.7.tgz#2727eb61fd789dcd5bdf0ed4569f551d2fe3be33" + integrity sha512-C3grZTvObeN1xud4cRWl366OMXZTj0+HGyk4hvfpx4ZHt1Pb60ANSXqCK7pdOTeUQpRzECBSTphqvD7U+l22Eg== dependencies: - is-accessor-descriptor "^0.1.6" - is-data-descriptor "^0.1.4" - kind-of "^5.0.0" + is-accessor-descriptor "^1.0.1" + is-data-descriptor "^1.0.1" is-descriptor@^1.0.0, is-descriptor@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" - integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== + version "1.0.3" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.3.tgz#92d27cb3cd311c4977a4db47df457234a13cb306" + integrity sha512-JCNNGbwWZEVaSPtS45mdtrneRWJFp07LLmykxeFV5F6oBvNF8vHSfJuJgoT472pSfk+Mf8VnlrspaFBHWM8JAw== dependencies: - is-accessor-descriptor "^1.0.0" - is-data-descriptor "^1.0.0" - kind-of "^6.0.2" + is-accessor-descriptor "^1.0.1" + is-data-descriptor "^1.0.1" is-directory@^0.3.1: version "0.3.1" @@ -9966,12 +9950,7 @@ kind-of@^4.0.0: dependencies: is-buffer "^1.1.5" -kind-of@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" - integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== - -kind-of@^6.0.0, kind-of@^6.0.2, kind-of@^6.0.3: +kind-of@^6.0.2, kind-of@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== @@ -10393,7 +10372,7 @@ make-error@1.x: resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== -make-fetch-happen@^10.0.6: +make-fetch-happen@^10.0.3, make-fetch-happen@^10.0.6: version "10.2.1" resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-10.2.1.tgz#f5e3835c5e9817b617f2770870d9492d28678164" integrity sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w== @@ -10415,7 +10394,7 @@ make-fetch-happen@^10.0.6: socks-proxy-agent "^7.0.0" ssri "^9.0.0" -make-fetch-happen@^11.0.0, make-fetch-happen@^11.0.1, make-fetch-happen@^11.0.3, make-fetch-happen@^11.1.1: +make-fetch-happen@^11.0.0, make-fetch-happen@^11.0.1, make-fetch-happen@^11.1.1: version "11.1.1" resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-11.1.1.tgz#85ceb98079584a9523d4bf71d32996e7e208549f" integrity sha512-rLWS7GCSTcEujjVBs2YqG7Y4643u8ucvCJeSRqiLYhesrDuzeuFIk37xREzAsfQaqzl8b9rNCE4m6J8tvX4Q8w== @@ -11899,15 +11878,15 @@ node-gyp@8.x: which "^2.0.2" node-gyp@^9.0.0: - version "9.4.0" - resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-9.4.0.tgz#2a7a91c7cba4eccfd95e949369f27c9ba704f369" - integrity sha512-dMXsYP6gc9rRbejLXmTbVRYjAHw7ppswsKyMxuxJxxOHzluIO1rGp9TOQgjFJ+2MCqcOcQTOPB/8Xwhr+7s4Eg== + version "9.4.1" + resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-9.4.1.tgz#8a1023e0d6766ecb52764cc3a734b36ff275e185" + integrity sha512-OQkWKbjQKbGkMf/xqI1jjy3oCTgMKJac58G2+bjZb3fza6gW2YrCSdMQYaoTb70crvE//Gngr4f0AgVHmqHvBQ== dependencies: env-paths "^2.2.0" exponential-backoff "^3.1.1" glob "^7.1.4" graceful-fs "^4.2.6" - make-fetch-happen "^11.0.3" + make-fetch-happen "^10.0.3" nopt "^6.0.0" npmlog "^6.0.0" rimraf "^3.0.2" @@ -13113,9 +13092,9 @@ punycode@^1.3.2: integrity sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ== punycode@^2.1.0, punycode@^2.1.1: - version "2.3.0" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f" - integrity sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA== + version "2.3.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" + integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== q@^1.4.1, q@^1.5.1: version "1.5.1" @@ -14986,9 +14965,9 @@ terser-webpack-plugin@^5.3.6, terser-webpack-plugin@^5.3.7: terser "^5.16.8" terser@^5.15.0, terser@^5.16.8: - version "5.22.0" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.22.0.tgz#4f18103f84c5c9437aafb7a14918273310a8a49d" - integrity sha512-hHZVLgRA2z4NWcN6aS5rQDc+7Dcy58HOf2zbYwmFcQ+ua3h6eEFf5lIDKTzbWwlazPyOZsFQO8V80/IjVNExEw== + version "5.23.0" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.23.0.tgz#a9c02bc3087d0f5b1cc63bbfb4fe0f7e5dbbde82" + integrity sha512-Iyy83LN0uX9ZZLCX4Qbu5JiHiWjOCTwrmM9InWOzVeM++KNWEsqV4YgN9U9E8AlohQ6Gs42ztczlWOG/lwDAMA== dependencies: "@jridgewell/source-map" "^0.3.3" acorn "^8.8.2" From 18f89760abfd8c8149dd3ac43411fd13a15f8ea8 Mon Sep 17 00:00:00 2001 From: erinleigh90 <106691284+erinleigh90@users.noreply.github.com> Date: Mon, 30 Oct 2023 14:13:12 -0700 Subject: [PATCH 11/45] feat(predictions): specify identifyEntity metadata type (#12470) * feat: specify identifyEntity metadata type * fix: add missing properties to metadata --------- Co-authored-by: Venkata Ramyasri Kota <34170013+kvramyasri7@users.noreply.github.com> --- packages/predictions/src/types/Predictions.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/predictions/src/types/Predictions.ts b/packages/predictions/src/types/Predictions.ts index df3695a35fe..cc502c4e34b 100644 --- a/packages/predictions/src/types/Predictions.ts +++ b/packages/predictions/src/types/Predictions.ts @@ -284,18 +284,33 @@ export type EntityAgeRange = { low?: Number; high?: Number; }; + export type EntityLandmark = { type?: string; x?: number; y?: number; }; +export type EntityMetadata = { + id?: string; + name?: string; + pose?: { + roll?: number; + yaw?: number; + pitch?: number; + }; + urls?: string[]; + externalImageId?: string; + similarity?: number; + confidence?: number; +}; + export type IdentifyEntity = { boundingBox?: BoundingBox; ageRange?: EntityAgeRange; landmarks?: (EntityLandmark | undefined)[]; attributes?: FaceAttributes; - metadata?: object; + metadata?: EntityMetadata; }; export interface IdentifyEntitiesOutput { From 20e9a799c8260f61a4b4d7d637b67f5d0e427322 Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Mon, 30 Oct 2023 15:12:48 -0700 Subject: [PATCH 12/45] fix(storage): address actionable TODOs (#12414) --------- Co-authored-by: Venkata Ramyasri Kota <34170013+kvramyasri7@users.noreply.github.com> --- packages/aws-amplify/package.json | 8 ++++---- .../core/__tests__/Platform/userAgent.test.ts | 1 - .../__tests__/providers/s3/apis/copy.test.ts | 4 +++- .../providers/s3/apis/downloadData.test.ts | 6 +++--- .../providers/s3/apis/getProperties.test.ts | 4 +++- .../__tests__/providers/s3/apis/getUrl.test.ts | 4 +++- .../__tests__/providers/s3/apis/list.test.ts | 4 +++- .../__tests__/providers/s3/apis/remove.test.ts | 4 +++- .../providers/s3/apis/uploadData/index.test.ts | 2 -- .../apis/uploadData/multipartHandlers.test.ts | 2 +- .../s3/utils/client/xmlParser-fixture.ts | 2 +- packages/storage/src/index.ts | 1 - .../src/providers/s3/apis/downloadData.ts | 8 ++++---- .../src/providers/s3/apis/internal/copy.ts | 15 +++++++++------ .../s3/apis/internal/getProperties.ts | 13 +++++++++---- .../src/providers/s3/apis/internal/list.ts | 18 ++++++++++++++---- .../src/providers/s3/apis/internal/remove.ts | 10 ++++++---- .../providers/s3/apis/uploadData/byteLength.ts | 2 +- .../uploadData/multipart/getDataChunker.ts | 9 ++++----- .../apis/uploadData/multipart/initialUpload.ts | 7 +++---- .../apis/uploadData/multipart/uploadCache.ts | 5 +++-- .../uploadData/multipart/uploadHandlers.ts | 6 +++--- .../uploadData/multipart/uploadPartExecutor.ts | 8 ++++---- .../s3/apis/uploadData/putObjectJob.ts | 6 ++---- .../src/providers/s3/utils/client/getObject.ts | 4 +--- .../src/providers/s3/utils/client/types.ts | 18 +++++++++++------- .../s3/utils/resolveS3ConfigAndInput.ts | 2 -- .../src/providers/s3/utils/transferTask.ts | 4 ++++ packages/storage/src/utils/index.ts | 1 + packages/storage/src/utils/logger.ts | 6 ++++++ 30 files changed, 109 insertions(+), 75 deletions(-) create mode 100644 packages/storage/src/utils/logger.ts diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index dd00000c0d5..4a3af55b280 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -418,7 +418,7 @@ "name": "[Storage] copy (S3)", "path": "./lib-esm/storage/index.js", "import": "{ copy }", - "limit": "12.94 kB" + "limit": "12.98 kB" }, { "name": "[Storage] downloadData (S3)", @@ -442,19 +442,19 @@ "name": "[Storage] list (S3)", "path": "./lib-esm/storage/index.js", "import": "{ list }", - "limit": "13.26 kB" + "limit": "13.39 kB" }, { "name": "[Storage] remove (S3)", "path": "./lib-esm/storage/index.js", "import": "{ remove }", - "limit": "12.78 kB" + "limit": "12.82 kB" }, { "name": "[Storage] uploadData (S3)", "path": "./lib-esm/storage/index.js", "import": "{ uploadData }", - "limit": "17.81 kB" + "limit": "17.99 kB" } ], "jest": { diff --git a/packages/core/__tests__/Platform/userAgent.test.ts b/packages/core/__tests__/Platform/userAgent.test.ts index 0780e7b9c2c..b363452b55c 100644 --- a/packages/core/__tests__/Platform/userAgent.test.ts +++ b/packages/core/__tests__/Platform/userAgent.test.ts @@ -49,7 +49,6 @@ describe('Platform test', () => { ]); }); - /* TODO: test with actual API action */ test('with customUserAgentDetails', () => { expect( getAmplifyUserAgentObject({ diff --git a/packages/storage/__tests__/providers/s3/apis/copy.test.ts b/packages/storage/__tests__/providers/s3/apis/copy.test.ts index f859b5e82dd..74c1821c5bc 100644 --- a/packages/storage/__tests__/providers/s3/apis/copy.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/copy.test.ts @@ -12,7 +12,9 @@ import { jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { diff --git a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts index d26d4e7fd78..646799c77cb 100644 --- a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts @@ -11,7 +11,9 @@ import { DownloadDataOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('../../../../src/providers/s3/utils'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { @@ -34,8 +36,6 @@ const mockFetchAuthSession = Amplify.Auth.fetchAuthSession as jest.Mock; const mockCreateDownloadTask = createDownloadTask as jest.Mock; const mockGetConfig = Amplify.getConfig as jest.Mock; -// TODO: test validation errors -// TODO: test downloadData from guest, private, protected access level respectively. describe('downloadData', () => { beforeAll(() => { mockFetchAuthSession.mockResolvedValue({ diff --git a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts index 761094ec208..9ec68618a05 100644 --- a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts @@ -9,7 +9,9 @@ import { GetPropertiesOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { diff --git a/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts b/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts index 8a9b4c131dc..d32bf670a32 100644 --- a/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/getUrl.test.ts @@ -12,7 +12,9 @@ import { GetUrlOptions } from '../../../../src/providers/s3/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { diff --git a/packages/storage/__tests__/providers/s3/apis/list.test.ts b/packages/storage/__tests__/providers/s3/apis/list.test.ts index 88762c365cf..2e9d79a8710 100644 --- a/packages/storage/__tests__/providers/s3/apis/list.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/list.test.ts @@ -12,7 +12,9 @@ import { jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { diff --git a/packages/storage/__tests__/providers/s3/apis/remove.test.ts b/packages/storage/__tests__/providers/s3/apis/remove.test.ts index c3f716f8a7c..b5c1f3902ce 100644 --- a/packages/storage/__tests__/providers/s3/apis/remove.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/remove.test.ts @@ -9,7 +9,9 @@ import { StorageOptions } from '../../../../src/types'; jest.mock('../../../../src/providers/s3/utils/client'); jest.mock('@aws-amplify/core', () => ({ - ConsoleLogger: jest.fn(), + ConsoleLogger: jest.fn().mockImplementation(function ConsoleLogger() { + return { debug: jest.fn() }; + }), Amplify: { getConfig: jest.fn(), Auth: { diff --git a/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts b/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts index fa5dbec670a..813d4bfbfdc 100644 --- a/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts @@ -52,8 +52,6 @@ describe('uploadData', () => { }); expect(mockCreateUploadTask).toBeCalled(); }); - - // TODO[AllanZhengYP]: Make sure common S3 configs and input validation utility is called. }); describe('use putObject', () => { diff --git a/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts b/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts index 35786782aef..b494b2735d6 100644 --- a/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts @@ -176,7 +176,7 @@ describe('getMultipartUploadHandlers', () => { it.each([ ['file', new File([getBlob(8 * MB)], 'someName')], ['blob', getBlob(8 * MB)], - ['string', '1'.repeat(8 * MB)], + ['string', 'Ü'.repeat(4 * MB)], ['arrayBuffer', new ArrayBuffer(8 * MB)], ['arrayBufferView', new Uint8Array(8 * MB)], ])( diff --git a/packages/storage/__tests__/providers/s3/utils/client/xmlParser-fixture.ts b/packages/storage/__tests__/providers/s3/utils/client/xmlParser-fixture.ts index d26a8480872..95c9bc559aa 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/xmlParser-fixture.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/xmlParser-fixture.ts @@ -233,7 +233,7 @@ const cases = [ `, expected: expect.objectContaining({ stringValue: 'string', - }), // TODO: non-browser parser from AWS SDK populates extra property. It won'd affect service handler. + }), // Non-browser parser from AWS SDK populates extra property. It won'd affect service handler. }, { spec: '', diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 647a498cf1c..6183ed3a2d5 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -35,6 +35,5 @@ export { export { TransferProgressEvent } from './types'; -// TODO[AllanZhengYP]: support isCancelError in Node.js with node-fetch export { isCancelError } from './errors/CanceledError'; export { StorageError } from './errors/StorageError'; diff --git a/packages/storage/src/providers/s3/apis/downloadData.ts b/packages/storage/src/providers/s3/apis/downloadData.ts index a44bed58488..281f73a7456 100644 --- a/packages/storage/src/providers/s3/apis/downloadData.ts +++ b/packages/storage/src/providers/s3/apis/downloadData.ts @@ -10,6 +10,7 @@ import { StorageValidationErrorCode } from '../../../errors/types/validation'; import { createDownloadTask } from '../utils'; import { getObject } from '../utils/client'; import { getStorageUserAgentValue } from '../utils/userAgent'; +import { logger } from '../../../utils'; /** * Download S3 object data to memory @@ -63,9 +64,10 @@ const downloadDataJob = Amplify, downloadDataOptions ); - // TODO[AllanZhengYP]: support excludeSubPaths option to exclude sub paths const finalKey = keyPrefix + key; + logger.debug(`download ${key} from ${finalKey}.`); + const { Body: body, LastModified: lastModified, @@ -90,10 +92,8 @@ const downloadDataJob = } ); return { - // Casting with ! as body always exists for getObject API. - // TODO[AllanZhengYP]: remove casting when we have better typing for getObject API key, - body: body!, + body, lastModified, size, contentType, diff --git a/packages/storage/src/providers/s3/apis/internal/copy.ts b/packages/storage/src/providers/s3/apis/internal/copy.ts index 3644f0b96dc..47afbc9107e 100644 --- a/packages/storage/src/providers/s3/apis/internal/copy.ts +++ b/packages/storage/src/providers/s3/apis/internal/copy.ts @@ -9,6 +9,7 @@ import { StorageValidationErrorCode } from '../../../../errors/types/validation' import { assertValidationError } from '../../../../errors/utils/assertValidationError'; import { copyObject } from '../../utils/client'; import { getStorageUserAgentValue } from '../../utils/userAgent'; +import { logger } from '../../../../utils'; export const copy = async ( amplify: AmplifyClassV6, @@ -36,16 +37,18 @@ export const copy = async ( ); // resolveS3ConfigAndInput does not make extra API calls or storage access if called repeatedly. // TODO(ashwinkumar6) V6-logger: warn `You may copy files from another user if the source level is "protected", currently it's ${srcLevel}` - // TODO(ashwinkumar6) V6-logger: debug `copying ${finalSrcKey} to ${finalDestKey}` + const finalCopySource = `${bucket}/${sourceKeyPrefix}${sourceKey}`; + const finalCopyDestination = `${destinationKeyPrefix}${destinationKey}`; + logger.debug(`copying "${finalCopySource}" to "${finalCopyDestination}".`); await copyObject( { - ...s3Config, - userAgentValue: getStorageUserAgentValue(StorageAction.Copy) - }, + ...s3Config, + userAgentValue: getStorageUserAgentValue(StorageAction.Copy), + }, { Bucket: bucket, - CopySource: `${bucket}/${sourceKeyPrefix}${sourceKey}`, - Key: `${destinationKeyPrefix}${destinationKey}`, + CopySource: finalCopySource, + Key: finalCopyDestination, MetadataDirective: 'COPY', // Copies over metadata like contentType as well } ); diff --git a/packages/storage/src/providers/s3/apis/internal/getProperties.ts b/packages/storage/src/providers/s3/apis/internal/getProperties.ts index e2807ac35fd..cd75852b38f 100644 --- a/packages/storage/src/providers/s3/apis/internal/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/internal/getProperties.ts @@ -7,6 +7,7 @@ import { GetPropertiesInput, GetPropertiesOutput } from '../../types'; import { resolveS3ConfigAndInput } from '../../utils'; import { headObject } from '../../utils/client'; import { getStorageUserAgentValue } from '../../utils/userAgent'; +import { logger } from '../../../../utils'; export const getProperties = async function ( amplify: AmplifyClassV6, @@ -18,15 +19,19 @@ export const getProperties = async function ( amplify, options ); + const finalKey = `${keyPrefix}${key}`; + logger.debug(`get properties of ${key} from ${finalKey}`); const response = await headObject( { - ...s3Config, - userAgentValue: getStorageUserAgentValue(action ?? StorageAction.GetProperties) - }, + ...s3Config, + userAgentValue: getStorageUserAgentValue( + action ?? StorageAction.GetProperties + ), + }, { Bucket: bucket, - Key: `${keyPrefix}${key}`, + Key: finalKey, } ); return { diff --git a/packages/storage/src/providers/s3/apis/internal/list.ts b/packages/storage/src/providers/s3/apis/internal/list.ts index 8118254147d..1e90565e6a9 100644 --- a/packages/storage/src/providers/s3/apis/internal/list.ts +++ b/packages/storage/src/providers/s3/apis/internal/list.ts @@ -18,6 +18,7 @@ import { ListObjectsV2Output, } from '../../utils/client'; import { getStorageUserAgentValue } from '../../utils/userAgent'; +import { logger } from '../../../../utils'; const MAX_PAGE_SIZE = 1000; @@ -37,12 +38,22 @@ export const list = async ( bucket, keyPrefix: prefix, } = await resolveS3ConfigAndInput(amplify, options); + // @ts-expect-error pageSize and nextToken should not coexist with listAll + if (options?.listAll && (options?.pageSize || options?.nextToken)) { + const anyOptions = options as any; + logger.debug( + `listAll is set to true, ignoring ${ + anyOptions?.pageSize ? `pageSize: ${anyOptions?.pageSize}` : '' + } ${anyOptions?.nextToken ? `nextToken: ${anyOptions?.nextToken}` : ''}.` + ); + } const listParams = { Bucket: bucket, Prefix: `${prefix}${path}`, MaxKeys: options?.listAll ? undefined : options?.pageSize, ContinuationToken: options?.listAll ? undefined : options?.nextToken, }; + logger.debug(`listing items from "${listParams.Prefix}"`); return options.listAll ? await _listAll({ s3Config, listParams, prefix }) : await _list({ s3Config, listParams, prefix }); @@ -53,7 +64,6 @@ const _listAll = async ({ listParams, prefix, }: ListInputArgs): Promise => { - // TODO(ashwinkumar6) V6-logger: pageSize and nextToken aren't required when listing all items const listResult: ListOutputItem[] = []; let continuationToken = listParams.ContinuationToken; do { @@ -82,14 +92,14 @@ const _list = async ({ }: ListInputArgs): Promise => { const listParamsClone = { ...listParams }; if (!listParamsClone.MaxKeys || listParamsClone.MaxKeys > MAX_PAGE_SIZE) { + logger.debug(`defaulting pageSize to ${MAX_PAGE_SIZE}.`); listParamsClone.MaxKeys = MAX_PAGE_SIZE; - // TODO(ashwinkumar6) V6-logger: defaulting pageSize to ${MAX_PAGE_SIZE}. } const response: ListObjectsV2Output = await listObjectsV2( { - ...s3Config, - userAgentValue: getStorageUserAgentValue(StorageAction.List) + ...s3Config, + userAgentValue: getStorageUserAgentValue(StorageAction.List), }, listParamsClone ); diff --git a/packages/storage/src/providers/s3/apis/internal/remove.ts b/packages/storage/src/providers/s3/apis/internal/remove.ts index 57ee214387f..f942f1a180a 100644 --- a/packages/storage/src/providers/s3/apis/internal/remove.ts +++ b/packages/storage/src/providers/s3/apis/internal/remove.ts @@ -7,6 +7,7 @@ import { RemoveInput, RemoveOutput } from '../../types'; import { resolveS3ConfigAndInput } from '../../utils'; import { deleteObject } from '../../utils/client'; import { getStorageUserAgentValue } from '../../utils/userAgent'; +import { logger } from '../../../../utils'; export const remove = async ( amplify: AmplifyClassV6, @@ -18,15 +19,16 @@ export const remove = async ( options ); - // TODO(ashwinkumar6) V6-logger: debug `remove ${key} from ${finalKey}` + const finalKey = `${keyPrefix}${key}`; + logger.debug(`remove "${key}" from "${finalKey}".`); await deleteObject( { - ...s3Config, - userAgentValue: getStorageUserAgentValue(StorageAction.Remove) + ...s3Config, + userAgentValue: getStorageUserAgentValue(StorageAction.Remove), }, { Bucket: bucket, - Key: `${keyPrefix}${key}` + Key: finalKey, } ); return { diff --git a/packages/storage/src/providers/s3/apis/uploadData/byteLength.ts b/packages/storage/src/providers/s3/apis/uploadData/byteLength.ts index 0ecf21af949..96b97f42430 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/byteLength.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/byteLength.ts @@ -25,6 +25,6 @@ export const byteLength = (input?: any): number | undefined => { // handles browser File object return input.size; } - // TODO: support Node.js stream size + // TODO: support Node.js stream size when Node.js runtime is supported out-of-box. return undefined; }; diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts index 75e391cc4db..4289152bb91 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts @@ -18,7 +18,7 @@ export type PartToUpload = { export const getDataChunker = ( data: StorageUploadDataPayload, totalSize?: number -) => { +): Generator => { const partSize = calculatePartSize(totalSize); if (data instanceof Blob) { @@ -28,7 +28,8 @@ export const getDataChunker = ( } else if (data instanceof ArrayBuffer) { return helper(data, 0, data.byteLength, partSize); } else if (typeof data === 'string') { - return helper(data, 0, data.length, partSize); + const blob = new Blob([data]); + return getDataChunker(blob, blob.size); } else { throw new StorageError({ name: StorageValidationErrorCode.InvalidUploadSource, @@ -37,10 +38,8 @@ export const getDataChunker = ( } }; -// TODO[AllanZhengYP]: the byte length of string is incorrect here which will cause the progress tracking behave -// incorrectly. We should fix this in the future. const helper = function* ( - buffer: ArrayBuffer | Blob | string, + buffer: ArrayBuffer | Blob, byteOffset: number, byteLength: number, partSize: number diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts index 1c81e9efa1a..c7b8f64dfc6 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts @@ -11,6 +11,7 @@ import { import { ResolvedS3Config } from '../../../types/options'; import { StorageUploadDataPayload } from '../../../../../types'; import { Part, createMultipartUpload } from '../../../utils/client'; +import { logger } from '../../../../../utils'; type LoadOrCreateMultipartUploadOptions = { s3Config: ResolvedS3Config; @@ -62,8 +63,7 @@ export const loadOrCreateMultipartUpload = async ({ } | undefined; if (size === undefined) { - // Cannot determine total length of the data source, so we cannot safely cache the upload - // TODO: logger message + logger.debug('uploaded data size cannot be determined, skipping cache.'); cachedUpload = undefined; } else { const uploadCacheKey = getUploadsCacheKey({ @@ -106,8 +106,7 @@ export const loadOrCreateMultipartUpload = async ({ } ); if (size === undefined) { - // Cannot determine total length of the data source, so we cannot safely cache the upload - // TODO: logger message + logger.debug('uploaded data size cannot be determined, skipping cache.'); return { uploadId: UploadId!, cachedParts: [], diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts index c18ed21e9fd..251b5a1bf60 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts @@ -10,6 +10,7 @@ import { import { UPLOADS_STORAGE_KEY } from '../../../utils/constants'; import { ResolvedS3Config } from '../../../types/options'; import { Part, listParts } from '../../../utils/client'; +import { logger } from '../../../../../utils'; const ONE_HOUR = 1000 * 60 * 60; @@ -60,7 +61,7 @@ export const findCachedUploadParts = async ({ uploadId: cachedUpload.uploadId, }; } catch (e) { - // TODO: debug message: failed to list parts. The cached upload will be removed. + logger.debug('failed to list cached parts, removing cached upload.'); await removeCachedUpload(cacheKey); return null; } @@ -81,7 +82,7 @@ const listCachedUploadTasks = async ( try { return JSON.parse((await kvStorage.getItem(UPLOADS_STORAGE_KEY)) ?? '{}'); } catch (e) { - // TODO: debug message: cached uploads is not a valid JSON string + logger.debug('failed to parse cached uploads record.'); return {}; } }; diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts index 897f04d3368..bd560fc0406 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts @@ -26,6 +26,7 @@ import { headObject, } from '../../../utils/client'; import { getStorageUserAgentValue } from '../../../utils/userAgent'; +import { logger } from '../../../../../utils'; /** * Create closure hiding the multipart upload implementation details and expose the upload job and control functions( @@ -97,7 +98,6 @@ export const getMultipartUploadHandlers = ( }; } - // TODO[AllanZhengYP]: support excludeSubPaths option to exclude sub paths const finalKey = keyPrefix + key; uploadCacheKey = size ? getUploadsCacheKey({ @@ -195,7 +195,7 @@ export const getMultipartUploadHandlers = ( .catch(error => { const abortSignal = abortController?.signal; if (abortSignal?.aborted && isAbortSignalFromPause) { - // TODO: debug message: upload paused + logger.debug('upload paused.'); } else { // Uncaught errors should be exposed to the users. rejectCallback!(error); @@ -232,7 +232,7 @@ export const getMultipartUploadHandlers = ( }); }; cancelUpload().catch(e => { - // TODO: debug message: Error cancelling upload task. + logger.debug('error when cancelling upload task.', e); }); rejectCallback!( diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts index 48898251650..b8c2b7f43c1 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts @@ -6,6 +6,7 @@ import { TransferProgressEvent } from '../../../../../types'; import { ResolvedS3Config } from '../../../types/options'; import { calculateContentMd5 } from '../../../utils'; import { uploadPart } from '../../../utils/client'; +import { logger } from '../../../../../utils'; type UploadPartExecutorOptions = { dataChunkerGenerator: Generator; @@ -35,12 +36,12 @@ export const uploadPartExecutor = async ({ let transferredBytes = 0; for (const { data, partNumber, size } of dataChunkerGenerator) { if (abortSignal.aborted) { - // TODO: debug message: upload executor aborted + logger.debug('upload executor aborted.'); break; } if (completedPartNumberSet.has(partNumber)) { - // TODO: debug message: part already uploaded + logger.debug(`part ${partNumber} already uploaded.`); transferredBytes += size; onProgress?.({ transferredBytes, @@ -62,8 +63,7 @@ export const uploadPartExecutor = async ({ Bucket: bucket, Key: finalKey, UploadId: uploadId, - // TODO: The Body type of S3 UploadPart API from AWS SDK does not correctly reflects the supported data types. - Body: data as any, + Body: data, PartNumber: partNumber, ContentMD5: isObjectLockEnabled ? await calculateContentMd5(data) diff --git a/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts b/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts index adf463565e1..0842197acf8 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts @@ -25,7 +25,6 @@ export const putObjectJob = const { bucket, keyPrefix, s3Config, isObjectLockEnabled } = await resolveS3ConfigAndInput(Amplify, uploadDataOptions); - // TODO[AllanZhengYP]: support excludeSubPaths option to exclude sub paths const finalKey = keyPrefix + key; const { contentDisposition, @@ -40,13 +39,12 @@ export const putObjectJob = ...s3Config, abortSignal, onUploadProgress: onProgress, - userAgentValue: getStorageUserAgentValue(StorageAction.UploadData) + userAgentValue: getStorageUserAgentValue(StorageAction.UploadData), }, { Bucket: bucket, Key: finalKey, - // TODO: The Body type of S3 PutObject API from AWS SDK does not correctly reflects the supported data types. - Body: data as any, + Body: data, ContentType: contentType, ContentDisposition: contentDisposition, ContentEncoding: contentEncoding, diff --git a/packages/storage/src/providers/s3/utils/client/getObject.ts b/packages/storage/src/providers/s3/utils/client/getObject.ts index 2f6313d6a08..17278aaa67e 100644 --- a/packages/storage/src/providers/s3/utils/client/getObject.ts +++ b/packages/storage/src/providers/s3/utils/client/getObject.ts @@ -65,8 +65,6 @@ const getObjectDeserializer = async ( if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; throw buildStorageServiceError(error, response.statusCode); - } else if (!response.body) { - throw new Error('Got empty response body.'); } else { return { ...map(response.headers, { @@ -147,7 +145,7 @@ export const getPresignedGetObjectUrl = async ( const endpoint = defaultConfig.endpointResolver(config, input); const { url, headers, method } = await getObjectSerializer(input, endpoint); - // TODO: set content sha256 query parameter with value of UNSIGNED-PAYLOAD. + // TODO: set content sha256 query parameter with value of UNSIGNED-PAYLOAD instead of empty hash. // It requires changes in presignUrl. Without this change, the generated url still works, // but not the same as other tools like AWS SDK and CLI. url.searchParams.append(CONTENT_SHA256_HEADER, EMPTY_SHA256_HASH); diff --git a/packages/storage/src/providers/s3/utils/client/types.ts b/packages/storage/src/providers/s3/utils/client/types.ts index 169c5021b2e..bada269fb21 100644 --- a/packages/storage/src/providers/s3/utils/client/types.ts +++ b/packages/storage/src/providers/s3/utils/client/types.ts @@ -4,10 +4,12 @@ /** * Generated by scripts/dts-bundler/README.md * Manual change contained: - * * {@link CompatibleHttpResponse}: Add compatible interface for response payload to harmonize AWS SDK and custom clients. - * * {@link GetObjectCommandOutput.Body}: Update the type to `CompatibleHttpResponse` - * * {@link PutObjectRequest.Body}: Remove Node.js specific `Readable` type - * * {@link UploadPartRequest.Body}: Remove Node.js specific `Readable` type + * * {@link CompatibleHttpResponse}: Add compatible interface for response payload to harmonize AWS SDK and custom + * clients. + * * {@link GetObjectCommandOutput.Body}: Update the type to `CompatibleHttpResponse` and make it required as fetch + * Response always extends from Body class, the body consumption utilities always presents. + * * {@link PutObjectRequest.Body}: Remove Node.js specific `Readable` type and add `ArrayBuffer` and `ArrayBufferView` + * * {@link UploadPartRequest.Body}: Remove Node.js specific `Readable` type and add `ArrayBuffer` and `ArrayBufferView` */ import { MetadataBearer as __MetadataBearer } from '@aws-sdk/types'; import { @@ -1130,7 +1132,9 @@ export interface GetObjectCommandInput extends GetObjectRequest {} */ export interface GetObjectCommandOutput extends GetObjectOutput, - __MetadataBearer {} + __MetadataBearer { + Body: CompatibleHttpResponse['body']; +} /** * @public */ @@ -2832,7 +2836,7 @@ export type PutObjectCommandInputType = Omit & { /** * For *`PutObjectRequest["Body"]`*, see {@link PutObjectRequest.Body}. */ - Body?: PutObjectRequest['Body'] | string | Uint8Array | Buffer; + Body?: string | Blob | ArrayBuffer | ArrayBufferView; }; /** * @public @@ -2871,7 +2875,7 @@ export type UploadPartCommandInputType = Omit & { /** * For *`UploadPartRequest["Body"]`*, see {@link UploadPartRequest.Body}. */ - Body?: UploadPartRequest['Body'] | string | Uint8Array | Buffer; + Body?: string | Blob | ArrayBuffer | ArrayBufferView; }; export {}; diff --git a/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts b/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts index 6606ff794b5..cf32138b86e 100644 --- a/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts +++ b/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts @@ -31,8 +31,6 @@ type ResolvedS3ConfigAndInput = { * @throws A {@link StorageError} with `error.name` from {@link StorageValidationErrorCode} indicating invalid * configurations or Amplify library options. * - * TODO: add config errors - * * @internal */ export const resolveS3ConfigAndInput = async ( diff --git a/packages/storage/src/providers/s3/utils/transferTask.ts b/packages/storage/src/providers/s3/utils/transferTask.ts index 0863b83026b..ecbd3aa3b30 100644 --- a/packages/storage/src/providers/s3/utils/transferTask.ts +++ b/packages/storage/src/providers/s3/utils/transferTask.ts @@ -7,6 +7,7 @@ import { TransferTaskState, UploadTask, } from '../../../types/common'; +import { logger } from '../../../utils'; type CreateCancellableTaskOptions = { job: () => Promise; @@ -25,6 +26,7 @@ const createCancellableTask = ({ cancel: (message?: string) => { const { state } = cancelableTask; if (state === 'CANCELED' || state === 'ERROR' || state === 'SUCCESS') { + logger.debug(`This task cannot be canceled. State: ${state}`); return; } cancelableTask.state = 'CANCELED'; @@ -80,6 +82,7 @@ export const createUploadTask = ({ pause: () => { const { state } = uploadTask; if (!isMultipartUpload || state !== 'IN_PROGRESS') { + logger.debug(`This task cannot be paused. State: ${state}`); return; } // @ts-ignore @@ -89,6 +92,7 @@ export const createUploadTask = ({ resume: () => { const { state } = uploadTask; if (!isMultipartUpload || state !== 'PAUSED') { + logger.debug(`This task cannot be resumed. State: ${state}`); return; } // @ts-ignore diff --git a/packages/storage/src/utils/index.ts b/packages/storage/src/utils/index.ts index 5bdaf78f4b1..170a3ee5949 100644 --- a/packages/storage/src/utils/index.ts +++ b/packages/storage/src/utils/index.ts @@ -2,3 +2,4 @@ // SPDX-License-Identifier: Apache-2.0 export { resolvePrefix } from './resolvePrefix'; +export { logger } from './logger'; diff --git a/packages/storage/src/utils/logger.ts b/packages/storage/src/utils/logger.ts new file mode 100644 index 00000000000..c0818362ad4 --- /dev/null +++ b/packages/storage/src/utils/logger.ts @@ -0,0 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ConsoleLogger } from '@aws-amplify/core'; + +export const logger = new ConsoleLogger('Storage'); From 5e48cb1c4c4a31357cd06f19b7f135f8a307bb06 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Tue, 31 Oct 2023 09:09:07 -0500 Subject: [PATCH 13/45] fix: Resolving in-flight OAuth promises when sign-in flow cancelled (#12474) --- packages/auth/src/providers/cognito/apis/signInWithRedirect.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index 9920a034d86..42855e4813a 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -165,6 +165,7 @@ async function handleCodeFlow({ if (!code) { await store.clearOAuthData(); + invokeAndClearPromise(); return; } @@ -263,6 +264,7 @@ async function handleImplicitFlow({ }); if (!access_token) { await store.clearOAuthData(); + invokeAndClearPromise(); return; } From 3b7a1f399982fdf087fb35fe18c40f60557832f9 Mon Sep 17 00:00:00 2001 From: ManojNB Date: Tue, 31 Oct 2023 10:02:47 -0700 Subject: [PATCH 14/45] chore(inapp): reduce todos, update error message, update tests and add thresholds (#12419) * reduce todos and update error message for no userpoolId * chore: add tests and update thresholds * test to it * update import path and error string --- .../cognito/credentialsProvider.test.ts | 4 +- .../cognito/identityIdProvider.test.ts | 13 +- .../credentialsProvider/IdentityIdStore.ts | 5 +- .../aws-clients/cognitoIdentity/package.json | 8 + .../src/singleton/Auth/utils/errorHelpers.ts | 6 + .../core/src/singleton/Auth/utils/index.ts | 2 +- .../providers/pinpoint/utils/helpers.test.ts | 274 ++++++++++++++++++ .../pinpoint/utils/resolveConfig.test.ts | 21 ++ .../pinpoint/utils/resolveCredentials.test.ts | 23 ++ packages/notifications/package.json | 8 +- 10 files changed, 348 insertions(+), 16 deletions(-) create mode 100644 packages/core/internals/aws-clients/cognitoIdentity/package.json create mode 100644 packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts create mode 100644 packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts create mode 100644 packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveCredentials.test.ts diff --git a/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts b/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts index bcbfc7254ac..b809b5e919c 100644 --- a/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts @@ -20,8 +20,6 @@ jest.mock('@aws-amplify/core', () => ({ getCredentialsForIdentity: jest.fn(), })); -jest.mock('@aws-amplify/core/lib/awsClients/cognitoIdentity'); - jest.mock( './../../../src/providers/cognito/credentialsProvider/IdentityIdProvider', () => ({ @@ -51,7 +49,7 @@ const validAuthConfig: ResourcesConfig = { }, }; const inValidAuthConfig: ResourcesConfig = { - Auth: {}, + Auth: undefined, }; const disallowGuestAccessConfig: ResourcesConfig = { Auth: { diff --git a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts index 1f186bf7272..abf5cc0b59f 100644 --- a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts @@ -4,16 +4,13 @@ import { authAPITestParams } from './testUtils/authApiTestParams'; import { Amplify, Identity, ResourcesConfig } from '@aws-amplify/core'; import { DefaultIdentityIdStore } from '../../../src/providers/cognito/credentialsProvider/IdentityIdStore'; - -// TODO(V6): import these from top level core/ and not lib/ -import * as cogId from '@aws-amplify/core/lib/awsClients/cognitoIdentity'; +import * as cogId from '@aws-amplify/core/internals/aws-clients/cognitoIdentity'; import { cognitoIdentityIdProvider } from '../../../src/providers/cognito/credentialsProvider/IdentityIdProvider'; -jest.mock('@aws-amplify/core/lib/awsClients/cognitoIdentity'); +import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; + +jest.mock('@aws-amplify/core/internals/aws-clients/cognitoIdentity'); jest.mock('../../../src/providers/cognito/credentialsProvider/IdentityIdStore'); -type ArgumentTypes = F extends (...args: infer A) => any - ? A - : never; const ampConfig: ResourcesConfig = { Auth: { Cognito: { @@ -63,6 +60,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { ); expect( await cognitoIdentityIdProvider({ + authConfig: ampConfig.Auth!.Cognito as CognitoIdentityPoolConfig, identityIdStore: mockDefaultIdentityIdStoreInstance, }) ).toBe(authAPITestParams.GuestIdentityId.id); @@ -98,6 +96,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { ); expect( await cognitoIdentityIdProvider({ + authConfig: ampConfig.Auth!.Cognito as CognitoIdentityPoolConfig, tokens: authAPITestParams.ValidAuthTokens, identityIdStore: mockDefaultIdentityIdStoreInstance, }) diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts index e3a24c0ee4d..bda71efb5e3 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts @@ -3,6 +3,7 @@ import { AuthConfig, + ConsoleLogger, Identity, KeyValueStorageInterface, } from '@aws-amplify/core'; @@ -11,6 +12,8 @@ import { IdentityIdStorageKeys, IdentityIdStore } from './types'; import { getAuthStorageKeys } from '../tokenProvider/TokenStore'; import { AuthKeys } from '../tokenProvider/types'; +const logger = new ConsoleLogger('DefaultIdentityIdStore'); + export class DefaultIdentityIdStore implements IdentityIdStore { keyValueStorage: KeyValueStorageInterface; authConfig?: AuthConfig; @@ -53,7 +56,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { return null; } } catch (err) { - // TODO(v6): validate partial results with mobile implementation + logger.log('Error getting stored IdentityId.', err); return null; } } diff --git a/packages/core/internals/aws-clients/cognitoIdentity/package.json b/packages/core/internals/aws-clients/cognitoIdentity/package.json new file mode 100644 index 00000000000..221c2b67bb2 --- /dev/null +++ b/packages/core/internals/aws-clients/cognitoIdentity/package.json @@ -0,0 +1,8 @@ +{ + "name": "@aws-amplify/core/internals/aws-clients/cognitoIdentity", + "types": "../../../lib-esm/awsClients/cognitoIdentity/index.d.ts", + "main": "../../../lib/awsClients/cognitoIdentity/index.js", + "module": "../../../lib-esm/awsClients/cognitoIdentity/index.js", + "react-native": "../../../lib-esm/awsClients/cognitoIdentity/index.js", + "sideEffects": false +} diff --git a/packages/core/src/singleton/Auth/utils/errorHelpers.ts b/packages/core/src/singleton/Auth/utils/errorHelpers.ts index dfa45ecaacf..a8cf1c9b3b9 100644 --- a/packages/core/src/singleton/Auth/utils/errorHelpers.ts +++ b/packages/core/src/singleton/Auth/utils/errorHelpers.ts @@ -7,6 +7,7 @@ import { AmplifyErrorMap, AssertionFunction } from '../../../types'; export enum AuthConfigurationErrorCode { AuthTokenConfigException = 'AuthTokenConfigException', AuthUserPoolAndIdentityPoolException = 'AuthUserPoolAndIdentityPoolException', + AuthUserPoolException = 'AuthUserPoolException', InvalidIdentityPoolIdException = 'InvalidIdentityPoolIdException', OAuthNotConfigureException = 'OAuthNotConfigureException', } @@ -21,6 +22,11 @@ const authConfigurationErrorMap: AmplifyErrorMap = { recoverySuggestion: 'Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId.', }, + [AuthConfigurationErrorCode.AuthUserPoolException]: { + message: 'Auth UserPool not configured.', + recoverySuggestion: + 'Make sure to call Amplify.configure in your app with userPoolId and userPoolClientId.', + }, [AuthConfigurationErrorCode.InvalidIdentityPoolIdException]: { message: 'Invalid identity pool id provided.', recoverySuggestion: diff --git a/packages/core/src/singleton/Auth/utils/index.ts b/packages/core/src/singleton/Auth/utils/index.ts index f7c61d4491a..7cc665e9d9e 100644 --- a/packages/core/src/singleton/Auth/utils/index.ts +++ b/packages/core/src/singleton/Auth/utils/index.ts @@ -33,7 +33,7 @@ export function assertTokenProviderConfig( return assert( assertionValid, - AuthConfigurationErrorCode.AuthTokenConfigException + AuthConfigurationErrorCode.AuthUserPoolException ); } diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts new file mode 100644 index 00000000000..33b7bfd1b6d --- /dev/null +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts @@ -0,0 +1,274 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { InAppMessageCampaign as PinpointInAppMessage } from '@aws-amplify/core/internals/aws-clients/pinpoint'; +import cloneDeep from 'lodash/cloneDeep'; + +import { + clearMemo, + extractContent, + extractMetadata, + getStartOfDay, + isBeforeEndDate, + matchesAttributes, + matchesEventType, + matchesMetrics, +} from '../../../../../src/inAppMessaging/providers/pinpoint/utils/helpers'; + +import { + extractedContent, + extractedMetadata, + pinpointInAppMessage, +} from '../../../../testUtils/data'; +import { InAppMessagingEvent } from '../../../../../src/inAppMessaging/types'; + +jest.mock('@aws-amplify/core'); +jest.mock('@aws-amplify/core/internals/providers/pinpoint'); +jest.mock('../../../../../src/inAppMessaging/providers/pinpoint/utils'); + +const HOUR_IN_MS = 1000 * 60 * 60; + +describe('InAppMessaging Provider Utils', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('getStartOfDay returns a date string for the start of day', () => { + const dateString = getStartOfDay(); + const date = new Date(dateString); + + expect(date.getHours()).toBe(0); + expect(date.getMinutes()).toBe(0); + expect(date.getSeconds()).toBe(0); + expect(date.getMilliseconds()).toBe(0); + }); + + describe('matchesEventType', () => { + let message: PinpointInAppMessage; + beforeEach(() => { + message = cloneDeep(pinpointInAppMessage); + clearMemo(); + }); + + it('checks if an event name matches a Pinpoint message', () => { + const clickEvent: InAppMessagingEvent = { name: 'clicked' }; + const swipeEvent: InAppMessagingEvent = { name: 'swiped' }; + const dragEvent: InAppMessagingEvent = { name: 'dragged' }; + + expect(matchesEventType(message, clickEvent)).toBe(true); + expect(matchesEventType(message, swipeEvent)).toBe(true); + expect(matchesEventType(message, dragEvent)).toBe(false); + }); + + it('memoizes matches', () => { + const clickEvent: InAppMessagingEvent = { name: 'clicked' }; + message!.Schedule!.EventFilter!.Dimensions!.EventType!.Values = [ + 'clicked', + ]; + + expect(matchesEventType(message, clickEvent)).toBe(true); + + // This is a contrived way of validating the memo logic and should never happen in practice + message!.Schedule!.EventFilter!.Dimensions!.EventType!.Values = []; + + expect(matchesEventType(message, clickEvent)).toBe(true); + + clearMemo(); + + expect(matchesEventType(message, clickEvent)).toBe(false); + }); + }); + + describe('matchesAttributes', () => { + let message: PinpointInAppMessage; + beforeEach(() => { + message = cloneDeep(pinpointInAppMessage); + clearMemo(); + }); + + it('checks if event attributes matches a Pinpoint message', () => { + const matchingEvent: InAppMessagingEvent = { + name: 'action.taken', + attributes: { + favoriteFood: 'pizza', + favoriteAnimal: 'dog', + favoriteHobby: 'skydiving', + }, + }; + const nonMatchingEvent: InAppMessagingEvent = { + name: 'action.taken', + attributes: { + favoriteFood: 'pizza', + favoriteAnimal: 'monkey', + }, + }; + const missingAttributesEvent: InAppMessagingEvent = { + name: 'action.taken', + attributes: { favoriteFood: 'sushi' }, + }; + const noAttributesEvent: InAppMessagingEvent = { name: 'action.taken' }; + + // Everything matches if there are no attributes on the message + expect(matchesAttributes(message, matchingEvent)).toBe(true); + expect(matchesAttributes(message, nonMatchingEvent)).toBe(true); + expect(matchesAttributes(message, missingAttributesEvent)).toBe(true); + expect(matchesAttributes(message, noAttributesEvent)).toBe(true); + + clearMemo(); + + message!.Schedule!.EventFilter!.Dimensions!.Attributes = { + favoriteFood: { Values: ['pizza', 'sushi'] }, + favoriteAnimal: { Values: ['dog', 'giraffe'] }, + }; + + expect(matchesAttributes(message, matchingEvent)).toBe(true); + expect(matchesAttributes(message, nonMatchingEvent)).toBe(false); + expect(matchesAttributes(message, missingAttributesEvent)).toBe(false); + expect(matchesAttributes(message, noAttributesEvent)).toBe(false); + }); + + it('memoizes matches', () => { + const event: InAppMessagingEvent = { + name: 'action.taken', + attributes: { favoriteFood: 'sushi' }, + }; + message!.Schedule!.EventFilter!.Dimensions!.Attributes = { + favoriteFood: { Values: ['pizza', 'sushi'] }, + }; + + expect(matchesAttributes(message, event)).toBe(true); + + // This is a contrived way of validating the memo logic and should never happen in practice + message!.Schedule!.EventFilter!.Dimensions!.Attributes = { + favoriteFood: { Values: ['pizza'] }, + }; + + expect(matchesAttributes(message, event)).toBe(true); + + clearMemo(); + + expect(matchesAttributes(message, event)).toBe(false); + }); + }); + + describe('matchesMetrics', () => { + let message: PinpointInAppMessage; + beforeEach(() => { + message = cloneDeep(pinpointInAppMessage); + clearMemo(); + }); + + it('checks if event metrics matches a Pinpoint message', () => { + const matchingEvent: InAppMessagingEvent = { + name: 'action.taken', + metrics: { + lotSize: 2000, + yearBuilt: 2000, + bedrooms: 3, + bathrooms: 2, + listPrice: 600000, + viewed: 300, + }, + }; + const nonMatchingEvent: InAppMessagingEvent = { + name: 'action.taken', + metrics: { + lotSize: 2000, + yearBuilt: 2000, + bedrooms: 3, + bathrooms: 2, + listPrice: 700000, + }, + }; + const missingMetricsEvent: InAppMessagingEvent = { + name: 'action.taken', + metrics: { + lotSize: 2000, + yearBuilt: 2000, + }, + }; + const noMetricsEvent: InAppMessagingEvent = { name: 'action.taken' }; + + // Everything matches if there are no metrics on the message + expect(matchesMetrics(message, matchingEvent)).toBe(true); + expect(matchesMetrics(message, nonMatchingEvent)).toBe(true); + expect(matchesMetrics(message, missingMetricsEvent)).toBe(true); + expect(matchesMetrics(message, noMetricsEvent)).toBe(true); + + clearMemo(); + + message!.Schedule!.EventFilter!.Dimensions!.Metrics = { + lotSize: { ComparisonOperator: 'GREATER_THAN', Value: 1000 }, + yearBuilt: { ComparisonOperator: 'EQUAL', Value: 2000 }, + bedrooms: { ComparisonOperator: 'LESS_THAN_OR_EQUAL', Value: 3 }, + bathrooms: { ComparisonOperator: 'GREATER_THAN_OR_EQUAL', Value: 1 }, + listPrice: { ComparisonOperator: 'LESS_THAN', Value: 700000 }, + }; + + expect(matchesMetrics(message, matchingEvent)).toBe(true); + expect(matchesMetrics(message, nonMatchingEvent)).toBe(false); + expect(matchesMetrics(message, missingMetricsEvent)).toBe(false); + expect(matchesMetrics(message, noMetricsEvent)).toBe(false); + + clearMemo(); + + message!.Schedule!.EventFilter!.Dimensions!.Metrics = { + lotSize: { ComparisonOperator: 'GREATER_OR_LESS_THAN', Value: 1000 }, + }; + + expect(matchesMetrics(message, matchingEvent)).toBe(false); + }); + + it('memoizes matches', () => { + const event: InAppMessagingEvent = { + name: 'action.taken', + metrics: { lotSize: 2000 }, + }; + message!.Schedule!.EventFilter!.Dimensions!.Metrics = { + lotSize: { ComparisonOperator: 'GREATER_THAN', Value: 1000 }, + }; + + expect(matchesMetrics(message, event)).toBe(true); + + // This is a contrived way of validating the memo logic and should never happen in practice + message!.Schedule!.EventFilter!.Dimensions!.Metrics = { + lotSize: { ComparisonOperator: 'LESS_THAN', Value: 1000 }, + }; + + expect(matchesMetrics(message, event)).toBe(true); + + clearMemo(); + + expect(matchesMetrics(message, event)).toBe(false); + }); + }); + + it('isBeforeEndDate checks if a message is still not yet at its end', () => { + const message = cloneDeep(pinpointInAppMessage); + + expect(isBeforeEndDate(message)).toBe(false); + + // Set the end date to 24 hours from now + message!.Schedule!.EndDate = new Date( + new Date().getTime() + HOUR_IN_MS * 24 + ).toISOString(); + + expect(isBeforeEndDate(message)).toBe(true); + + message!.Schedule!.EndDate = undefined; + + expect(isBeforeEndDate(message)).toBe(true); + }); + + it('extractContent extracts Pinpoint content into a normalized shape', () => { + const message = cloneDeep(pinpointInAppMessage); + + expect(extractContent(message)).toStrictEqual(extractedContent); + }); + + it('extractMetadata extracts Pinpoint metadata into a flat object', () => { + const message = cloneDeep(pinpointInAppMessage); + + expect(extractMetadata(message)).toStrictEqual(extractedMetadata); + }); +}); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts new file mode 100644 index 00000000000..6eb572e2888 --- /dev/null +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts @@ -0,0 +1,21 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Amplify } from '@aws-amplify/core'; +import { resolveConfig } from '../../../../../src/inAppMessaging/providers/pinpoint/utils'; + +describe('resolveConfig', () => { + const validConfig = { + Notifications: { + InAppMessaging: { + Pinpoint: { appId: 'test-app-id', region: 'test-region' }, + }, + }, + }; + it('should return the configured appId and region', () => { + Amplify.configure(validConfig); + expect(resolveConfig()).toStrictEqual( + validConfig.Notifications!.InAppMessaging!.Pinpoint + ); + }); +}); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveCredentials.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveCredentials.test.ts new file mode 100644 index 00000000000..b556eb74bee --- /dev/null +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveCredentials.test.ts @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { fetchAuthSession } from '@aws-amplify/core'; +import { resolveCredentials } from '../../../../../src/inAppMessaging/providers/pinpoint/utils'; + +jest.mock('@aws-amplify/core'); +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + +describe('resolveCredentials', () => { + const credentials = { + credentials: { + accessKeyId: 'access-key-id', + secretAccessKey: 'secret-access-key', + }, + identityId: 'identity-id', + }; + + it('should return the credentials and identityId', async () => { + mockFetchAuthSession.mockReturnValue(credentials); + expect(await resolveCredentials()).toStrictEqual(credentials); + }); +}); diff --git a/packages/notifications/package.json b/packages/notifications/package.json index 4cec870647d..7ce32ce825e 100644 --- a/packages/notifications/package.json +++ b/packages/notifications/package.json @@ -127,10 +127,10 @@ "testURL": "http://localhost/", "coverageThreshold": { "global": { - "branches": 0, - "functions": 0, - "lines": 0, - "statements": 0 + "branches": 70, + "functions": 85, + "lines": 85, + "statements": 85 } }, "coveragePathIgnorePatterns": [ From 4476eba85af1aba0d5d9c723e8b5b82069489b79 Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Tue, 31 Oct 2023 10:20:39 -0700 Subject: [PATCH 15/45] test: increase tsc-compliance test coverage (#12444) Co-authored-by: Jim Blanchard --- package.json | 2 +- scripts/tsc-compliance-test/package.json | 4 +- scripts/tsc-compliance-test/publicPaths.ts | 73 +++++++++++++++++++ scripts/tsc-compliance-test/ts4_2.ts | 31 -------- .../tsconfig.skipLibCheck.json | 7 ++ .../{tsconfig.json => tsconfig.ts4_2.json} | 2 +- 6 files changed, 85 insertions(+), 34 deletions(-) create mode 100644 scripts/tsc-compliance-test/publicPaths.ts delete mode 100644 scripts/tsc-compliance-test/ts4_2.ts create mode 100644 scripts/tsc-compliance-test/tsconfig.skipLibCheck.json rename scripts/tsc-compliance-test/{tsconfig.json => tsconfig.ts4_2.json} (89%) diff --git a/package.json b/package.json index 9fb5f820530..c1a5853292c 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "test:duplicates": "./scripts/duplicates-yarn.sh", "test:license": "license-check-and-add check -f license_config.json", "test:github-actions": "node ./scripts/test-github-actions.js", - "test:tsc-compliance": "yarn workspace tsc-compliance-test test:compliance:ts4.2", + "test:tsc-compliance": "yarn workspace tsc-compliance-test test:compliance", "coverage": "codecov || exit 0", "docs": "typedoc packages/**/src --name amplify-js --hideGenerator --excludePrivate --ignoreCompilerErrors --mode file --out docs/api --theme docs/amplify-theme/typedoc/ --readme README.md", "build": "lerna run build --stream && yarn test:duplicates", diff --git a/scripts/tsc-compliance-test/package.json b/scripts/tsc-compliance-test/package.json index b520e84d2a5..967d66d7c96 100644 --- a/scripts/tsc-compliance-test/package.json +++ b/scripts/tsc-compliance-test/package.json @@ -9,6 +9,8 @@ "typescript": "4.2.x" }, "scripts": { - "test:compliance:ts4.2": "tsc -p tsconfig.json" + "test:compliance": "yarn test:compliance:ts4.2 && yarn test:compliance:skipLibCheck", + "test:compliance:ts4.2": "tsc -p tsconfig.ts4_2.json", + "test:compliance:skipLibCheck": "tsc -p tsconfig.skipLibCheck.json" } } diff --git a/scripts/tsc-compliance-test/publicPaths.ts b/scripts/tsc-compliance-test/publicPaths.ts new file mode 100644 index 00000000000..861bcabb110 --- /dev/null +++ b/scripts/tsc-compliance-test/publicPaths.ts @@ -0,0 +1,73 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import * as Amplify from 'aws-amplify'; + +import * as analytics from 'aws-amplify/analytics'; +import * as analyticsPinpoint from 'aws-amplify/analytics/pinpoint'; +import * as analyticsKinesis from 'aws-amplify/analytics/kinesis'; +import * as analyticsPersonalize from 'aws-amplify/analytics/personalize'; +import * as analyticsFirehose from 'aws-amplify/analytics/kinesis-firehose'; + +import * as auth from 'aws-amplify/auth'; +import * as authCognito from 'aws-amplify/auth/cognito'; +import * as authServer from 'aws-amplify/auth/server'; +import * as authCognitoServer from 'aws-amplify/auth/cognito/server'; + +import * as storage from 'aws-amplify/storage'; +import * as storageServer from 'aws-amplify/storage/server'; +import * as storageS3 from 'aws-amplify/storage/s3'; +import * as storageS3Server from 'aws-amplify/storage/s3/server'; + +import * as api from 'aws-amplify/api'; +import * as apiServer from 'aws-amplify/api/server'; + +import * as dataStore from 'aws-amplify/datastore'; + +import * as interactions from '@aws-amplify/interactions'; + +import * as predictions from '@aws-amplify/predictions'; + +import * as geo from '@aws-amplify/geo'; + +import * as pubsub from '@aws-amplify/pubsub'; + +import * as utils from 'aws-amplify/utils'; + +export const allPublicPaths = [ + // Singleton + Amplify, + // Analytics + analytics, + analyticsFirehose, + analyticsKinesis, + analyticsPersonalize, + analyticsPinpoint, + // Auth + auth, + authCognito, + authServer, + authCognitoServer, + // Storage + storage, + storageServer, + storageS3, + storageS3Server, + // API + api, + apiServer, + // DataStore + dataStore, + // Interactions + interactions, + // Predictions + predictions, + // Geo + geo, + // PubSub + pubsub, + // Utils + utils, + + // Skipping React Native packages and Next.js-only packages +]; diff --git a/scripts/tsc-compliance-test/ts4_2.ts b/scripts/tsc-compliance-test/ts4_2.ts deleted file mode 100644 index dcce2da6051..00000000000 --- a/scripts/tsc-compliance-test/ts4_2.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import * as Amplify from 'aws-amplify'; -import * as analytics from 'aws-amplify/analytics'; - -import * as auth from 'aws-amplify/auth'; -import * as authCognito from 'aws-amplify/auth/cognito'; -import * as authServer from 'aws-amplify/auth/server'; -import * as authCognitoServer from 'aws-amplify/auth/cognito/server'; - -import * as storage from 'aws-amplify/storage'; -import * as storageServer from 'aws-amplify/storage/server'; -import * as storageS3 from 'aws-amplify/storage/s3'; -import * as storageS3Server from 'aws-amplify/storage/s3/server'; - -import * as utils from 'aws-amplify/utils'; - -export const allPublicPaths = [ - Amplify, - analytics, - auth, - authCognito, - authServer, - authCognitoServer, - storage, - storageServer, - storageS3, - storageS3Server, - utils, -]; diff --git a/scripts/tsc-compliance-test/tsconfig.skipLibCheck.json b/scripts/tsc-compliance-test/tsconfig.skipLibCheck.json new file mode 100644 index 00000000000..179a9b1b948 --- /dev/null +++ b/scripts/tsc-compliance-test/tsconfig.skipLibCheck.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.ts4_2.json", + "compilerOptions": { + "skipLibCheck": false + }, + "include": ["publicPaths.ts"] +} diff --git a/scripts/tsc-compliance-test/tsconfig.json b/scripts/tsc-compliance-test/tsconfig.ts4_2.json similarity index 89% rename from scripts/tsc-compliance-test/tsconfig.json rename to scripts/tsc-compliance-test/tsconfig.ts4_2.json index ef471cfc523..28761a0862c 100644 --- a/scripts/tsc-compliance-test/tsconfig.json +++ b/scripts/tsc-compliance-test/tsconfig.ts4_2.json @@ -9,5 +9,5 @@ "moduleResolution": "node", "types": ["node"] }, - "include": ["ts4_2.ts"] + "include": ["publicPaths.ts"] } From 58d1375b358780d80a6c02f0dce17cc260f94b62 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Tue, 31 Oct 2023 13:15:35 -0500 Subject: [PATCH 16/45] chore: Tweak bundle size limits(increase) (#12480) Tweak bundle size limits. --- packages/aws-amplify/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index 4a3af55b280..88374a9579d 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -394,7 +394,7 @@ "name": "[Auth] signInWithRedirect (Cognito)", "path": "./lib-esm/auth/index.js", "import": "{ signInWithRedirect }", - "limit": "19.19 kB" + "limit": "19.24 kB" }, { "name": "[Auth] fetchUserAttributes (Cognito)", From aaa7e9841a804f88fbf6fbc95ede8117ae198508 Mon Sep 17 00:00:00 2001 From: Hui Zhao <10602282+HuiSF@users.noreply.github.com> Date: Tue, 31 Oct 2023 11:34:26 -0700 Subject: [PATCH 17/45] fix(aws-amplify): preserve default auth providers with repetitive calls of configure (#12478) --- .../__tests__/initSingleton.test.ts | 40 +++++++++++++++++++ packages/aws-amplify/src/initSingleton.ts | 6 ++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/packages/aws-amplify/__tests__/initSingleton.test.ts b/packages/aws-amplify/__tests__/initSingleton.test.ts index 0945cc6c1ae..3bdad8a9d86 100644 --- a/packages/aws-amplify/__tests__/initSingleton.test.ts +++ b/packages/aws-amplify/__tests__/initSingleton.test.ts @@ -53,6 +53,13 @@ describe('initSingleton (DefaultAmplify)', () => { mockCognitoUserPoolsTokenProviderSetKeyValueStorage.mockReset(); mockAmplifySingletonConfigure.mockReset(); mockAmplifySingletonGetConfig.mockReset(); + + mockAmplifySingletonConfigure.mockImplementation((_, libraryOptions) => { + AmplifySingleton.libraryOptions = + libraryOptions ?? AmplifySingleton.libraryOptions; + }); + // reset to its initial state + AmplifySingleton.libraryOptions = {}; }); describe('DefaultAmplify.configure()', () => { @@ -137,6 +144,39 @@ describe('initSingleton (DefaultAmplify)', () => { ); }); + it('should preserve the default auth providers when Amplify.configure is called again without custom auth provider', () => { + mockAmplifySingletonGetConfig.mockReturnValueOnce(mockResourceConfig); + + Amplify.configure(mockResourceConfig); + const defaultAuthProvidersHaveBeenConfigured = + AmplifySingleton.libraryOptions; + + Amplify.configure({ + ...Amplify.getConfig(), + Analytics: { + Kinesis: { + region: 'us-west-2', + }, + }, + }); + expect(AmplifySingleton.libraryOptions).toStrictEqual( + defaultAuthProvidersHaveBeenConfigured + ); + + Amplify.configure({ + ...Amplify.getConfig(), + Analytics: { + Personalize: { + trackingId: 'f1b2d240-f7e7-416a-af88-759d7e258994', + region: 'us-west-2', + }, + }, + }); + expect(AmplifySingleton.libraryOptions).toStrictEqual( + defaultAuthProvidersHaveBeenConfigured + ); + }); + it('should invoke AmplifySingleton.configure with other provided library options', () => { const libraryOptionsWithStorage = { Storage: { diff --git a/packages/aws-amplify/src/initSingleton.ts b/packages/aws-amplify/src/initSingleton.ts index 289eef5587e..2ec413012c9 100644 --- a/packages/aws-amplify/src/initSingleton.ts +++ b/packages/aws-amplify/src/initSingleton.ts @@ -31,7 +31,11 @@ export const DefaultAmplify = { // When Auth config is provided but no custom Auth provider defined // use the default Auth Providers - if (resolvedResourceConfig.Auth && !libraryOptions?.Auth) { + if ( + resolvedResourceConfig.Auth && + !libraryOptions?.Auth && + !Amplify.libraryOptions.Auth + ) { CognitoUserPoolsTokenProvider.setAuthConfig(resolvedResourceConfig.Auth); const libraryOptionsWithDefaultAuthProviders: LibraryOptions = { From 5ce4435059730c138e77341e2142aa7830d48b48 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 30 Oct 2023 13:08:08 -0700 Subject: [PATCH 18/45] chore(adapter-nextjs): update public APIs inline docs --- .../src/api/generateServerClient.ts | 26 ++++++++----------- .../adapter-nextjs/src/createServerRunner.ts | 22 ++++++++++++++-- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/packages/adapter-nextjs/src/api/generateServerClient.ts b/packages/adapter-nextjs/src/api/generateServerClient.ts index 8c43c86e604..41229bd30ba 100644 --- a/packages/adapter-nextjs/src/api/generateServerClient.ts +++ b/packages/adapter-nextjs/src/api/generateServerClient.ts @@ -21,12 +21,10 @@ import { getAmplifyConfig } from '../utils'; * Generates an API client that can be used inside a Next.js Server Component with Dynamic Rendering * * @example - * ```ts * import { cookies } from "next/headers" * - * const client = generateServerClientUsingCookies({ cookies }) - * const result = await client.graphql({query: listPosts}) - * ``` + * const client = generateServerClientUsingCookies({ cookies }); + * const result = await client.graphql({ query: listPosts }); */ export function generateServerClientUsingCookies< T extends Record = never @@ -68,19 +66,17 @@ export function generateServerClientUsingCookies< * Generates an API client that can be used with both Pages Router and App Router * * @example - * ```ts + * import config from './amplifyconfiguration.json'; + * import { listPosts } from './graphql/queries'; + * + * const client = generateServerClientUsingReqRes(); * - * const client = generateServerClient() - * * result = await runWithAmplifyServerContext({ - nextServerContext: { request, response }, - operation: async (contextSpec) => { - return await client.graphql(contextSpec, { - query: listPosts, - }) - }, - }) - * ``` + * nextServerContext: { request, response }, + * operation: (contextSpec) => client.graphql(contextSpec, { + * query: listPosts, + * }), + * }); */ export function generateServerClientUsingReqRes< T extends Record = never diff --git a/packages/adapter-nextjs/src/createServerRunner.ts b/packages/adapter-nextjs/src/createServerRunner.ts index f6d39566b56..7b39007e494 100644 --- a/packages/adapter-nextjs/src/createServerRunner.ts +++ b/packages/adapter-nextjs/src/createServerRunner.ts @@ -1,14 +1,32 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ResourcesConfig } from '@aws-amplify/core'; -import { parseAWSExports } from '@aws-amplify/core/internals/utils'; +import { ResourcesConfig } from 'aws-amplify'; import { AmplifyServerContextError } from '@aws-amplify/core/internals/adapter-core'; import { createRunWithAmplifyServerContext, getAmplifyConfig } from './utils'; import { NextServer } from './types'; let amplifyConfig: ResourcesConfig | undefined; +/** + * Creates the `runWithAmplifyServerContext` function to run Amplify server side APIs in an isolated request context. + * + * @remarks + * This function should be called only once; you can use the returned `runWithAmplifyServerContext` across + * your codebase. + * + * @param input The input used to create the `runWithAmplifyServerContext` function. + * @param input.config The {@link ResourcesConfig} imported from the `amplifyconfiguration.json` file or manually + * created. + * @returns An object that contains the `runWithAmplifyServerContext` function. + * + * @example + * import { createServerRunner } from '@aws-amplify/adapter-nextjs'; + * import config from './amplifyconfiguration.json'; + * + * export const { runWithAmplifyServerContext } = createServerRunner({ config }) + * + */ export const createServerRunner: NextServer.CreateServerRunner = ({ config, }) => { From 6b2d06b78eb5430f958bc59e7048cb47eb824595 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 31 Oct 2023 11:39:28 -0700 Subject: [PATCH 19/45] fix(adapter-nextjs): add api dir to the distribution list --- packages/adapter-nextjs/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 017555dc288..1c3a23973ca 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -49,7 +49,8 @@ "lib-esm", "src", "with-amplify", - "internals" + "internals", + "api" ], "homepage": "https://aws-amplify.github.io/", "jest": { From cfbde4c7962de77bd43ba20811b84c4d7d333b42 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 31 Oct 2023 12:00:20 -0700 Subject: [PATCH 20/45] chore(api): hide generateClient from api/server subpath --- .../src/api/generateServerClient.ts | 6 +-- .../api/src/internals/generateServerClient.ts | 38 +++++++++++++++ packages/api/src/internals/index.ts | 1 + packages/api/src/server.ts | 47 ------------------- 4 files changed, 42 insertions(+), 50 deletions(-) create mode 100644 packages/api/src/internals/generateServerClient.ts diff --git a/packages/adapter-nextjs/src/api/generateServerClient.ts b/packages/adapter-nextjs/src/api/generateServerClient.ts index 41229bd30ba..8dfc424e612 100644 --- a/packages/adapter-nextjs/src/api/generateServerClient.ts +++ b/packages/adapter-nextjs/src/api/generateServerClient.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { generateClient as internalGenerateClient } from '@aws-amplify/api/server'; +import { generateServerClient } from '@aws-amplify/api/internals'; import { getAmplifyServerContext, AmplifyServerContextError, @@ -56,7 +56,7 @@ export function generateServerClientUsingCookies< fn(getAmplifyServerContext(contextSpec).amplify), }); - return internalGenerateClient>({ + return generateServerClient>({ amplify: getAmplify, config: resourcesConfig, }); @@ -84,7 +84,7 @@ export function generateServerClientUsingReqRes< const amplifyConfig = getAmplifyConfig(config); // passing `null` instance because each (future model) method must retrieve a valid instance // from server context - const client = internalGenerateClient>({ + const client = generateServerClient>({ amplify: null, config: amplifyConfig, }); diff --git a/packages/api/src/internals/generateServerClient.ts b/packages/api/src/internals/generateServerClient.ts new file mode 100644 index 00000000000..ffcd785f47d --- /dev/null +++ b/packages/api/src/internals/generateServerClient.ts @@ -0,0 +1,38 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + ServerClientGenerationParams, + V6Client, + V6ClientSSR, + __amplify, +} from '@aws-amplify/api-graphql'; +import { + graphql, + cancel, + isCancelError, +} from '@aws-amplify/api-graphql/internals'; + +/** + * @private + * + * Creates a client that can be used to make GraphQL requests, using a provided `AmplifyClassV6` + * compatible context object for config and auth fetching. + * + * @param params + * @returns + */ +export function generateServerClient< + T extends Record = never, + ClientType extends V6ClientSSR | V6Client = V6ClientSSR +>(params: ServerClientGenerationParams): ClientType { + const client = { + [__amplify]: params.amplify, + graphql, + cancel, + isCancelError, + models: {}, + } as any; + + return client as ClientType; +} diff --git a/packages/api/src/internals/index.ts b/packages/api/src/internals/index.ts index 3bd49365ab4..aed523d8246 100644 --- a/packages/api/src/internals/index.ts +++ b/packages/api/src/internals/index.ts @@ -1,3 +1,4 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 export { InternalAPI, InternalAPIClass } from './InternalAPI'; +export { generateServerClient } from './generateServerClient'; diff --git a/packages/api/src/server.ts b/packages/api/src/server.ts index 2cad97872b5..681f6cfe3db 100644 --- a/packages/api/src/server.ts +++ b/packages/api/src/server.ts @@ -1,53 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export { GraphQLQuery, GraphQLSubscription } from './types'; -import { - graphql, - cancel, - isCancelError, -} from '@aws-amplify/api-graphql/internals'; -import { - AmplifyServer, - getAmplifyServerContext, -} from '@aws-amplify/core/internals/adapter-core'; - -import { - __amplify, - V6Client, - V6ClientSSR, - ServerClientGenerationParams, -} from '@aws-amplify/api-graphql'; - -export type { - GraphQLResult, - GraphQLReturnType, -} from '@aws-amplify/api-graphql'; - -/** - * @private - * - * Creates a client that can be used to make GraphQL requests, using a provided `AmplifyClassV6` - * compatible context object for config and auth fetching. - * - * @param params - * @returns - */ -export function generateClient< - T extends Record = never, - ClientType extends V6ClientSSR | V6Client = V6ClientSSR ->(params: ServerClientGenerationParams): ClientType { - const client = { - [__amplify]: params.amplify, - graphql, - cancel, - isCancelError, - models: {}, - } as any; - - return client as ClientType; -} - export { get, put, From 091f681b502cfee7ae4df178388cea052d7eb9fb Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 31 Oct 2023 14:21:45 -0700 Subject: [PATCH 21/45] fix(adapter-nextjs): remove the constraint of calling createServerRunner only once --- .../__tests__/createServerRunner.test.ts | 5 ----- packages/adapter-nextjs/src/createServerRunner.ts | 11 +---------- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts index 3df244366d5..7525b8968c0 100644 --- a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts +++ b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts @@ -73,11 +73,6 @@ describe('createServerRunner', () => { }); }); - it('throws when get called more than once', () => { - createServerRunner({ config: mockAmplifyConfig }); - expect(() => createServerRunner({ config: mockAmplifyConfig })).toThrow(); - }); - describe('runWithAmplifyServerContext', () => { describe('when amplifyConfig.Auth is not defined', () => { it('should call runWithAmplifyServerContextCore without Auth library options', () => { diff --git a/packages/adapter-nextjs/src/createServerRunner.ts b/packages/adapter-nextjs/src/createServerRunner.ts index 7b39007e494..76d238cdd15 100644 --- a/packages/adapter-nextjs/src/createServerRunner.ts +++ b/packages/adapter-nextjs/src/createServerRunner.ts @@ -2,12 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { ResourcesConfig } from 'aws-amplify'; -import { AmplifyServerContextError } from '@aws-amplify/core/internals/adapter-core'; import { createRunWithAmplifyServerContext, getAmplifyConfig } from './utils'; import { NextServer } from './types'; -let amplifyConfig: ResourcesConfig | undefined; - /** * Creates the `runWithAmplifyServerContext` function to run Amplify server side APIs in an isolated request context. * @@ -30,13 +27,7 @@ let amplifyConfig: ResourcesConfig | undefined; export const createServerRunner: NextServer.CreateServerRunner = ({ config, }) => { - if (amplifyConfig) { - throw new AmplifyServerContextError({ - message: '`createServerRunner` needs to be called only once.', - }); - } - - amplifyConfig = getAmplifyConfig(config); + const amplifyConfig = getAmplifyConfig(config); return { runWithAmplifyServerContext: createRunWithAmplifyServerContext({ From ad5c83e05e2c32c9f23ff61a8f10395148f5757e Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Tue, 31 Oct 2023 18:20:41 -0500 Subject: [PATCH 22/45] fix: Support tracking multiple inflight OAuth promise resolvers (#12482) --- packages/auth/package.json | 4 ++-- .../src/providers/cognito/apis/signInWithRedirect.ts | 11 +++++++---- packages/aws-amplify/package.json | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/packages/auth/package.json b/packages/auth/package.json index 465b9ba944d..c36d03ff74e 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -7,8 +7,8 @@ "typings": "./lib-esm/index.d.ts", "react-native": "./lib-esm/index.js", "sideEffects": [ - "./lib/providers/cognito/apis/signInWithOAuth.js", - "./lib-esm/providers/cognito/apis/signInWithOAuth.js" + "./lib/providers/cognito/apis/signInWithRedirect.js", + "./lib-esm/providers/cognito/apis/signInWithRedirect.js" ], "publishConfig": { "access": "public" diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index 42855e4813a..a5004e499bc 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -461,11 +461,14 @@ function urlListener() { isBrowser() && urlListener(); // This has a reference for listeners that requires to be notified, TokenOrchestrator use this for load tokens -let resolveInflightPromise = () => {}; +let inflightPromiseResolvers: ((value: void | PromiseLike) => void)[] = + []; const invokeAndClearPromise = () => { - resolveInflightPromise(); - resolveInflightPromise = () => {}; + for (const promiseResolver of inflightPromiseResolvers) { + promiseResolver(); + } + inflightPromiseResolvers = []; }; isBrowser() && @@ -475,7 +478,7 @@ isBrowser() && if (!(await store.loadOAuthInFlight())) { res(); } else { - resolveInflightPromise = res; + inflightPromiseResolvers.push(res); } return; }) diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index 88374a9579d..e9d1fe42a8f 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -340,7 +340,7 @@ "name": "[Auth] confirmSignIn (Cognito)", "path": "./lib-esm/auth/index.js", "import": "{ confirmSignIn }", - "limit": "25.48 kB" + "limit": "25.55 kB" }, { "name": "[Auth] updateMFAPreference (Cognito)", @@ -412,7 +412,7 @@ "name": "[Auth] OAuth Auth Flow (Cognito)", "path": "./lib-esm/auth/index.js", "import": "{ signInWithRedirect, signOut, fetchAuthSession }", - "limit": "19.53 kB" + "limit": "19.61 kB" }, { "name": "[Storage] copy (S3)", From 588b76bf6344ecedf3cc4c3c3e762665c38f7005 Mon Sep 17 00:00:00 2001 From: Hui Zhao <10602282+HuiSF@users.noreply.github.com> Date: Wed, 1 Nov 2023 09:23:57 -0700 Subject: [PATCH 23/45] chore(adapter-nextjs): bump Next.js version range (#12442) * chore(adapter-nextjs): bump Next.js supported version to < 15.0 * chore: use Next.js 13.5.6 in the workspace temporarily --- package.json | 3 ++- packages/adapter-nextjs/package.json | 4 ++-- yarn.lock | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index c1a5853292c..4e179165448 100644 --- a/package.json +++ b/package.json @@ -130,7 +130,8 @@ "@types/babel__traverse": "7.20.0", "path-scurry": "1.10.0", "**/glob/minipass": "6.0.2", - "nx": "16.7.0" + "nx": "16.7.0", + "next": "13.5.6" }, "jest": { "resetMocks": true, diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 1c3a23973ca..aba4255786b 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -4,7 +4,7 @@ "description": "The adapter for the supporting of using Amplify APIs in Next.js.", "peerDependencies": { "aws-amplify": "^6.0.0", - "next": ">=13.4.0 <14.0.0" + "next": ">=13.4.0 <15.0.0" }, "dependencies": { "cookie": "0.5.0", @@ -17,7 +17,7 @@ "@types/react-dom": "^18.2.6", "aws-amplify": "6.0.0", "jest-fetch-mock": "3.0.3", - "next": ">= 13.4.0 < 14.0.0", + "next": ">= 13.4.0 < 15.0.0", "typescript": "5.1.6" }, "publishConfig": { diff --git a/yarn.lock b/yarn.lock index 488a9aa6d4f..ef2e2cd5a21 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11787,7 +11787,7 @@ neo-async@^2.5.0, neo-async@^2.6.2: resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== -"next@>= 13.4.0 < 14.0.0": +next@13.5.6, "next@>= 13.4.0 < 15.0.0": version "13.5.6" resolved "https://registry.yarnpkg.com/next/-/next-13.5.6.tgz#e964b5853272236c37ce0dd2c68302973cf010b1" integrity sha512-Y2wTcTbO4WwEsVb4A8VSnOsG1I9ok+h74q0ZdxkwM3EODqrs4pasq7O0iUxbcS9VtWMicG7f3+HAj0r1+NtKSw== From ecba1ece65af5f2918ea2b08b876a104b07ac4b0 Mon Sep 17 00:00:00 2001 From: israx <70438514+israx@users.noreply.github.com> Date: Thu, 2 Nov 2023 10:42:23 -0400 Subject: [PATCH 24/45] chore(amplify-js/utils): expose storage helpers (#12493) * chore: expose storage helpers * fix test --- packages/aws-amplify/__tests__/exports.test.ts | 4 ++++ packages/aws-amplify/src/utils/index.ts | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index 69ee2dee24b..3fd3015112b 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -41,6 +41,10 @@ describe('aws-amplify Exports', () => { "Cache", "ConsoleLogger", "ServiceWorker", + "CookieStorage", + "defaultStorage", + "sessionStorage", + "sharedInMemoryStorage", ] `); }); diff --git a/packages/aws-amplify/src/utils/index.ts b/packages/aws-amplify/src/utils/index.ts index c32d42a964f..7ea4a20be8b 100644 --- a/packages/aws-amplify/src/utils/index.ts +++ b/packages/aws-amplify/src/utils/index.ts @@ -10,4 +10,9 @@ export { Cache, ConsoleLogger, ServiceWorker, + CookieStorage, + defaultStorage, + sessionStorage, + sharedInMemoryStorage, + KeyValueStorageInterface, } from '@aws-amplify/core'; From 1aa0c2b85611e43279541bf987fe2eda72758f1f Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Thu, 2 Nov 2023 14:32:28 -0700 Subject: [PATCH 25/45] test(core): unit validating clockskew offset is updated when client clock back and forth (#12495) --- .../utils/getUpdatedSystemClockOffset.test.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts index a7bf498885e..1861ded4eef 100644 --- a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts @@ -15,7 +15,7 @@ describe('getUpdatedSystemClockOffset', () => { Date.now = jest.fn(() => signingDate.valueOf()); }); - test('returns the current offset if not skewed', () => { + it('should return the current offset if not skewed', () => { mockIsClockSkewed.mockReturnValue(false); const offset = 1500; expect(getUpdatedSystemClockOffset(signingDate.getTime(), offset)).toBe( @@ -23,7 +23,7 @@ describe('getUpdatedSystemClockOffset', () => { ); }); - test('returns the updated offset if system clock is behind', () => { + it('should return the updated offset if system clock is behind', () => { mockIsClockSkewed.mockReturnValue(true); const clockTime = new Date(signingDate); clockTime.setMinutes(signingDate.getMinutes() + 15); @@ -32,7 +32,7 @@ describe('getUpdatedSystemClockOffset', () => { ); }); - test('returns the updated offset if system clock is ahead', () => { + it('should return the updated offset if system clock is ahead', () => { mockIsClockSkewed.mockReturnValue(true); const clockTime = new Date(signingDate); clockTime.setMinutes(signingDate.getMinutes() - 15); @@ -40,4 +40,17 @@ describe('getUpdatedSystemClockOffset', () => { -15 * 60 * 1000 ); }); + + // Addresses: https://github.com/aws-amplify/amplify-js/issues/12450#issuecomment-1787945008 + it('should return the updated offset if system clock is back and forth', () => { + // initialize client clock skew to be 15 mins behind + mockIsClockSkewed.mockReturnValue(true); + const clockTime = new Date(signingDate); + clockTime.setMinutes(signingDate.getMinutes() - 15); + let offset = getUpdatedSystemClockOffset(clockTime.getTime(), 0); + // client clock skew is now 15 mins ahead, making is sync with server clock + clockTime.setMinutes(signingDate.getMinutes() + 15); + offset = getUpdatedSystemClockOffset(clockTime.getTime(), offset); + expect(offset).toBe(0); + }); }); From 02a91a4f83f18b1a8d04f51d33d270b0c9720224 Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Date: Fri, 3 Nov 2023 08:07:32 -0700 Subject: [PATCH 26/45] fix(auth): rename type CognitoAuthUser to AuthUser (#12500) Co-authored-by: Ashwin Kumar --- packages/auth/src/index.ts | 1 + .../src/providers/cognito/apis/internal/getCurrentUser.ts | 4 ++-- packages/auth/src/providers/cognito/index.ts | 2 +- packages/auth/src/providers/cognito/types/index.ts | 2 +- packages/auth/src/providers/cognito/types/models.ts | 4 ++-- packages/auth/src/providers/cognito/types/outputs.ts | 5 ++--- packages/auth/src/providers/cognito/utils/signInHelpers.ts | 4 ++-- packages/auth/src/types/index.ts | 2 +- packages/auth/src/types/models.ts | 4 ++-- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 6dcb5d93e78..f7ff0c7cf20 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -29,6 +29,7 @@ export { forgetDevice, fetchDevices, autoSignIn, + AuthUser, } from './providers/cognito'; export { diff --git a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts index 9f530c911f6..395512d66a4 100644 --- a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts @@ -6,7 +6,7 @@ import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; import { assertAuthTokens } from '../../utils/types'; import { CognitoAuthSignInDetails, - CognitoAuthUser, + AuthUser, GetCurrentUserOutput, } from '../../types'; @@ -21,7 +21,7 @@ export const getCurrentUser = async ( assertAuthTokens(tokens); const { 'cognito:username': username, sub } = tokens.idToken?.payload ?? {}; - const authUser: CognitoAuthUser = { + const authUser: AuthUser = { username: username as string, userId: sub as string, }; diff --git a/packages/auth/src/providers/cognito/index.ts b/packages/auth/src/providers/cognito/index.ts index ea6d0a59ad8..25a2eb8e85b 100644 --- a/packages/auth/src/providers/cognito/index.ts +++ b/packages/auth/src/providers/cognito/index.ts @@ -64,7 +64,7 @@ export { SendUserAttributeVerificationCodeOutput, FetchDevicesOutput, } from './types/outputs'; -export { CognitoAuthUser } from './types/models'; +export { AuthUser } from './types/models'; export { cognitoCredentialsProvider, CognitoAWSCredentialsAndIdentityIdProvider, diff --git a/packages/auth/src/providers/cognito/types/index.ts b/packages/auth/src/providers/cognito/types/index.ts index 52cd4322724..48e9be3273e 100644 --- a/packages/auth/src/providers/cognito/types/index.ts +++ b/packages/auth/src/providers/cognito/types/index.ts @@ -9,7 +9,7 @@ export { VerifiableUserAttributeKey, MFAPreference, AWSAuthDevice, - CognitoAuthUser, + AuthUser, CognitoAuthSignInDetails, } from './models'; diff --git a/packages/auth/src/providers/cognito/types/models.ts b/packages/auth/src/providers/cognito/types/models.ts index 282508f82cd..30f27db8dcc 100644 --- a/packages/auth/src/providers/cognito/types/models.ts +++ b/packages/auth/src/providers/cognito/types/models.ts @@ -5,7 +5,7 @@ import { AuthStandardAttributeKey, AuthVerifiableAttributeKey, } from '@aws-amplify/core/internals/utils'; -import { AuthUserAttribute, AuthDevice, AuthUser } from '../../../types'; +import { AuthUserAttribute, AuthDevice, AWSAuthUser } from '../../../types'; import { AuthProvider } from '../../../types/inputs'; import { SignUpOutput } from './outputs'; @@ -92,6 +92,6 @@ export type CognitoAuthSignInDetails = { /** * Holds the user information along with the sign in details. */ -export interface CognitoAuthUser extends AuthUser { +export interface AuthUser extends AWSAuthUser { signInDetails?: CognitoAuthSignInDetails; } diff --git a/packages/auth/src/providers/cognito/types/outputs.ts b/packages/auth/src/providers/cognito/types/outputs.ts index 58ebe7826ea..aa6a40c58be 100644 --- a/packages/auth/src/providers/cognito/types/outputs.ts +++ b/packages/auth/src/providers/cognito/types/outputs.ts @@ -5,7 +5,6 @@ import { AuthVerifiableAttributeKey } from '@aws-amplify/core/internals/utils'; import { AuthMFAType, AuthUserAttributes, - AuthUser, AuthCodeDeliveryDetails, AuthTOTPSetupDetails, AuthSignInOutput, @@ -14,7 +13,7 @@ import { AuthUpdateUserAttributesOutput, AuthUpdateUserAttributeOutput, } from '../../../types'; -import { AWSAuthDevice, CognitoAuthUser, UserAttributeKey } from '../types'; +import { AWSAuthDevice, AuthUser, UserAttributeKey } from '../types'; export type FetchMFAPreferenceOutput = { enabled?: AuthMFAType[]; @@ -29,7 +28,7 @@ export type FetchUserAttributesOutput = AuthUserAttributes; /** * Output type for Cognito getCurrentUser API. */ -export type GetCurrentUserOutput = CognitoAuthUser; +export type GetCurrentUserOutput = AuthUser; /** * Output type for Cognito confirmSignIn API. diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index b89db470e97..d12ec03682c 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -26,7 +26,7 @@ import { import { AuthError } from '../../../errors/AuthError'; import { InitiateAuthException } from '../types/errors'; import { - AuthUser, + AWSAuthUser, AuthUserAttributes, AuthMFAType, AuthTOTPSetupDetails, @@ -1001,7 +1001,7 @@ export function isMFATypeEnabled( } export async function assertUserNotAuthenticated() { - let authUser: AuthUser | undefined; + let authUser: AWSAuthUser | undefined; try { authUser = await getCurrentUser(); } catch (error) {} diff --git a/packages/auth/src/types/index.ts b/packages/auth/src/types/index.ts index 57514140eb6..0b1137a437c 100644 --- a/packages/auth/src/types/index.ts +++ b/packages/auth/src/types/index.ts @@ -15,7 +15,7 @@ export { AuthNextUpdateAttributeStep, AuthMFAType, AuthAllowedMFATypes, - AuthUser, + AWSAuthUser, AuthTOTPSetupDetails, AuthResetPasswordStep, AuthUpdateAttributeStep, diff --git a/packages/auth/src/types/models.ts b/packages/auth/src/types/models.ts index 11c8e5cb82c..10259c042e3 100644 --- a/packages/auth/src/types/models.ts +++ b/packages/auth/src/types/models.ts @@ -259,9 +259,9 @@ export type AuthNextUpdateAttributeStep< }; /** - * The AuthUser object contains username and userId from the idToken. + * The AWSAuthUser object contains username and userId from the idToken. */ -export type AuthUser = { +export type AWSAuthUser = { username: string; userId: string; }; From c4f598316a5e0940053391e3ff031e18f79aaadd Mon Sep 17 00:00:00 2001 From: AllanZhengYP Date: Fri, 3 Nov 2023 09:34:06 -0700 Subject: [PATCH 27/45] test(core): fix clock skew unit test (#12509) --- .../signing/utils/getUpdatedSystemClockOffset.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts index 1861ded4eef..acb53d5c167 100644 --- a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts @@ -48,8 +48,8 @@ describe('getUpdatedSystemClockOffset', () => { const clockTime = new Date(signingDate); clockTime.setMinutes(signingDate.getMinutes() - 15); let offset = getUpdatedSystemClockOffset(clockTime.getTime(), 0); - // client clock skew is now 15 mins ahead, making is sync with server clock - clockTime.setMinutes(signingDate.getMinutes() + 15); + // client clock skew is now 15 mins ahead, making it sync with server clock + clockTime.setMinutes(clockTime.getMinutes() + 15); offset = getUpdatedSystemClockOffset(clockTime.getTime(), offset); expect(offset).toBe(0); }); From 2432d39a311e3645c2482ed21c8c16af77979c6b Mon Sep 17 00:00:00 2001 From: Ivan Artemiev <29709626+iartemiev@users.noreply.github.com> Date: Fri, 3 Nov 2023 13:45:22 -0400 Subject: [PATCH 28/45] export connection state type and enum from /api (#12508) * export connection state type and enum from /api * update exports.test snapshot --- packages/api/src/index.ts | 3 ++- packages/aws-amplify/__tests__/exports.test.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 344268d3ca5..0e13f06739f 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -6,11 +6,12 @@ export { GraphQLQuery, GraphQLSubscription } from './types'; export { generateClient } from './API'; -export { GraphQLAuthError } from '@aws-amplify/api-graphql'; +export { GraphQLAuthError, ConnectionState } from '@aws-amplify/api-graphql'; export type { GraphQLResult, GraphQLReturnType, + CONNECTION_STATE_CHANGE, } from '@aws-amplify/api-graphql'; export { diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index 3fd3015112b..f9cad7933a5 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -56,6 +56,7 @@ describe('aws-amplify Exports', () => { Array [ "generateClient", "GraphQLAuthError", + "ConnectionState", "get", "put", "post", From e1d88c2eee75ed28a33cc9e3354fc5af7ab1549a Mon Sep 17 00:00:00 2001 From: Chris F <5827964+cshfang@users.noreply.github.com> Date: Fri, 3 Nov 2023 11:18:35 -0700 Subject: [PATCH 29/45] fix(react-native): Update namespaces to be unique (#12510) --- packages/react-native/android/build.gradle | 2 +- packages/rtn-push-notification/android/build.gradle | 2 +- packages/rtn-web-browser/android/build.gradle | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/react-native/android/build.gradle b/packages/react-native/android/build.gradle index efe69cffd7f..8e4ee3a1e4e 100644 --- a/packages/react-native/android/build.gradle +++ b/packages/react-native/android/build.gradle @@ -43,7 +43,7 @@ def getExtOrIntegerDefault(name) { android { if (agpVersion >= 7) { - namespace 'com.amazonaws.amplify' + namespace 'com.amazonaws.amplify.rtncore' } compileSdkVersion getExtOrIntegerDefault("compileSdkVersion") diff --git a/packages/rtn-push-notification/android/build.gradle b/packages/rtn-push-notification/android/build.gradle index 17f49f78059..6ff8e90f566 100644 --- a/packages/rtn-push-notification/android/build.gradle +++ b/packages/rtn-push-notification/android/build.gradle @@ -32,7 +32,7 @@ def getExtOrDefault(prop) { android { if (agpVersion >= 7) { - namespace 'com.amazonaws.amplify' + namespace 'com.amazonaws.amplify.rtnpushnotification' } compileSdkVersion getExtOrDefault('compileSdkVersion') diff --git a/packages/rtn-web-browser/android/build.gradle b/packages/rtn-web-browser/android/build.gradle index cf8d6a1606a..1de0265efd5 100644 --- a/packages/rtn-web-browser/android/build.gradle +++ b/packages/rtn-web-browser/android/build.gradle @@ -31,7 +31,7 @@ def getExtOrDefault(prop) { android { if (agpVersion >= 7) { - namespace 'com.amazonaws.amplify' + namespace 'com.amazonaws.amplify.rtnwebbrowser' } compileSdkVersion getExtOrDefault('compileSdkVersion') From 3ae78c757cf2c42e5c5b5e8f75446dc3449f9d67 Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Date: Fri, 3 Nov 2023 11:47:58 -0700 Subject: [PATCH 30/45] chore(types): expose CodeDeliveryDetails, HubCapsule types (#12501) * chore(types): expose CodeDeliveryDetails, HubCapsule types * resolve conflicts --------- Co-authored-by: Ashwin Kumar Co-authored-by: erinleigh90 <106691284+erinleigh90@users.noreply.github.com> --- packages/auth/src/index.ts | 3 +++ packages/auth/src/providers/cognito/index.ts | 8 ++++++-- .../auth/src/providers/cognito/types/index.ts | 1 + .../auth/src/providers/cognito/types/models.ts | 16 +++++++++++++++- packages/aws-amplify/src/utils/index.ts | 1 + 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index f7ff0c7cf20..8193109802c 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -30,6 +30,9 @@ export { fetchDevices, autoSignIn, AuthUser, + CodeDeliveryDetails, + UserAttributeKey, + VerifiableUserAttributeKey, } from './providers/cognito'; export { diff --git a/packages/auth/src/providers/cognito/index.ts b/packages/auth/src/providers/cognito/index.ts index 25a2eb8e85b..1043a5ae7ae 100644 --- a/packages/auth/src/providers/cognito/index.ts +++ b/packages/auth/src/providers/cognito/index.ts @@ -47,7 +47,6 @@ export { DeleteUserAttributesInput, ForgetDeviceInput, } from './types/inputs'; - export { FetchUserAttributesOutput, GetCurrentUserOutput, @@ -64,7 +63,12 @@ export { SendUserAttributeVerificationCodeOutput, FetchDevicesOutput, } from './types/outputs'; -export { AuthUser } from './types/models'; +export { + AuthUser, + CodeDeliveryDetails, + UserAttributeKey, + VerifiableUserAttributeKey, +} from './types/models'; export { cognitoCredentialsProvider, CognitoAWSCredentialsAndIdentityIdProvider, diff --git a/packages/auth/src/providers/cognito/types/index.ts b/packages/auth/src/providers/cognito/types/index.ts index 48e9be3273e..0b72451e925 100644 --- a/packages/auth/src/providers/cognito/types/index.ts +++ b/packages/auth/src/providers/cognito/types/index.ts @@ -11,6 +11,7 @@ export { AWSAuthDevice, AuthUser, CognitoAuthSignInDetails, + CodeDeliveryDetails, } from './models'; export { diff --git a/packages/auth/src/providers/cognito/types/models.ts b/packages/auth/src/providers/cognito/types/models.ts index 30f27db8dcc..f763b494a0c 100644 --- a/packages/auth/src/providers/cognito/types/models.ts +++ b/packages/auth/src/providers/cognito/types/models.ts @@ -5,7 +5,14 @@ import { AuthStandardAttributeKey, AuthVerifiableAttributeKey, } from '@aws-amplify/core/internals/utils'; -import { AuthUserAttribute, AuthDevice, AWSAuthUser } from '../../../types'; + +import { + AuthUserAttribute, + AuthDevice, + AWSAuthUser, + AuthCodeDeliveryDetails, +} from '../../../types'; + import { AuthProvider } from '../../../types/inputs'; import { SignUpOutput } from './outputs'; @@ -95,3 +102,10 @@ export type CognitoAuthSignInDetails = { export interface AuthUser extends AWSAuthUser { signInDetails?: CognitoAuthSignInDetails; } + +/** + * Holds data describing the dispatch of a confirmation code. + */ +export type CodeDeliveryDetails< + CognitoUserAttributeKey extends UserAttributeKey = UserAttributeKey +> = AuthCodeDeliveryDetails; diff --git a/packages/aws-amplify/src/utils/index.ts b/packages/aws-amplify/src/utils/index.ts index 7ea4a20be8b..87ff39d973f 100644 --- a/packages/aws-amplify/src/utils/index.ts +++ b/packages/aws-amplify/src/utils/index.ts @@ -6,6 +6,7 @@ This file maps exports from `aws-amplify/utils`. */ export { Hub, + HubCapsule, I18n, Cache, ConsoleLogger, From 0960fdde3b302b19dc7390d20ae63211d81feebb Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 31 Oct 2023 11:21:57 -0700 Subject: [PATCH 31/45] fix(core): remove used symbol and remove usage of Symbol.for --- packages/core/src/Hub/index.ts | 4 ++-- packages/core/src/constants.ts | 11 ----------- packages/core/src/libraryUtils.ts | 5 +---- 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/packages/core/src/Hub/index.ts b/packages/core/src/Hub/index.ts index d226a9f1b78..6f6cb907140 100644 --- a/packages/core/src/Hub/index.ts +++ b/packages/core/src/Hub/index.ts @@ -16,8 +16,8 @@ import { } from './types'; export const AMPLIFY_SYMBOL = ( - typeof Symbol !== 'undefined' && typeof Symbol.for === 'function' - ? Symbol.for('amplify_default') + typeof Symbol !== 'undefined' + ? Symbol('amplify_default') : '@@amplify_default' ) as Symbol; diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts index 3a202d31da4..82e84497f40 100644 --- a/packages/core/src/constants.ts +++ b/packages/core/src/constants.ts @@ -4,17 +4,6 @@ // Logging constants export const AWS_CLOUDWATCH_CATEGORY = 'Logging'; -/** - * This Symbol is used to reference an internal-only PubSub provider that - * is used for AppSync/GraphQL subscriptions in the API category. - */ -const hasSymbol = - typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'; - -export const INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER = hasSymbol - ? Symbol.for('INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER') - : '@@INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER'; - export const USER_AGENT_HEADER = 'x-amz-user-agent'; // Error exception code constants diff --git a/packages/core/src/libraryUtils.ts b/packages/core/src/libraryUtils.ts index 0eed9202d67..bbaa20143fe 100644 --- a/packages/core/src/libraryUtils.ts +++ b/packages/core/src/libraryUtils.ts @@ -90,10 +90,7 @@ export { export { BackgroundProcessManager } from './BackgroundProcessManager'; export { Mutex } from './Mutex'; export { Reachability } from './Reachability'; -export { - INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER, - USER_AGENT_HEADER, -} from './constants'; +export { USER_AGENT_HEADER } from './constants'; export { fetchAuthSession } from './singleton/apis/internal/fetchAuthSession'; export { AMPLIFY_SYMBOL } from './Hub'; export { base64Decoder, base64Encoder } from './utils/convert'; From 39eacaad501579ab541b3ad3886b7819d43bfd46 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 1 Nov 2023 15:19:31 -0700 Subject: [PATCH 32/45] chore(adapter-nextjs): bump the min support version of Next.js --- packages/adapter-nextjs/package.json | 4 ++-- yarn.lock | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index aba4255786b..f1e34e24760 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -4,7 +4,7 @@ "description": "The adapter for the supporting of using Amplify APIs in Next.js.", "peerDependencies": { "aws-amplify": "^6.0.0", - "next": ">=13.4.0 <15.0.0" + "next": ">=13.5.0 <15.0.0" }, "dependencies": { "cookie": "0.5.0", @@ -17,7 +17,7 @@ "@types/react-dom": "^18.2.6", "aws-amplify": "6.0.0", "jest-fetch-mock": "3.0.3", - "next": ">= 13.4.0 < 15.0.0", + "next": ">= 13.5.0 < 15.0.0", "typescript": "5.1.6" }, "publishConfig": { diff --git a/yarn.lock b/yarn.lock index ef2e2cd5a21..d7f6844fb78 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11787,7 +11787,7 @@ neo-async@^2.5.0, neo-async@^2.6.2: resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== -next@13.5.6, "next@>= 13.4.0 < 15.0.0": +next@13.5.6, "next@>= 13.5.0 < 15.0.0": version "13.5.6" resolved "https://registry.yarnpkg.com/next/-/next-13.5.6.tgz#e964b5853272236c37ce0dd2c68302973cf010b1" integrity sha512-Y2wTcTbO4WwEsVb4A8VSnOsG1I9ok+h74q0ZdxkwM3EODqrs4pasq7O0iUxbcS9VtWMicG7f3+HAj0r1+NtKSw== From 7b514bbfe8e24939d7a94a93f45ac5518ff54258 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Fri, 3 Nov 2023 15:01:07 -0700 Subject: [PATCH 33/45] chore(adapter-nextjs): remove unused server-only dep --- packages/adapter-nextjs/package.json | 3 +-- yarn.lock | 5 ----- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index f1e34e24760..0e48733a351 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -7,8 +7,7 @@ "next": ">=13.5.0 <15.0.0" }, "dependencies": { - "cookie": "0.5.0", - "server-only": "^0.0.1" + "cookie": "0.5.0" }, "devDependencies": { "@types/cookie": "0.5.1", diff --git a/yarn.lock b/yarn.lock index d7f6844fb78..d9eafe0534a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14148,11 +14148,6 @@ serve-static@^1.13.1: parseurl "~1.3.3" send "0.18.0" -server-only@^0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/server-only/-/server-only-0.0.1.tgz#0f366bb6afb618c37c9255a314535dc412cd1c9e" - integrity sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA== - set-blocking@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" From 7dde34332397efc47a174122df0a6efc24b61296 Mon Sep 17 00:00:00 2001 From: Chris F <5827964+cshfang@users.noreply.github.com> Date: Tue, 7 Nov 2023 10:01:31 -0800 Subject: [PATCH 34/45] fix: add module loader for web browser native module (#12519) Co-authored-by: Ashwin Kumar --- .../utils/openAuthSession.native.test.ts | 15 +++++----- .../auth/src/utils/openAuthSession.native.ts | 22 ++------------ packages/react-native/src/index.ts | 1 + .../react-native/src/moduleLoaders/index.ts | 1 + .../moduleLoaders/loadAmplifyWebBrowser.ts | 29 +++++++++++++++++++ packages/rtn-web-browser/src/apis/index.ts | 4 +++ packages/rtn-web-browser/src/constants.ts | 11 +++++++ packages/rtn-web-browser/src/index.ts | 11 +++---- packages/rtn-web-browser/src/nativeModule.ts | 11 +++---- packages/rtn-web-browser/src/types/index.ts | 4 +++ .../src/{types.ts => types/native.ts} | 6 ++-- 11 files changed, 72 insertions(+), 43 deletions(-) create mode 100644 packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts create mode 100644 packages/rtn-web-browser/src/apis/index.ts create mode 100644 packages/rtn-web-browser/src/constants.ts create mode 100644 packages/rtn-web-browser/src/types/index.ts rename packages/rtn-web-browser/src/{types.ts => types/native.ts} (68%) diff --git a/packages/auth/__tests__/utils/openAuthSession.native.test.ts b/packages/auth/__tests__/utils/openAuthSession.native.test.ts index 85963f543b8..fa9e3da660e 100644 --- a/packages/auth/__tests__/utils/openAuthSession.native.test.ts +++ b/packages/auth/__tests__/utils/openAuthSession.native.test.ts @@ -2,20 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 import { openAuthSession } from '../../src/utils/openAuthSession.native'; -import { AmplifyRTNWebBrowser } from '@aws-amplify/rtn-web-browser'; -jest.mock('@aws-amplify/rtn-web-browser', () => ({ - AmplifyRTNWebBrowser: { - openAuthSessionAsync: jest.fn(), - }, +jest.mock('@aws-amplify/react-native', () => ({ + loadAmplifyWebBrowser: jest.fn(() => ({ + openAuthSessionAsync: mockOpenAuthSessionAsync, + })), })); +// module level mocks +const mockOpenAuthSessionAsync = jest.fn(); + describe('openAuthSession (native)', () => { const url = 'https://example.com'; const redirectUrl = 'scheme://oauth/'; - // create mocks - const mockOpenAuthSessionAsync = - AmplifyRTNWebBrowser.openAuthSessionAsync as jest.Mock; afterEach(() => { mockOpenAuthSessionAsync.mockReset(); diff --git a/packages/auth/src/utils/openAuthSession.native.ts b/packages/auth/src/utils/openAuthSession.native.ts index 507e309736f..a607d55edbd 100644 --- a/packages/auth/src/utils/openAuthSession.native.ts +++ b/packages/auth/src/utils/openAuthSession.native.ts @@ -1,24 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { - AmplifyWebBrowser, - OpenAuthSession, - OpenAuthSessionResult, -} from './types'; - -const RTN_MODULE = '@aws-amplify/rtn-web-browser'; - -let webBrowser: AmplifyWebBrowser; - -try { - webBrowser = require(RTN_MODULE)?.AmplifyRTNWebBrowser; - if (!webBrowser) { - throw new Error(); - } -} catch (err) { - throw new Error(`Unable to find ${RTN_MODULE}. Did you install it?`); -} +import { loadAmplifyWebBrowser } from '@aws-amplify/react-native'; +import { OpenAuthSession, OpenAuthSessionResult } from './types'; export const openAuthSession: OpenAuthSession = async ( url: string, @@ -26,7 +10,7 @@ export const openAuthSession: OpenAuthSession = async ( prefersEphemeralSession?: boolean ): Promise => { try { - const redirectUrl = await webBrowser.openAuthSessionAsync( + const redirectUrl = await loadAmplifyWebBrowser().openAuthSessionAsync( url, redirectUrls, prefersEphemeralSession diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index d8de90e9de8..8141aa8855b 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -4,6 +4,7 @@ export { computeModPow, computeS, getOperatingSystem } from './apis'; export { loadAmplifyPushNotification, + loadAmplifyWebBrowser, loadAsyncStorage, loadNetInfo, loadBuffer, diff --git a/packages/react-native/src/moduleLoaders/index.ts b/packages/react-native/src/moduleLoaders/index.ts index fdd79cf7fa1..9c9e24522af 100644 --- a/packages/react-native/src/moduleLoaders/index.ts +++ b/packages/react-native/src/moduleLoaders/index.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 export { loadAmplifyPushNotification } from './loadAmplifyPushNotification'; +export { loadAmplifyWebBrowser } from './loadAmplifyWebBrowser'; export { loadAsyncStorage } from './loadAsyncStorage'; export { loadNetInfo } from './loadNetInfo'; export { loadBuffer } from './loadBuffer'; diff --git a/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts b/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts new file mode 100644 index 00000000000..2e1b9025676 --- /dev/null +++ b/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts @@ -0,0 +1,29 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { WebBrowserModule } from '@aws-amplify/rtn-web-browser'; + +export const loadAmplifyWebBrowser = () => { + try { + // metro bundler requires static string for loading module. + // See: https://facebook.github.io/metro/docs/configuration/#dynamicdepsinpackages + const module = require('@aws-amplify/rtn-web-browser') + ?.module as WebBrowserModule; + if (module) { + return module; + } + + throw new Error( + 'Ensure `@aws-amplify/rtn-web-browser` is installed and linked.' + ); + } catch (e) { + // The error parsing logic cannot be extracted with metro as the `require` + // would be confused when there is a `import` in the same file importing + // another module and that causes an error + const message = (e as Error).message.replace( + /undefined/g, + '@aws-amplify/rtn-web-browser' + ); + throw new Error(message); + } +}; diff --git a/packages/rtn-web-browser/src/apis/index.ts b/packages/rtn-web-browser/src/apis/index.ts new file mode 100644 index 00000000000..937d37e8852 --- /dev/null +++ b/packages/rtn-web-browser/src/apis/index.ts @@ -0,0 +1,4 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { openAuthSessionAsync } from './openAuthSessionAsync'; diff --git a/packages/rtn-web-browser/src/constants.ts b/packages/rtn-web-browser/src/constants.ts new file mode 100644 index 00000000000..9cb6aa67fcc --- /dev/null +++ b/packages/rtn-web-browser/src/constants.ts @@ -0,0 +1,11 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import { Platform } from 'react-native'; + +// General +export const PACKAGE_NAME = '@aws-amplify/rtn-web-browser'; +export const LINKING_ERROR = + `The ${PACKAGE_NAME} package doesn't seem to be linked. Make sure: \n\n` + + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + + '- You rebuilt the app after installing the package\n' + + '- You are not using Expo Go\n'; diff --git a/packages/rtn-web-browser/src/index.ts b/packages/rtn-web-browser/src/index.ts index 7f094248e81..b07eddc0b37 100644 --- a/packages/rtn-web-browser/src/index.ts +++ b/packages/rtn-web-browser/src/index.ts @@ -1,12 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { openAuthSessionAsync } from './apis/openAuthSessionAsync'; -import { nativeModule } from './nativeModule'; +import { openAuthSessionAsync } from './apis'; -const mergedModule = { - ...nativeModule, - openAuthSessionAsync, -}; +const module = { openAuthSessionAsync }; -export { mergedModule as AmplifyRTNWebBrowser }; +export type WebBrowserModule = typeof module; +export { module }; diff --git a/packages/rtn-web-browser/src/nativeModule.ts b/packages/rtn-web-browser/src/nativeModule.ts index 22ff9cc77bf..be8da5d38ab 100644 --- a/packages/rtn-web-browser/src/nativeModule.ts +++ b/packages/rtn-web-browser/src/nativeModule.ts @@ -1,15 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { NativeModules, Platform } from 'react-native'; +import { NativeModules, NativeEventEmitter } from 'react-native'; +import { LINKING_ERROR } from './constants'; import { WebBrowserNativeModule } from './types'; -const LINKING_ERROR = - `The package '@aws-amplify/rtn-web-browser' doesn't seem to be linked. Make sure: \n\n` + - Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + - '- You rebuilt the app after installing the package\n' + - '- You are not using Expo Go\n'; - export const nativeModule: WebBrowserNativeModule = NativeModules.AmplifyRTNWebBrowser ? NativeModules.AmplifyRTNWebBrowser @@ -21,3 +16,5 @@ export const nativeModule: WebBrowserNativeModule = }, } ); + +export const nativeEventEmitter = new NativeEventEmitter(nativeModule); diff --git a/packages/rtn-web-browser/src/types/index.ts b/packages/rtn-web-browser/src/types/index.ts new file mode 100644 index 00000000000..ea1ea8d0eda --- /dev/null +++ b/packages/rtn-web-browser/src/types/index.ts @@ -0,0 +1,4 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +export * from './native'; diff --git a/packages/rtn-web-browser/src/types.ts b/packages/rtn-web-browser/src/types/native.ts similarity index 68% rename from packages/rtn-web-browser/src/types.ts rename to packages/rtn-web-browser/src/types/native.ts index 136c65cae9f..3ddc1a6d952 100644 --- a/packages/rtn-web-browser/src/types.ts +++ b/packages/rtn-web-browser/src/types/native.ts @@ -1,10 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export type WebBrowserNativeModule = { +import { NativeModule } from 'react-native'; + +export interface WebBrowserNativeModule extends NativeModule { openAuthSessionAsync: ( url: string, redirectUrl?: string, prefersEphemeralSession?: boolean ) => Promise; -}; +} From 875e28aeca78b65cc391d82226eba58910978866 Mon Sep 17 00:00:00 2001 From: ManojNB Date: Tue, 7 Nov 2023 14:56:07 -0800 Subject: [PATCH 35/45] fix(auth): vend the helpful types for custom providers (#12497) * fix: vend the required types for custom providers * chore: expose JWT related types and method * update snapshot * rename types to not include AWS prefix --------- Co-authored-by: Aaron S <94858815+stocaaro@users.noreply.github.com> --- packages/auth/src/index.ts | 11 ++++++++++- .../credentialsProvider/credentialsProvider.ts | 18 +++++++++--------- ...AWSCredentialsAndIdentityIdProvider.test.ts | 2 +- packages/aws-amplify/__tests__/exports.test.ts | 1 + ...reateAWSCredentialsAndIdentityIdProvider.ts | 4 ++-- .../core/__tests__/singleton/Singleton.test.ts | 6 +++--- packages/core/src/index.ts | 6 ++++-- packages/core/src/singleton/Auth/index.ts | 4 ++-- packages/core/src/singleton/Auth/types.ts | 8 ++++---- 9 files changed, 36 insertions(+), 24 deletions(-) diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 8193109802c..cd9c90280a0 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -75,4 +75,13 @@ export { export { AuthError } from './errors/AuthError'; -export { fetchAuthSession } from '@aws-amplify/core'; +export { + fetchAuthSession, + decodeJWT, + CredentialsAndIdentityIdProvider, + GetCredentialsOptions, + CredentialsAndIdentityId, + TokenProvider, + AuthTokens, + JWT, +} from '@aws-amplify/core'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index e4daf73d1c7..b394ebd883e 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -4,8 +4,8 @@ import { cognitoIdentityIdProvider } from './IdentityIdProvider'; import { AuthTokens, - AWSCredentialsAndIdentityIdProvider, - AWSCredentialsAndIdentityId, + CredentialsAndIdentityIdProvider, + CredentialsAndIdentityId, getCredentialsForIdentity, GetCredentialsOptions, ConsoleLogger, @@ -23,7 +23,7 @@ import { assertIdTokenInAuthTokens } from '../utils/types'; const logger = new ConsoleLogger('CognitoCredentialsProvider'); const CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future export class CognitoAWSCredentialsAndIdentityIdProvider - implements AWSCredentialsAndIdentityIdProvider + implements CredentialsAndIdentityIdProvider { constructor(identityIdStore: IdentityIdStore) { this._identityIdStore = identityIdStore; @@ -31,7 +31,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider private _identityIdStore: IdentityIdStore; - private _credentialsAndIdentityId?: AWSCredentialsAndIdentityId & { + private _credentialsAndIdentityId?: CredentialsAndIdentityId & { isAuthenticatedCreds: boolean; associatedIdToken?: string; }; @@ -50,7 +50,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider async getCredentialsAndIdentityId( getCredentialsOptions: GetCredentialsOptions - ): Promise { + ): Promise { const isAuthenticated = getCredentialsOptions.authenticated; const tokens = getCredentialsOptions.tokens; const authConfig = getCredentialsOptions.authConfig; @@ -89,7 +89,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider private async getGuestCredentials( identityId: string, authConfig: CognitoIdentityPoolConfig - ): Promise { + ): Promise { // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials if ( this._credentialsAndIdentityId && @@ -124,7 +124,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider clientResult.Credentials.SecretKey ) { this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL; - const res: AWSCredentialsAndIdentityId = { + const res: CredentialsAndIdentityId = { credentials: { accessKeyId: clientResult.Credentials.AccessKeyId, secretAccessKey: clientResult.Credentials.SecretKey, @@ -159,7 +159,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider authConfig: CognitoIdentityPoolConfig, authTokens: AuthTokens, identityId: string - ): Promise { + ): Promise { if ( this._credentialsAndIdentityId && !this.isPastTTL() && @@ -193,7 +193,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider clientResult.Credentials.AccessKeyId && clientResult.Credentials.SecretKey ) { - const res: AWSCredentialsAndIdentityId = { + const res: CredentialsAndIdentityId = { credentials: { accessKeyId: clientResult.Credentials.AccessKeyId, secretAccessKey: clientResult.Credentials.SecretKey, diff --git a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts index 57130645d3d..0d3e2570fd3 100644 --- a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts @@ -6,7 +6,7 @@ import { DefaultIdentityIdStore, } from '@aws-amplify/auth/cognito'; import { - AWSCredentialsAndIdentityIdProvider, + CredentialsAndIdentityIdProvider, AuthConfig, KeyValueStorageInterface, } from '@aws-amplify/core'; diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index f9cad7933a5..d5f7208356e 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -195,6 +195,7 @@ describe('aws-amplify Exports', () => { "autoSignIn", "AuthError", "fetchAuthSession", + "decodeJWT", ] `); }); diff --git a/packages/aws-amplify/src/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.ts b/packages/aws-amplify/src/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.ts index 3ccf4dad2f6..521ab0bc072 100644 --- a/packages/aws-amplify/src/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.ts +++ b/packages/aws-amplify/src/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.ts @@ -6,7 +6,7 @@ import { DefaultIdentityIdStore, } from '@aws-amplify/auth/cognito'; import { - AWSCredentialsAndIdentityIdProvider, + CredentialsAndIdentityIdProvider, AuthConfig, KeyValueStorageInterface, } from '@aws-amplify/core'; @@ -21,7 +21,7 @@ import { export const createAWSCredentialsAndIdentityIdProvider = ( authConfig: AuthConfig, keyValueStorage: KeyValueStorageInterface -): AWSCredentialsAndIdentityIdProvider => { +): CredentialsAndIdentityIdProvider => { const credentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( new DefaultIdentityIdStore(keyValueStorage) ); diff --git a/packages/core/__tests__/singleton/Singleton.test.ts b/packages/core/__tests__/singleton/Singleton.test.ts index a6a51f8c068..ad84565cc3e 100644 --- a/packages/core/__tests__/singleton/Singleton.test.ts +++ b/packages/core/__tests__/singleton/Singleton.test.ts @@ -1,7 +1,7 @@ import { Amplify } from '../../src/singleton'; import { AuthClass as Auth } from '../../src/singleton/Auth'; import { decodeJWT } from '../../src/singleton/Auth/utils'; -import { AWSCredentialsAndIdentityId } from '../../src/singleton/Auth/types'; +import { CredentialsAndIdentityId } from '../../src/singleton/Auth/types'; import { TextEncoder, TextDecoder } from 'util'; import { fetchAuthSession } from '../../src'; Object.assign(global, { TextDecoder, TextEncoder }); @@ -246,7 +246,7 @@ describe('Session tests', () => { tokens, authConfig, identityId, - }): Promise => { + }): Promise => { return { credentials: { accessKeyId: 'accessKeyIdValue', @@ -341,7 +341,7 @@ describe('Session tests', () => { tokens, authConfig, identityId, - }): Promise => { + }): Promise => { return { credentials: { accessKeyId: 'accessKeyIdValue', diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 29587871944..05c753c7e6b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,12 +13,14 @@ export { TokenProvider, AuthTokens, FetchAuthSessionOptions, - AWSCredentialsAndIdentityIdProvider, - AWSCredentialsAndIdentityId, + CredentialsAndIdentityIdProvider, + CredentialsAndIdentityId, Identity, OAuthConfig, CognitoUserPoolConfig, + JWT, } from './singleton/Auth/types'; +export { decodeJWT } from './singleton/Auth/utils'; export { AuthConfig, AuthUserPoolConfig, diff --git a/packages/core/src/singleton/Auth/index.ts b/packages/core/src/singleton/Auth/index.ts index 66321ebb7d6..d43f508674c 100644 --- a/packages/core/src/singleton/Auth/index.ts +++ b/packages/core/src/singleton/Auth/index.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { - AWSCredentialsAndIdentityId, + CredentialsAndIdentityId, AuthConfig, AuthSession, AuthTokens, @@ -48,7 +48,7 @@ export class AuthClass { options: FetchAuthSessionOptions = {} ): Promise { let tokens: AuthTokens | undefined; - let credentialsAndIdentityId: AWSCredentialsAndIdentityId | undefined; + let credentialsAndIdentityId: CredentialsAndIdentityId | undefined; let userSub: string | undefined; // Get tokens will throw if session cannot be refreshed (network or service error) or return null if not available diff --git a/packages/core/src/singleton/Auth/types.ts b/packages/core/src/singleton/Auth/types.ts index 479fd46f3b2..69d0e8fff7e 100644 --- a/packages/core/src/singleton/Auth/types.ts +++ b/packages/core/src/singleton/Auth/types.ts @@ -38,7 +38,7 @@ export type AuthSession = { export type LibraryAuthOptions = { tokenProvider?: TokenProvider; - credentialsProvider?: AWSCredentialsAndIdentityIdProvider; + credentialsProvider?: CredentialsAndIdentityIdProvider; }; export type Identity = { @@ -46,10 +46,10 @@ export type Identity = { type: 'guest' | 'primary'; }; -export interface AWSCredentialsAndIdentityIdProvider { +export interface CredentialsAndIdentityIdProvider { getCredentialsAndIdentityId: ( getCredentialsOptions: GetCredentialsOptions - ) => Promise; + ) => Promise; clearCredentialsAndIdentityId: () => void; } @@ -212,7 +212,7 @@ type GetCredentialsUnauthenticatedUser = { tokens?: never; }; -export type AWSCredentialsAndIdentityId = { +export type CredentialsAndIdentityId = { credentials: AWSCredentials; identityId?: string; }; From 903a0123e51f69ff3476b6b15aa89a73b750f9dc Mon Sep 17 00:00:00 2001 From: Hui Zhao <10602282+HuiSF@users.noreply.github.com> Date: Tue, 7 Nov 2023 15:55:26 -0800 Subject: [PATCH 36/45] feat(repo): set up rollup to emit esm and cjs artifacts (#12522) * chore: set up testing branch * feat(core): set up rollup emitting mjs * fix: failed unit tests caused by the core mjs emitting * feat: Analytics migration. * feat: Update `core` RN entry points and switch to `umd`. * feat: API + API GraphQL + API REST migration * feat(auth): set up rollup emitting mjs * chore: Add `package.json` to API category exports * feat: Migrate DataStore * feat: Migrate `datastore-storage-adapter` * feat: Migrate Geo * fix(aws-amplify): update unit test snapshots * feat(storage): set up rollup emitting mjs * fix(repo): let rollup generate sourcemap * feat: Migrate Interactions. * feat(aws-amplify): set up rollup emitting mjs * feat: Migrate Predictions * feat: Migrate PubSub * feat(adapter-nextjs): set up rollup emitting mjs * chore(repo): move tsbuildinfo file out of dist * fix(aws-amplify): update unit tests snapshot * feat(react-native): set up rollup emitting mjs * feat: Migrate Notifications * feat(rtn-pn): set up rollup emitting mjs * feat: Migrate rtn-web-browser * fix(react-native): wrong main entry point * fix(auth): resolve circular dependencies deadlock - Fix relevant unit tests * fix(repo): move tsbuildinfo file so it can be cleaned * fix: rn packages rollup emitting * fix: Use fully resolved imports from Next.js * fix(aws-amplify): update export snapshot * fix(storage): remove unnecessary package.json files * fix(repo): apply preserveModules: true * REVERT: E2E test suite branch selection * fix(core): make polyfill importing conform to rollup treeshake * fix(core): add react-native entry to exports key * fix(repo): let cjs build using CommonJS module * fix(storage): xmlParser browser module resolution * fix(aws-amplify): stablize the exports test * fix(aws-amplify): rebase size-limit * chore: use ts for react-native entries * fix: Properly bundle Paho Vendor file. * fix(storage): fix fetch xhr override for browser * fix: Bundle size tests. * fix(storage): fix runtime module resolution * fix: Lodash imports. * fix: Fix package.json errors. * fix(repo): resolve rollup warned circular dependencies * chore(repo): ignore license check on rollup config files * chore(aws-amplify): ignore dual-publish-tmp from jest * chore(repo): revert testing workflow set up * Apply suggestions from code review Co-authored-by: Jim Blanchard * chore: remove react-native entries from the /server subpaths * fix(atastore-storage-adapter): build issue * fix(repo): typo in the rollup configs * chore(api-reset): remove unnecessary side effects * chore(datastore): remove ssr subpath (no longer supported) * fix(repo): react-native entries --------- Co-authored-by: Jim Blanchard Co-authored-by: Jim Blanchard --- .gitignore | 4 + license_config.json | 5 +- package.json | 1 + .../api/generateServerClient.test.ts | 2 +- .../adapter-nextjs/__tests__/mocks/headers.ts | 4 +- ...torageAdapterFromNextServerContext.test.ts | 4 +- packages/adapter-nextjs/api/package.json | 8 +- .../adapter-nextjs/internals/package.json | 7 - packages/adapter-nextjs/package.json | 71 ++-- packages/adapter-nextjs/rollup.config.mjs | 41 ++ .../src/api/generateServerClient.ts | 8 +- .../adapter-nextjs/src/internals/index.ts | 5 - .../adapter-nextjs/src/types/NextServer.ts | 4 +- ...okieStorageAdapterFromNextServerContext.ts | 2 +- packages/adapter-nextjs/tsconfig.build.json | 7 +- packages/adapter-nextjs/tsconfig.json | 2 - .../analytics/kinesis-firehose/package.json | 9 +- packages/analytics/kinesis/package.json | 9 +- packages/analytics/package.json | 75 ++-- packages/analytics/personalize/package.json | 9 +- packages/analytics/pinpoint/package.json | 9 +- packages/analytics/rollup.config.mjs | 31 ++ .../personalize/utils/resolveConfig.ts | 5 +- packages/analytics/webpack.config.dev.js | 2 +- packages/analytics/webpack.config.js | 4 +- packages/api-graphql/internals/package.json | 8 +- packages/api-graphql/package.json | 60 ++- packages/api-graphql/rollup.config.mjs | 31 ++ packages/api-graphql/src/GraphQLAPI.ts | 2 +- packages/api-graphql/tsconfig.build.json | 5 - packages/api-graphql/webpack.config.dev.js | 2 +- packages/api-graphql/webpack.config.js | 4 +- packages/api-rest/internals/package.json | 8 +- .../api-rest/internals/server/package.json | 7 +- packages/api-rest/package.json | 78 ++-- packages/api-rest/rollup.config.mjs | 31 ++ packages/api-rest/server/package.json | 7 +- packages/api-rest/tsconfig.build.json | 5 - packages/api-rest/webpack.config.dev.js | 2 +- packages/api-rest/webpack.config.js | 4 +- packages/api/internals/package.json | 8 +- packages/api/package.json | 78 ++-- packages/api/rollup.config.mjs | 31 ++ packages/api/server/package.json | 7 +- packages/api/tsconfig.build.json | 5 - packages/api/tsconfig.json | 11 + packages/api/webpack.config.dev.js | 2 +- packages/api/webpack.config.js | 4 +- .../providers/cognito/autoSignIn.test.ts | 2 +- .../cognito/confirmResetPassword.test.ts | 2 +- .../cognito/confirmSignInErrorCases.test.ts | 2 +- .../providers/cognito/confirmSignUp.test.ts | 2 +- .../cognito/confirmUserAttribute.test.ts | 75 ++-- .../providers/cognito/deleteUser.test.ts | 94 +++-- .../cognito/deleteUserAttributes.test.ts | 76 ++-- .../cognito/fetchAuthSession.test.ts | 2 +- .../providers/cognito/fetchDevices.test.ts | 74 ++-- .../cognito/fetchMFAPreference.test.ts | 78 ++-- .../cognito/fetchUserAttributes.test.ts | 6 +- .../providers/cognito/forgetDevice.test.ts | 79 ++-- .../providers/cognito/getCurrentUser.test.ts | 2 +- .../cognito/identityIdProvider.test.ts | 43 +- .../providers/cognito/refreshToken.test.ts | 2 +- .../providers/cognito/rememberDevice.test.ts | 73 ++-- .../cognito/resendSignUpCode.test.ts | 2 +- .../providers/cognito/resetPassword.test.ts | 2 +- .../sendUserAttributeVerificationCode.test.ts | 73 ++-- .../providers/cognito/setUpTOTP.test.ts | 78 ++-- .../cognito/signInErrorCases.test.ts | 2 +- .../providers/cognito/signOut.test.ts | 2 +- .../providers/cognito/signUp.test.ts | 6 +- .../cognito/updateMFAPreference.test.ts | 89 +++-- .../providers/cognito/updatePassword.test.ts | 73 ++-- .../cognito/updateUserAttribute.test.ts | 108 ++--- .../cognito/updateUserAttributes.test.ts | 73 ++-- .../providers/cognito/verifyTOTPSetup.test.ts | 52 +-- .../utils/getAuthUserAgentValue.test.ts | 5 +- packages/auth/cognito/package.json | 9 +- packages/auth/cognito/server/package.json | 8 +- packages/auth/package.json | 69 ++-- packages/auth/rollup.config.mjs | 31 ++ packages/auth/server/package.json | 7 +- .../cognito/apis/confirmUserAttribute.ts | 10 +- .../src/providers/cognito/apis/deleteUser.ts | 5 +- .../cognito/apis/deleteUserAttributes.ts | 10 +- .../providers/cognito/apis/fetchDevices.ts | 3 +- .../cognito/apis/fetchMFAPreference.ts | 12 +- .../providers/cognito/apis/forgetDevice.ts | 3 +- .../providers/cognito/apis/rememberDevice.ts | 12 +- .../apis/sendUserAttributeVerificationCode.ts | 3 +- .../src/providers/cognito/apis/setUpTOTP.ts | 12 +- .../cognito/apis/updateMFAPreference.ts | 12 +- .../providers/cognito/apis/updatePassword.ts | 12 +- .../cognito/apis/updateUserAttribute.ts | 2 +- .../cognito/apis/updateUserAttributes.ts | 3 +- .../providers/cognito/apis/verifyTOTPSetup.ts | 3 +- .../credentialsProvider/IdentityIdProvider.ts | 2 +- .../credentialsProvider.ts | 16 +- .../cognito/credentialsProvider/utils.ts | 20 + packages/auth/webpack.config.dev.js | 2 +- packages/auth/webpack.config.js | 4 +- .../aws-amplify/__tests__/exports.test.ts | 370 +++++++++--------- .../aws-amplify/adapter-core/package.json | 7 +- .../analytics/kinesis-firehose/package.json | 9 +- .../analytics/kinesis/package.json | 9 +- packages/aws-amplify/analytics/package.json | 9 +- .../analytics/personalize/package.json | 9 +- .../analytics/pinpoint/package.json | 9 +- packages/aws-amplify/api/package.json | 9 +- packages/aws-amplify/api/server/package.json | 8 +- .../aws-amplify/auth/cognito/package.json | 9 +- .../auth/cognito/server/package.json | 8 +- packages/aws-amplify/auth/package.json | 9 +- packages/aws-amplify/auth/server/package.json | 10 +- packages/aws-amplify/datastore/package.json | 9 +- .../aws-amplify/in-app-messaging/package.json | 9 +- .../in-app-messaging/pinpoint/package.json | 9 +- packages/aws-amplify/package.json | 307 ++++++++------- .../push-notifications/package.json | 9 +- .../push-notifications/pinpoint/package.json | 9 +- packages/aws-amplify/rollup.config.mjs | 31 ++ packages/aws-amplify/storage/package.json | 9 +- packages/aws-amplify/storage/s3/package.json | 9 +- .../storage/s3/server/package.json | 8 +- .../aws-amplify/storage/server/package.json | 8 +- packages/aws-amplify/utils/package.json | 9 +- packages/aws-amplify/webpack.config.dev.js | 12 +- packages/aws-amplify/webpack.config.js | 14 +- .../pinpoint/apis/updateEndpoint.test.ts | 9 +- .../core/internals/adapter-core/package.json | 7 +- .../aws-client-utils/composers/package.json | 8 +- .../internals/aws-client-utils/package.json | 10 +- .../aws-clients/cognitoIdentity/package.json | 8 +- .../aws-clients/pinpoint/package.json | 10 +- .../internals/providers/pinpoint/package.json | 8 +- packages/core/internals/utils/package.json | 8 +- packages/core/package.json | 146 +++++-- packages/core/rollup.config.mjs | 31 ++ packages/core/server/package.json | 7 +- .../core/src/Reachability/Reachability.ts | 2 +- .../providers/pinpoint/apis/updateEndpoint.ts | 3 +- .../pinpoint/utils/cacheEndpointId.ts | 2 +- .../providers/pinpoint/utils/getEndpointId.ts | 2 +- .../pinpoint/utils/resolveEndpointId.ts | 2 +- .../{polyfill.native.ts => index.native.ts} | 5 + packages/core/src/utils/amplifyUrl/index.ts | 2 - .../core/src/utils/amplifyUrl/polyfill.ts | 4 - .../{polyfill.native.ts => index.native.ts} | 6 +- packages/core/src/utils/amplifyUuid/index.ts | 1 - .../core/src/utils/amplifyUuid/polyfill.ts | 4 - packages/core/webpack.config.dev.js | 2 +- packages/core/webpack.config.js | 4 +- .../__tests__/SQLiteAdapter.test.ts | 2 +- .../datastore-storage-adapter/package.json | 31 +- .../rollup.config.mjs | 31 ++ .../tsconfig.build.json | 5 - .../datastore-storage-adapter/tsconfig.json | 2 - .../webpack.config.dev.js | 4 +- .../webpack.config.js | 6 +- packages/datastore/build.js | 7 - packages/datastore/package.json | 43 +- packages/datastore/rollup.config.mjs | 31 ++ packages/datastore/src/ssr/index.ts | 27 -- packages/datastore/ssr/package.json | 8 - packages/datastore/tsconfig.build.json | 5 - packages/datastore/webpack.config.dev.js | 2 +- packages/datastore/webpack.config.js | 4 +- packages/geo/location-service/package.json | 9 +- packages/geo/package.json | 60 +-- packages/geo/rollup.config.mjs | 31 ++ packages/geo/webpack.config.dev.js | 2 +- packages/geo/webpack.config.js | 4 +- packages/interactions/lex-v1/package.json | 9 +- packages/interactions/lex-v2/package.json | 9 +- packages/interactions/package.json | 70 ++-- packages/interactions/rollup.config.mjs | 31 ++ packages/interactions/webpack.config.dev.js | 2 +- packages/interactions/webpack.config.js | 4 +- .../pinpoint/apis/dispatchEvent.test.ts | 1 - .../pinpoint/apis/syncMessages.test.ts | 1 - ...getPushNotificationUserAgentString.test.ts | 5 +- .../in-app-messaging/package.json | 9 +- .../in-app-messaging/pinpoint/package.json | 9 +- packages/notifications/package.json | 74 ++-- .../push-notifications/package.json | 9 +- .../push-notifications/pinpoint/package.json | 9 +- packages/notifications/rollup.config.mjs | 31 ++ .../providers/pinpoint/apis/dispatchEvent.ts | 2 +- .../providers/pinpoint/utils/helpers.ts | 2 +- .../pushNotifications/errors/errorHelpers.ts | 2 +- .../utils/resolveCredentials.ts | 5 +- packages/notifications/webpack.config.dev.js | 2 +- packages/notifications/webpack.config.js | 4 +- packages/predictions/package.json | 44 +-- packages/predictions/rollup.config.mjs | 31 ++ packages/predictions/webpack.config.dev.js | 2 +- packages/predictions/webpack.config.js | 4 +- packages/pubsub/build.js | 7 - packages/pubsub/internals/package.json | 8 +- packages/pubsub/iot/packages.json | 9 +- packages/pubsub/mqtt/packages.json | 9 +- packages/pubsub/package.json | 63 +-- packages/pubsub/rollup.config.mjs | 38 ++ packages/pubsub/src/Providers/MqttOverWS.ts | 2 +- packages/pubsub/webpack.config.dev.js | 2 +- packages/pubsub/webpack.config.js | 4 +- packages/react-native/package.json | 25 +- packages/react-native/rollup.config.mjs | 41 ++ packages/react-native/tsconfig.build.json | 2 +- packages/react-native/tsconfig.json | 10 +- packages/rtn-push-notification/build.js | 7 - packages/rtn-push-notification/index.js | 9 - packages/rtn-push-notification/package.json | 31 +- .../rtn-push-notification/rollup.config.mjs | 31 ++ .../src/utils/normalizeNativeMessage.ts | 2 +- packages/rtn-push-notification/tsconfig.json | 2 - .../webpack.config.dev.js | 6 - .../rtn-push-notification/webpack.config.js | 39 -- packages/rtn-web-browser/package.json | 27 +- packages/rtn-web-browser/rollup.config.mjs | 31 ++ packages/rtn-web-browser/tsconfig.build.json | 5 - packages/rtn-web-browser/tsconfig.json | 21 +- .../utils/client/S3/functional-apis.test.ts | 4 +- packages/storage/package.json | 92 ++--- packages/storage/rollup.config.mjs | 31 ++ packages/storage/s3/package.json | 9 +- packages/storage/s3/server/package.json | 8 +- packages/storage/server/package.json | 9 +- .../s3/utils/client/runtime/index.ts | 4 - .../s3/utils/client/runtime/package.json | 14 - packages/storage/webpack.config.dev.js | 2 +- packages/storage/webpack.config.js | 4 +- rollup/common.mjs | 41 ++ rollup/utils.mjs | 30 ++ yarn.lock | 38 +- 235 files changed, 2783 insertions(+), 2012 deletions(-) delete mode 100644 packages/adapter-nextjs/internals/package.json create mode 100644 packages/adapter-nextjs/rollup.config.mjs delete mode 100644 packages/adapter-nextjs/src/internals/index.ts create mode 100644 packages/analytics/rollup.config.mjs create mode 100644 packages/api-graphql/rollup.config.mjs delete mode 100644 packages/api-graphql/tsconfig.build.json create mode 100644 packages/api-rest/rollup.config.mjs delete mode 100644 packages/api-rest/tsconfig.build.json create mode 100644 packages/api/rollup.config.mjs delete mode 100644 packages/api/tsconfig.build.json create mode 100644 packages/api/tsconfig.json create mode 100644 packages/auth/rollup.config.mjs create mode 100644 packages/auth/src/providers/cognito/credentialsProvider/utils.ts create mode 100644 packages/aws-amplify/rollup.config.mjs create mode 100644 packages/core/rollup.config.mjs rename packages/core/src/utils/amplifyUrl/{polyfill.native.ts => index.native.ts} (61%) delete mode 100644 packages/core/src/utils/amplifyUrl/polyfill.ts rename packages/core/src/utils/amplifyUuid/{polyfill.native.ts => index.native.ts} (68%) delete mode 100644 packages/core/src/utils/amplifyUuid/polyfill.ts create mode 100644 packages/datastore-storage-adapter/rollup.config.mjs delete mode 100644 packages/datastore-storage-adapter/tsconfig.build.json delete mode 100644 packages/datastore/build.js create mode 100644 packages/datastore/rollup.config.mjs delete mode 100644 packages/datastore/src/ssr/index.ts delete mode 100644 packages/datastore/ssr/package.json delete mode 100644 packages/datastore/tsconfig.build.json create mode 100644 packages/geo/rollup.config.mjs create mode 100644 packages/interactions/rollup.config.mjs create mode 100644 packages/notifications/rollup.config.mjs create mode 100644 packages/predictions/rollup.config.mjs delete mode 100644 packages/pubsub/build.js create mode 100644 packages/pubsub/rollup.config.mjs create mode 100644 packages/react-native/rollup.config.mjs delete mode 100644 packages/rtn-push-notification/build.js delete mode 100644 packages/rtn-push-notification/index.js create mode 100644 packages/rtn-push-notification/rollup.config.mjs delete mode 100644 packages/rtn-push-notification/webpack.config.dev.js delete mode 100644 packages/rtn-push-notification/webpack.config.js create mode 100644 packages/rtn-web-browser/rollup.config.mjs delete mode 100644 packages/rtn-web-browser/tsconfig.build.json create mode 100644 packages/storage/rollup.config.mjs delete mode 100644 packages/storage/src/providers/s3/utils/client/runtime/package.json create mode 100644 rollup/common.mjs create mode 100644 rollup/utils.mjs diff --git a/.gitignore b/.gitignore index 479ad37bc42..621192e8ae0 100644 --- a/.gitignore +++ b/.gitignore @@ -63,3 +63,7 @@ coverage-ts/ **/example/ios/Podfile.lock **/example/.bundle **/example/yarn.lock + +# rollup +**/.rollup.cache +**/buildMeta diff --git a/license_config.json b/license_config.json index 3987cdb956c..f0bac69b3a4 100644 --- a/license_config.json +++ b/license_config.json @@ -35,7 +35,10 @@ "**/vendor", "**/__tests__", "**/__mocks__", - "**/Gemfile" + "**/Gemfile", + "**/.rollup.cache", + "**/rollup.config.mjs", + "rollup" ], "ignoreFile": ".gitignore", "license": "license_header.txt", diff --git a/package.json b/package.json index 4e179165448..33583c5c8db 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "babel-jest": "^24.9.0", "babel-loader": "^8.3.0", "codecov": "^3.6.5", + "glob": "^10.3.10", "husky": "^3.0.5", "jest": "^24.x.x", "jest-config": "24.8.0", diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index 8920cc3022a..09400588077 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -10,7 +10,7 @@ import { import { NextApiRequestMock, NextApiResponseMock } from '../mocks/headers'; import { createServerRunnerForAPI } from '../../src/api/createServerRunnerForAPI'; -const headers = import('next/headers'); +const headers = import('next/headers.js'); (global as any).Headers = jest.requireActual('node-fetch').Headers; const mockAmplifyConfig: ResourcesConfig = { diff --git a/packages/adapter-nextjs/__tests__/mocks/headers.ts b/packages/adapter-nextjs/__tests__/mocks/headers.ts index ab4aeaf10da..9023b16b0af 100644 --- a/packages/adapter-nextjs/__tests__/mocks/headers.ts +++ b/packages/adapter-nextjs/__tests__/mocks/headers.ts @@ -1,8 +1,8 @@ -import { NextApiRequest, NextApiResponse } from 'next'; +import { NextApiRequest, NextApiResponse } from 'next/index.js'; import { NextApiRequestCookies, NextApiRequestQuery, -} from 'next/dist/server/api-utils'; +} from 'next/dist/server/api-utils/index.js'; import { Socket } from 'net'; import { IncomingMessage } from 'http'; diff --git a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts index 0dda7a31726..b1ae7366d1c 100644 --- a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts @@ -6,8 +6,8 @@ import { enableFetchMocks } from 'jest-fetch-mock'; // Make global Request available during test enableFetchMocks(); -import { NextRequest, NextResponse } from 'next/server'; -import { cookies } from 'next/headers'; +import { NextRequest, NextResponse } from 'next/server.js'; +import { cookies } from 'next/headers.js'; import { createCookieStorageAdapterFromNextServerContext } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; import { DATE_IN_THE_PAST } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; import { IncomingMessage, ServerResponse } from 'http'; diff --git a/packages/adapter-nextjs/api/package.json b/packages/adapter-nextjs/api/package.json index 513f32bb0d8..61728c8d89a 100644 --- a/packages/adapter-nextjs/api/package.json +++ b/packages/adapter-nextjs/api/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/adapter-nextjs/api", - "main": "../lib/api/index.js", - "browser": "../lib-esm/api/index.js", - "module": "../lib-esm/api/index.js", - "typings": "../lib-esm/api/index.d.ts" + "main": "../dist/cjs/api/index.js", + "browser": "../dist/esm/api/index.mjs", + "module": "../dist/esm/api/index.mjs", + "typings": "../dist/esm/api/index.d.ts" } diff --git a/packages/adapter-nextjs/internals/package.json b/packages/adapter-nextjs/internals/package.json deleted file mode 100644 index 989341b8e6a..00000000000 --- a/packages/adapter-nextjs/internals/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "@aws-amplify/adapter-nextjs/internals", - "main": "../lib/internals/index.js", - "browser": "../lib-esm/internals/index.js", - "module": "../lib-esm/internals/index.js", - "typings": "../lib-esm/internals/index.d.ts" -} diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 0e48733a351..49db1978bd4 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -1,6 +1,7 @@ { "author": "Amazon Web Services", "name": "@aws-amplify/adapter-nextjs", + "version": "1.0.0", "description": "The adapter for the supporting of using Amplify APIs in Next.js.", "peerDependencies": { "aws-amplify": "^6.0.0", @@ -10,6 +11,7 @@ "cookie": "0.5.0" }, "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", "@types/cookie": "0.5.1", "@types/node": "^20.3.1", "@types/react": "^18.2.13", @@ -17,6 +19,7 @@ "aws-amplify": "6.0.0", "jest-fetch-mock": "3.0.3", "next": ">= 13.5.0 < 15.0.0", + "rollup": "3.29.4", "typescript": "5.1.6" }, "publishConfig": { @@ -27,31 +30,42 @@ }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js" }, "./api": { - "types": "./lib-esm/api/index.d.ts", - "import": "./lib-esm/api/index.js", - "require": "./lib/api/index.js" - }, - "./internals": { - "types": "./lib-esm/internals/index.d.ts", - "import": "./lib-esm/internals/index.js", - "require": "./lib/internals/index.js" + "types": "./dist/esm/api/index.d.ts", + "import": "./dist/esm/api/index.mjs", + "require": "./dist/cjs/api/index.js" }, "./package.json": "./package.json" }, "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", - "with-amplify", - "internals", "api" ], "homepage": "https://aws-amplify.github.io/", + "license": "Apache-2.0", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "sideEffects": false, + "scripts": { + "build": "npm run clean && npm run build:esm-cjs", + "build-with-test": "npm test && npm run build", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "clean": "npm run clean:size && rimraf dist", + "clean:size": "rimraf dual-publish-tmp tmp*", + "format": "echo \"Not implemented\"", + "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", + "test": "npm run lint && jest -w 1 --coverage", + "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 90.31" + }, "jest": { "coveragePathIgnorePatterns": [ "/node_modules/", @@ -73,7 +87,10 @@ "diagnostics": { "pathRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$" }, - "tsConfig": false + "tsConfig": { + "allowJs": true, + "types": ["@types/jest"] + } } }, "moduleFileExtensions": [ @@ -95,25 +112,5 @@ "transform": { "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" } - }, - "license": "Apache-2.0", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "sideEffects": false, - "scripts": { - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "clean": "npm run clean:size && rimraf lib-esm lib", - "clean:size": "rimraf dual-publish-tmp tmp*", - "format": "echo \"Not implemented\"", - "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", - "test": "npm run lint && jest -w 1 --coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 90.31" - }, - "typings": "./lib-esm/index.d.ts", - "version": "1.0.0" + } } diff --git a/packages/adapter-nextjs/rollup.config.mjs b/packages/adapter-nextjs/rollup.config.mjs new file mode 100644 index 00000000000..a299129900e --- /dev/null +++ b/packages/adapter-nextjs/rollup.config.mjs @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [ + typescript({ + ...cjsTSOptions, + tsconfig: 'tsconfig.build.json', + }), + ], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [ + typescript({ + ...esmTSOptions, + tsconfig: 'tsconfig.build.json', + }), + ], + }, +]); + +export default config; diff --git a/packages/adapter-nextjs/src/api/generateServerClient.ts b/packages/adapter-nextjs/src/api/generateServerClient.ts index 8dfc424e612..21bfc10b882 100644 --- a/packages/adapter-nextjs/src/api/generateServerClient.ts +++ b/packages/adapter-nextjs/src/api/generateServerClient.ts @@ -5,6 +5,7 @@ import { generateServerClient } from '@aws-amplify/api/internals'; import { getAmplifyServerContext, AmplifyServerContextError, + AmplifyServer, } from '@aws-amplify/core/internals/adapter-core'; import { V6Client, @@ -12,6 +13,7 @@ import { GraphQLMethod, GraphQLMethodSSR, __amplify, + GraphQLOptionsV6, } from '@aws-amplify/api-graphql'; import { NextServer } from '../types'; import { createServerRunnerForAPI } from './createServerRunnerForAPI'; @@ -92,7 +94,11 @@ export function generateServerClientUsingReqRes< // TODO: improve this and the next type const prevGraphql = client.graphql as unknown as GraphQLMethod; - const wrappedGraphql = (contextSpec, options, additionalHeaders?) => { + const wrappedGraphql = ( + contextSpec: AmplifyServer.ContextSpec, + options: GraphQLOptionsV6, + additionalHeaders?: { [key: string]: string } + ) => { const amplifyInstance = getAmplifyServerContext(contextSpec).amplify; return prevGraphql.call( { [__amplify]: amplifyInstance }, diff --git a/packages/adapter-nextjs/src/internals/index.ts b/packages/adapter-nextjs/src/internals/index.ts deleted file mode 100644 index 6e5b0dc636e..00000000000 --- a/packages/adapter-nextjs/src/internals/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -export { getAmplifyConfig } from '../utils'; -export { NextServer } from '../types'; diff --git a/packages/adapter-nextjs/src/types/NextServer.ts b/packages/adapter-nextjs/src/types/NextServer.ts index 78496433092..a727204bc00 100644 --- a/packages/adapter-nextjs/src/types/NextServer.ts +++ b/packages/adapter-nextjs/src/types/NextServer.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { GetServerSidePropsContext as NextGetServerSidePropsContext } from 'next'; -import { NextRequest, NextResponse } from 'next/server'; -import { cookies } from 'next/headers'; +import { NextRequest, NextResponse } from 'next/server.js'; +import { cookies } from 'next/headers.js'; import { LegacyConfig } from 'aws-amplify/adapter-core'; import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core'; import { ResourcesConfig } from '@aws-amplify/core'; diff --git a/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts b/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts index d30b7ba7859..beffc7ae31e 100644 --- a/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts +++ b/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from 'next/server.js'; import { NextServer } from '../types'; import { AmplifyServerContextError, diff --git a/packages/adapter-nextjs/tsconfig.build.json b/packages/adapter-nextjs/tsconfig.build.json index af6adca185d..aed335f0bbc 100644 --- a/packages/adapter-nextjs/tsconfig.build.json +++ b/packages/adapter-nextjs/tsconfig.build.json @@ -1,5 +1,8 @@ { "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] + "compilerOptions": { + "strict": true, + "noImplicitAny": true + }, + "include": ["./src"] } diff --git a/packages/adapter-nextjs/tsconfig.json b/packages/adapter-nextjs/tsconfig.json index 21f44e9f115..cf90b690b44 100755 --- a/packages/adapter-nextjs/tsconfig.json +++ b/packages/adapter-nextjs/tsconfig.json @@ -2,11 +2,9 @@ { "compilerOptions": { "allowSyntheticDefaultImports": true, - "outDir": "./lib/", "target": "es2020", "noImplicitAny": false, "lib": ["dom", "es2019", "esnext.asynciterable"], - "sourceMap": true, "module": "commonjs", "moduleResolution": "node", "allowJs": true, diff --git a/packages/analytics/kinesis-firehose/package.json b/packages/analytics/kinesis-firehose/package.json index 5a24371bb4b..64a3b9ef078 100644 --- a/packages/analytics/kinesis-firehose/package.json +++ b/packages/analytics/kinesis-firehose/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/analytics/kinesis-firehose", - "main": "../lib/providers/kinesis-firehose/index.js", - "browser": "../lib-esm/providers/kinesis-firehose/index.js", - "module": "../lib-esm/providers/kinesis-firehose/index.js", - "typings": "../lib-esm/providers/kinesis-firehose/index.d.ts" + "main": "../dist/cjs/providers/kinesis-firehose/index.js", + "browser": "../dist/esm/providers/kinesis-firehose/index.mjs", + "module": "../dist/esm/providers/kinesis-firehose/index.mjs", + "react-native": "../src/providers/kinesis-firehose/index.ts", + "typings": "../dist/esm/providers/kinesis-firehose/index.d.ts" } diff --git a/packages/analytics/kinesis/package.json b/packages/analytics/kinesis/package.json index 682df5115a2..69fb31b3d90 100644 --- a/packages/analytics/kinesis/package.json +++ b/packages/analytics/kinesis/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/analytics/kinesis", - "main": "../lib/providers/kinesis/index.js", - "browser": "../lib-esm/providers/kinesis/index.js", - "module": "../lib-esm/providers/kinesis/index.js", - "typings": "../lib-esm/providers/kinesis/index.d.ts" + "main": "../dist/cjs/providers/kinesis/index.js", + "browser": "../dist/esm/providers/kinesis/index.mjs", + "module": "../dist/esm/providers/kinesis/index.mjs", + "react-native": "../src/providers/kinesis/index.ts", + "typings": "../dist/esm/providers/kinesis/index.d.ts" } diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 9a1c66830f0..0a6cb1f1221 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -2,9 +2,10 @@ "name": "@aws-amplify/analytics", "version": "7.0.0", "description": "Analytics category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -12,60 +13,64 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm run clean && npm run test && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 71.4" }, - "react-native": "./lib-esm/index.js", "typesVersions": { ">=4.2": { "pinpoint": [ - "./lib-esm/providers/pinpoint/index.d.ts" + "./dist/esm/providers/pinpoint/index.d.ts" ], "kinesis": [ - "./lib-esm/providers/kinesis/index.d.ts" + "./dist/esm/providers/kinesis/index.d.ts" ], "kinesis-firehose": [ - "./lib-esm/providers/kinesis-firehose/index.d.ts" + "./dist/esm/providers/kinesis-firehose/index.d.ts" ], "personalize": [ - "./lib-esm/providers/personalize/index.d.ts" + "./dist/esm/providers/personalize/index.d.ts" ] } }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./pinpoint": { - "types": "./lib-esm/providers/pinpoint/index.d.ts", - "import": "./lib-esm/providers/pinpoint/index.js", - "require": "./lib/providers/pinpoint/index.js" + "types": "./dist/esm/providers/pinpoint/index.d.ts", + "import": "./dist/esm/providers/pinpoint/index.mjs", + "require": "./dist/cjs/providers/pinpoint/index.js", + "react-native": "./src/providers/pinpoint/index.ts" }, "./kinesis": { - "types": "./lib-esm/providers/kinesis/index.d.ts", - "import": "./lib-esm/providers/kinesis/index.js", - "require": "./lib/providers/kinesis/index.js" + "types": "./dist/esm/providers/kinesis/index.d.ts", + "import": "./dist/esm/providers/kinesis/index.mjs", + "require": "./dist/cjs/providers/kinesis/index.js", + "react-native": "./src/providers/kinesis/index.ts" }, "./kinesis-firehose": { - "types": "./lib-esm/providers/kinesis-firehose/index.d.ts", - "import": "./lib-esm/providers/kinesis-firehose/index.js", - "require": "./lib/providers/kinesis-firehose/index.js" + "types": "./dist/esm/providers/kinesis-firehose/index.d.ts", + "import": "./dist/esm/providers/kinesis-firehose/index.mjs", + "require": "./dist/cjs/providers/kinesis-firehose/index.js", + "react-native": "./src/providers/kinesis-firehose/index.ts" }, "./personalize": { - "types": "./lib-esm/providers/personalize/index.d.ts", - "import": "./lib-esm/providers/personalize/index.js", - "require": "./lib/providers/personalize/index.js" + "types": "./dist/esm/providers/personalize/index.d.ts", + "import": "./dist/esm/providers/personalize/index.mjs", + "require": "./dist/cjs/providers/personalize/index.js", + "react-native": "./src/providers/personalize/index.ts" }, "./package.json": "./package.json" }, @@ -80,8 +85,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "pinpoint", "kinesis", @@ -102,6 +107,8 @@ "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", "@aws-sdk/types": "3.398.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "jest": { @@ -140,9 +147,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ], "setupFiles": [ "/src/setupTests.ts" diff --git a/packages/analytics/personalize/package.json b/packages/analytics/personalize/package.json index 397b7934fb2..06822f3cb02 100644 --- a/packages/analytics/personalize/package.json +++ b/packages/analytics/personalize/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/analytics/personalize", - "main": "../lib/providers/personalize/index.js", - "browser": "../lib-esm/providers/personalize/index.js", - "module": "../lib-esm/providers/personalize/index.js", - "typings": "../lib-esm/providers/personalize/index.d.ts" + "main": "../dist/cjs/providers/personalize/index.js", + "browser": "../dist/esm/providers/personalize/index.mjs", + "module": "../dist/esm/providers/personalize/index.mjs", + "react-native": "../src/providers/personalize/index.ts", + "typings": "../dist/esm/providers/personalize/index.d.ts" } diff --git a/packages/analytics/pinpoint/package.json b/packages/analytics/pinpoint/package.json index 355c1fdea07..c88b5fb5b24 100644 --- a/packages/analytics/pinpoint/package.json +++ b/packages/analytics/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/analytics/pinpoint", - "main": "../lib/providers/pinpoint/index.js", - "browser": "../lib-esm/providers/pinpoint/index.js", - "module": "../lib-esm/providers/pinpoint/index.js", - "typings": "../lib-esm/providers/pinpoint/index.d.ts" + "main": "../dist/cjs/providers/pinpoint/index.js", + "browser": "../dist/esm/providers/pinpoint/index.mjs", + "module": "../dist/esm/providers/pinpoint/index.mjs", + "react-native": "../src/providers/pinpoint/index.ts", + "typings": "../dist/esm/providers/pinpoint/index.d.ts" } diff --git a/packages/analytics/rollup.config.mjs b/packages/analytics/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/analytics/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/analytics/src/providers/personalize/utils/resolveConfig.ts b/packages/analytics/src/providers/personalize/utils/resolveConfig.ts index 0c4d9641a98..990a215b7ca 100644 --- a/packages/analytics/src/providers/personalize/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/personalize/utils/resolveConfig.ts @@ -6,7 +6,10 @@ import { AnalyticsValidationErrorCode, assertValidationError, } from '../../../errors'; -import { DEFAULT_PERSONALIZE_CONFIG, PERSONALIZE_FLUSH_SIZE_MAX } from './'; +import { + DEFAULT_PERSONALIZE_CONFIG, + PERSONALIZE_FLUSH_SIZE_MAX, +} from './constants'; export const resolveConfig = () => { const config = Amplify.getConfig().Analytics?.Personalize; diff --git a/packages/analytics/webpack.config.dev.js b/packages/analytics/webpack.config.dev.js index 7b7ffbdd168..7d4ebcfc7dc 100644 --- a/packages/analytics/webpack.config.dev.js +++ b/packages/analytics/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-analytics': './lib-esm/index.js', + 'aws-amplify-analytics': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/analytics/webpack.config.js b/packages/analytics/webpack.config.js index 262525f3a29..feb0193546a 100644 --- a/packages/analytics/webpack.config.js +++ b/packages/analytics/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-analytics.min': './lib-esm/index.js', + 'aws-amplify-analytics.min': './dist/esm/index.mjs', }, externals: [ 'react-native', @@ -13,7 +13,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_analytics', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/api-graphql/internals/package.json b/packages/api-graphql/internals/package.json index 09613fd5a06..b3bb5b7ed50 100644 --- a/packages/api-graphql/internals/package.json +++ b/packages/api-graphql/internals/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/api-graphql/internals", - "types": "../lib-esm/internals/index.d.ts", - "main": "../lib/internals/index.js", - "module": "../lib-esm/internals/index.js", - "react-native": "../lib-esm/internals/index.js", + "types": "../dist/esm/internals/index.d.ts", + "main": "../dist/cjs/internals/index.js", + "module": "../dist/esm/internals/index.mjs", + "react-native": "../src/internals/index.ts", "sideEffects": false } diff --git a/packages/api-graphql/package.json b/packages/api-graphql/package.json index f993099ab6f..4dbdb44c291 100644 --- a/packages/api-graphql/package.json +++ b/packages/api-graphql/package.json @@ -2,15 +2,13 @@ "name": "@aws-amplify/api-graphql", "version": "4.0.0", "description": "Api-graphql category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": [ - "./lib/GraphQLAPI.js", - "./lib-esm/GraphQLAPI.js" + "./dist/cjs/GraphQLAPI.js", + "./dist/esm/GraphQLAPI.mjs" ], "publishConfig": { "access": "public" @@ -18,18 +16,40 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm test && npm build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 70.0" }, + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./internals": { + "types": "./dist/esm/internals/index.d.ts", + "import": "./dist/esm/internals/index.mjs", + "require": "./dist/cjs/internals/index.js", + "react-native": "./src/internals/index.ts" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + ">=4.2": { + "internals": [ + "./dist/esm/internals/index.d.ts" + ] + } + }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -41,10 +61,12 @@ }, "homepage": "https://aws-amplify.github.io/", "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4" }, "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "internals" ], @@ -60,7 +82,7 @@ "size-limit": [ { "name": "API (GraphQL client)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Amplify, GraphQLAPI }", "limit": "91.7 kB" } @@ -115,8 +137,6 @@ "coveragePathIgnorePatterns": [ "/node_modules/", "/dist", - "/lib", - "/lib-esm", "/__tests__" ] } diff --git a/packages/api-graphql/rollup.config.mjs b/packages/api-graphql/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/api-graphql/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/api-graphql/src/GraphQLAPI.ts b/packages/api-graphql/src/GraphQLAPI.ts index 55ca0a7cc53..858e95e6785 100644 --- a/packages/api-graphql/src/GraphQLAPI.ts +++ b/packages/api-graphql/src/GraphQLAPI.ts @@ -3,7 +3,7 @@ import { AmplifyClassV6 } from '@aws-amplify/core'; import { Category, ApiAction } from '@aws-amplify/core/internals/utils'; import { GraphQLOptions, GraphQLResult } from './types'; -import { InternalGraphQLAPIClass } from './internals'; +import { InternalGraphQLAPIClass } from './internals/InternalGraphQLAPI'; import { Observable } from 'rxjs'; export const graphqlOperation = ( diff --git a/packages/api-graphql/tsconfig.build.json b/packages/api-graphql/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/api-graphql/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/api-graphql/webpack.config.dev.js b/packages/api-graphql/webpack.config.dev.js index efbb2ebd243..6a235ede5f4 100644 --- a/packages/api-graphql/webpack.config.dev.js +++ b/packages/api-graphql/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-api-graphql': './lib-esm/index.js', + 'aws-amplify-api-graphql': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/api-graphql/webpack.config.js b/packages/api-graphql/webpack.config.js index 3f34d8bdd52..32c038ce651 100644 --- a/packages/api-graphql/webpack.config.js +++ b/packages/api-graphql/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-api-graphql.min': './lib-esm/index.js', + 'aws-amplify-api-graphql.min': './dist/esm/index.mjs', }, externals: [ 'graphql', @@ -14,7 +14,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_api-graphql', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/api-rest/internals/package.json b/packages/api-rest/internals/package.json index 2d15f99271b..b86f71a6d28 100644 --- a/packages/api-rest/internals/package.json +++ b/packages/api-rest/internals/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/api-rest/internals", - "types": "../lib-esm/internals/index.d.ts", - "main": "../lib/internals/index.js", - "module": "../lib-esm/internals/index.js", - "react-native": "../lib-esm/internals/index.js", + "types": "../dist/esm/internals/index.d.ts", + "main": "../dist/cjs/internals/index.js", + "module": "../dist/esm/internals/index.mjs", + "react-native": "../src/internals/index.ts", "sideEffects": false } diff --git a/packages/api-rest/internals/server/package.json b/packages/api-rest/internals/server/package.json index ef01dd19817..fea87aef0a6 100644 --- a/packages/api-rest/internals/server/package.json +++ b/packages/api-rest/internals/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/api-rest/internals/server", - "types": "../../lib-esm/internals/server.d.ts", - "main": "../../lib/internals/server.js", - "module": "../../lib-esm/internals/server.js", - "react-native": "../../lib-esm/internals/server.js", + "types": "../../dist/esm/internals/server.d.ts", + "main": "../../dist/cjs/internals/server.js", + "module": "../../dist/esm/internals/server.mjs", "sideEffects": false } diff --git a/packages/api-rest/package.json b/packages/api-rest/package.json index 6a249d45aaf..7c6f616df74 100644 --- a/packages/api-rest/package.json +++ b/packages/api-rest/package.json @@ -3,34 +3,66 @@ "private": false, "version": "4.0.0", "description": "Api-rest category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, - "sideEffects": [ - "./lib/RestAPI.js", - "./lib-esm/RestAPI.js" - ], + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "publishConfig": { "access": "public" }, "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm test && npm build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 70.0" }, + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./server": { + "types": "./dist/esm/server.d.ts", + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.js" + }, + "./internals": { + "types": "./dist/esm/internals/index.d.ts", + "import": "./dist/esm/internals/index.mjs", + "require": "./dist/cjs/internals/index.js", + "react-native": "./src/internals/index.ts" + }, + "./internals/server": { + "types": "./dist/esm/internals/server.d.ts", + "import": "./dist/esm/internals/server.mjs", + "require": "./dist/cjs/internals/server.js" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + ">=4.2": { + "server": [ + "./dist/esm/server.d.ts" + ], + "internals": [ + "./dist/esm/internals/index.d.ts" + ], + "internals/server": [ + "./dist/esm/internals/server.d.ts" + ] + } + }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -42,8 +74,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "internals", "server" @@ -57,12 +89,14 @@ "devDependencies": { "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "API (rest client)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Amplify, RestAPI }", "limit": "31.5 kB" } @@ -103,9 +137,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ], "setupFiles": [ "/setupTests.ts" diff --git a/packages/api-rest/rollup.config.mjs b/packages/api-rest/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/api-rest/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/api-rest/server/package.json b/packages/api-rest/server/package.json index a4aeee5a26a..807c4c6c1b3 100644 --- a/packages/api-rest/server/package.json +++ b/packages/api-rest/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/api-rest/server", - "types": "../lib-esm/server.d.ts", - "main": "../lib/server.js", - "module": "../lib-esm/server.js", - "react-native": "../lib-esm/server.js", + "types": "../dist/esm/server.d.ts", + "main": "../dist/cjs/server.js", + "module": "../dist/esm/server.mjs", "sideEffects": false } diff --git a/packages/api-rest/tsconfig.build.json b/packages/api-rest/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/api-rest/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/api-rest/webpack.config.dev.js b/packages/api-rest/webpack.config.dev.js index c4c8e5fd3fc..b97883d0483 100644 --- a/packages/api-rest/webpack.config.dev.js +++ b/packages/api-rest/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-api-rest': './lib-esm/index.js', + 'aws-amplify-api-rest': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/api-rest/webpack.config.js b/packages/api-rest/webpack.config.js index a7addf39479..590bc6bf882 100644 --- a/packages/api-rest/webpack.config.js +++ b/packages/api-rest/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-api-rest.min': './lib-esm/index.js', + 'aws-amplify-api-rest.min': './dist/esm/index.mjs', }, externals: [ 'graphql', @@ -14,7 +14,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_api-rest', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/api/internals/package.json b/packages/api/internals/package.json index e5ca7a3a13f..710efa1ec8a 100644 --- a/packages/api/internals/package.json +++ b/packages/api/internals/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/api/internals", - "types": "../lib-esm/internals/index.d.ts", - "main": "../lib/internals/index.js", - "module": "../lib-esm/internals/index.js", - "react-native": "../lib-esm/internals/index.js", + "types": "../dist/esm/internals/index.d.ts", + "main": "../dist/cjs/internals/index.js", + "module": "../dist/esm/internals/index.mjs", + "react-native": "../src/internals/index.ts", "sideEffects": false } diff --git a/packages/api/package.json b/packages/api/package.json index 622712e0ab3..1e70b663e5c 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -2,15 +2,13 @@ "name": "@aws-amplify/api", "version": "6.0.0", "description": "Api category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": [ - "./lib/API.js", - "./lib-esm/API.js" + "./dist/cjs/API.js", + "./dist/esm/API.mjs" ], "publishConfig": { "access": "public" @@ -18,16 +16,46 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "build-with-test": "npm test && npm run build", - "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "node ./build es6", - "build:cjs:watch": "node ./build es5 --watch", - "build:esm:watch": "node ./build es6 --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 88" + "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 88" + }, + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./internals": { + "types": "./dist/esm/internals/index.d.ts", + "import": "./dist/esm/internals/index.mjs", + "require": "./dist/cjs/internals/index.js", + "react-native": "./src/internals/index.ts" + }, + "./server": { + "types": "./dist/esm/server.d.ts", + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.js" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + ">=4.2": { + "internals": [ + "./dist/esm/internals/index.d.ts" + ], + "server": [ + "./dist/esm/server.d.ts" + ] + } }, "repository": { "type": "git", @@ -40,11 +68,13 @@ }, "homepage": "https://aws-amplify.github.io/", "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.1.6" }, "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "index.*.d.ts", "internals", @@ -58,7 +88,9 @@ "jest": { "globals": { "ts-jest": { - "diagnostics": false, + "diagnostics": { + "pathRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$" + }, "tsConfig": { "lib": [ "es5", @@ -67,7 +99,10 @@ "esnext.asynciterable", "es2017.object" ], - "allowJs": true + "allowJs": true, + "noEmitOnError": false, + "strictNullChecks": true, + "types": ["@types/jest"] } } }, @@ -93,10 +128,9 @@ } }, "coveragePathIgnorePatterns": [ - "/node_modules/", + "node_modules", "dist", - "lib", - "lib-esm" + "__tests__" ] } } diff --git a/packages/api/rollup.config.mjs b/packages/api/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/api/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/api/server/package.json b/packages/api/server/package.json index 11ec51e821a..7ab2fceccab 100644 --- a/packages/api/server/package.json +++ b/packages/api/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/api/server", - "types": "../lib-esm/server.d.ts", - "main": "../lib/server.js", - "module": "../lib-esm/server.js", - "react-native": "../lib-esm/server.js", + "types": "../dist/esm/server.d.ts", + "main": "../dist/cjs/server.js", + "module": "../dist/esm/server.mjs", "sideEffects": false } diff --git a/packages/api/tsconfig.build.json b/packages/api/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/api/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json new file mode 100644 index 00000000000..791d50a260c --- /dev/null +++ b/packages/api/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "importHelpers": true, + "strict": false, + "noImplicitAny": false, + "strictNullChecks": true, + "skipLibCheck": true + }, + "include": ["./src"] +} diff --git a/packages/api/webpack.config.dev.js b/packages/api/webpack.config.dev.js index 7d6c40c7a79..4e0d6d3ab8b 100644 --- a/packages/api/webpack.config.dev.js +++ b/packages/api/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-api': './lib-esm/index.js', + 'aws-amplify-api': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/api/webpack.config.js b/packages/api/webpack.config.js index f05389784c6..ae5aa44208e 100644 --- a/packages/api/webpack.config.js +++ b/packages/api/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-api.min': './lib-esm/index.js', + 'aws-amplify-api.min': './dist/esm/index.mjs', }, externals: [ 'graphql', @@ -14,7 +14,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_api', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts index 11fc8ef02f5..4155a788c28 100644 --- a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts +++ b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts @@ -12,7 +12,7 @@ import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cogn import { Amplify } from 'aws-amplify'; import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { AuthError } from '../../../src/errors/AuthError'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); const authConfig = { Cognito: { diff --git a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts index 777830ae61b..7f169c1c870 100644 --- a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts @@ -10,7 +10,7 @@ import * as confirmResetPasswordClient from '../../../src/providers/cognito/util import { authAPITestParams } from './testUtils/authApiTestParams'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts index 94001b5f2d4..107e9a07299 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts @@ -9,7 +9,7 @@ import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cogn import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { diff --git a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts index b24ab00c1a0..386ab9eccf9 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts @@ -11,7 +11,7 @@ import { Amplify } from '@aws-amplify/core'; import { ConfirmSignUpCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); const authConfig = { Cognito: { diff --git a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts index 02aef7904f0..f89de538486 100644 --- a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts @@ -1,46 +1,53 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { confirmUserAttribute } from '../../../src/providers/cognito'; import { VerifyUserAttributeException } from '../../../src/providers/cognito/types/errors'; import * as userPoolClients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { VerifyUserAttributeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('confirm user attribute API happy path cases', () => { - let fetchAuthSessionsSpy; let confirmUserAttributeSpy; + beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); confirmUserAttributeSpy = jest .spyOn(userPoolClients, 'verifyUserAttribute') @@ -54,7 +61,7 @@ describe('confirm user attribute API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); confirmUserAttributeSpy.mockClear(); }); @@ -93,17 +100,15 @@ describe('confirmUserAttribute API error path cases:', () => { }); test('confirmUserAttribute API should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts index 76996d8c7fc..889413d2b94 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts @@ -1,55 +1,55 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { deleteUser } from '../../../src/providers/cognito'; import * as cognitoApis from '../../../src/providers/cognito'; import * as TokenProvider from '../../../src/providers/cognito/tokenProvider'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from '@aws-amplify/core'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { DeleteUserException } from '../../../src/providers/cognito/types/errors'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); - -Amplify.configure( - { - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', +import { signOut } from '../../../src/providers/cognito/apis/signOut'; +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); +jest.mock('../../../src/providers/cognito/apis/signOut'); +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, }, - }, + })), }, - { - Auth: { - tokenProvider: TokenProvider.CognitoUserPoolsTokenProvider, - }, - } -); +})); const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; +const mockSignOut = signOut as jest.Mock; + describe('deleteUser API happy path cases', () => { - let fetchAuthSessionsSpy; let deleteUserClientSpy; let tokenOrchestratorSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); deleteUserClientSpy = jest .spyOn(clients, 'deleteUser') .mockImplementationOnce(async () => { @@ -63,16 +63,14 @@ describe('deleteUser API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); deleteUserClientSpy.mockClear(); }); it('Should delete user, signout and clear device tokens', async () => { - const signOutApiSpy = jest - .spyOn(cognitoApis, 'signOut') - .mockImplementationOnce(async () => { - return new Promise(resolve => resolve()); - }); + mockSignOut.mockImplementationOnce(async () => { + return new Promise(resolve => resolve(void 0)); + }); await deleteUser(); @@ -85,11 +83,11 @@ describe('deleteUser API happy path cases', () => { ); expect(deleteUserClientSpy).toBeCalledTimes(1); expect(tokenOrchestratorSpy).toHaveBeenCalledTimes(1); - expect(signOutApiSpy).toHaveBeenCalledTimes(1); + expect(mockSignOut).toHaveBeenCalledTimes(1); // make sure we clearDeviceToken -> signout, in that order expect(tokenOrchestratorSpy.mock.invocationCallOrder[0]).toBeLessThan( - signOutApiSpy.mock.invocationCallOrder[0] + mockSignOut.mock.invocationCallOrder[0] ); }); }); @@ -97,17 +95,15 @@ describe('deleteUser API happy path cases', () => { describe('deleteUser API error path cases', () => { test('Should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse(DeleteUserException.InvalidParameterException) diff --git a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts index bf397596b07..2365b2caa7b 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts @@ -1,44 +1,50 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { deleteUserAttributes } from '../../../src/providers/cognito'; import { DeleteUserAttributesException } from '../../../src/providers/cognito/types/errors'; import * as deleteUserAttributesClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('deleteUserAttributes API happy path cases', () => { - let fetchAuthSessionsSpy; let deleteUserAttributesClientSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); deleteUserAttributesClientSpy = jest .spyOn(deleteUserAttributesClient, 'deleteUserAttributes') .mockImplementation(async () => { @@ -49,12 +55,12 @@ describe('deleteUserAttributes API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); deleteUserAttributesClientSpy.mockClear(); }); afterAll(() => { - fetchAuthSessionsSpy.mockRestore(); + mockFetchAuthSession.mockRestore(); deleteUserAttributesClientSpy.mockRestore(); }); @@ -77,17 +83,15 @@ describe('deleteUserAttributes API happy path cases', () => { describe('deleteUserAttributes API error path cases', () => { it('should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts index dbb898e369a..660f075da57 100644 --- a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts @@ -5,7 +5,7 @@ import { CognitoUserPoolsTokenProvider, cognitoCredentialsProvider, } from '../../../src/providers/cognito'; -import { decodeJWT } from '@aws-amplify/core/lib-esm/libraryUtils'; +import { decodeJWT } from '@aws-amplify/core/internals/utils'; describe('fetchAuthSession behavior for IdentityPools only', () => { let credentialsProviderSpy; diff --git a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts index 8c9e358b293..1dc046fe2ed 100644 --- a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts @@ -1,26 +1,33 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { fetchDevices } from '../../../src/providers/cognito'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from '@aws-amplify/core'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { ListDevicesException } from '../../../src/providers/cognito/types/errors'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; const dateEpoch = 1.696296885807e9; @@ -43,23 +50,22 @@ const apiOutputDevice = { lastAuthenticatedDate: date, }; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('fetchDevices API happy path cases', () => { - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); it('should fetch devices and parse client response correctly', async () => { @@ -87,17 +93,15 @@ describe('fetchDevices API happy path cases', () => { describe('fetchDevices API error path cases', () => { it('should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse(ListDevicesException.InvalidParameterException) diff --git a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts index bd90bbd35cb..84242f6338c 100644 --- a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import * as getUserClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthError } from '../../../src/errors/AuthError'; import { fetchMFAPreference } from '../../../src/providers/cognito/apis/fetchMFAPreference'; @@ -8,39 +9,44 @@ import { GetUserException } from '../../../src/providers/cognito/types/errors'; import { GetUserCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('fetchMFAPreference Happy Path Cases:', () => { let getUserClientSpy; - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); getUserClientSpy = jest .spyOn(getUserClient, 'getUser') .mockImplementationOnce(async (): Promise => { @@ -55,7 +61,7 @@ describe('fetchMFAPreference Happy Path Cases:', () => { }); afterEach(() => { getUserClientSpy.mockClear(); - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test('fetchMFAPreference should return the preferred MFA setting', async () => { @@ -63,9 +69,9 @@ describe('fetchMFAPreference Happy Path Cases:', () => { expect(resp).toEqual({ preferred: 'SMS', enabled: ['SMS', 'TOTP'] }); expect(getUserClientSpy).toHaveBeenCalledTimes(1); expect(getUserClientSpy).toHaveBeenCalledWith( - { + { region: 'us-west-2', - userAgentValue: expect.any(String) + userAgentValue: expect.any(String), }, { AccessToken: mockedAccessToken, @@ -82,17 +88,15 @@ describe('fetchMFAPreference Error Path Cases:', () => { buildMockErrorResponse(GetUserException.InvalidParameterException) ) ); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); try { await fetchMFAPreference(); } catch (error) { diff --git a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts index a15065f1698..0787bc31106 100644 --- a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts @@ -11,7 +11,7 @@ import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-uti import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { fetchUserAttributes } from '../../../src/providers/cognito/apis/fetchUserAttributes'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), fetchAuthSession: jest.fn(), @@ -67,9 +67,9 @@ describe('fetchUserAttributes Happy Path Cases:', () => { }); expect(getUserClientSpy).toHaveBeenCalledTimes(1); expect(getUserClientSpy).toHaveBeenCalledWith( - { + { region: 'us-west-2', - userAgentValue: expect.any(String) + userAgentValue: expect.any(String), }, { AccessToken: mockedAccessToken, diff --git a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts index 93e1bc7e240..fb9c2cf93c1 100644 --- a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts @@ -1,28 +1,35 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { DEVICE_METADATA_NOT_FOUND_EXCEPTION } from '../../../src/errors/constants'; import { forgetDevice } from '../../../src/providers/cognito'; import { ForgetDeviceException } from '../../../src/providers/cognito/types/errors'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import * as TokenProvider from '../../../src/providers/cognito/tokenProvider'; -import { Amplify } from 'aws-amplify'; -import { decodeJWT, retry } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; +import { decodeJWT } from '@aws-amplify/core/internals/utils'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; const mockDeviceMetadata = { @@ -31,23 +38,22 @@ const mockDeviceMetadata = { randomPassword: 'randomPassword', }; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('forgetDevice API happy path cases', () => { - let fetchAuthSessionsSpy; let forgetDeviceStatusClientSpy; let getDeviceMetadataSpy; let clearDeviceMetadataSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); forgetDeviceStatusClientSpy = jest .spyOn(clients, 'forgetDevice') .mockImplementationOnce(async () => { @@ -64,7 +70,7 @@ describe('forgetDevice API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); forgetDeviceStatusClientSpy.mockClear(); getDeviceMetadataSpy.mockClear(); clearDeviceMetadataSpy.mockClear(); @@ -151,26 +157,23 @@ describe('forgetDevice API happy path cases', () => { }); describe('forgetDevice API error path cases', () => { - let fetchAuthSessionsSpy; let getDeviceMetadataSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); getDeviceMetadataSpy = jest .spyOn(TokenProvider.tokenOrchestrator, 'getDeviceMetadata') .mockImplementationOnce(async () => null); }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); getDeviceMetadataSpy.mockClear(); }); diff --git a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts index c2c99483e59..fa54690b375 100644 --- a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts @@ -7,7 +7,7 @@ import { AuthError } from '../../../src/errors/AuthError'; import { getCurrentUser } from '../../../src/providers/cognito'; import { Amplify as AmplifyV6 } from '@aws-amplify/core'; import { USER_UNAUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { diff --git a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts index abf5cc0b59f..0b4b42427df 100644 --- a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts @@ -2,12 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 import { authAPITestParams } from './testUtils/authApiTestParams'; -import { Amplify, Identity, ResourcesConfig } from '@aws-amplify/core'; +import { Amplify, Identity, ResourcesConfig, getId } from '@aws-amplify/core'; import { DefaultIdentityIdStore } from '../../../src/providers/cognito/credentialsProvider/IdentityIdStore'; -import * as cogId from '@aws-amplify/core/internals/aws-clients/cognitoIdentity'; +import { + GetIdInput, + GetIdOutput, +} from '@aws-amplify/core/internals/aws-clients/cognitoIdentity'; import { cognitoIdentityIdProvider } from '../../../src/providers/cognito/credentialsProvider/IdentityIdProvider'; import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + getId: jest.fn(), +})); jest.mock('@aws-amplify/core/internals/aws-clients/cognitoIdentity'); jest.mock('../../../src/providers/cognito/credentialsProvider/IdentityIdStore'); @@ -21,7 +28,7 @@ const ampConfig: ResourcesConfig = { }, }; -const getIdClientSpy = jest.spyOn(cogId, 'getId'); +const mockGetId = getId as jest.Mock; const mockKeyValueStorage = { setItem: jest.fn(), getItem: jest.fn(), @@ -38,19 +45,17 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { beforeAll(() => { jest.spyOn(Amplify, 'getConfig').mockImplementationOnce(() => ampConfig); - getIdClientSpy.mockImplementation( - async (config: {}, params: cogId.GetIdInput) => { - if (params.Logins && Object.keys(params.Logins).length === 0) { - return { - IdentityId: authAPITestParams.GuestIdentityId.id, - } as cogId.GetIdOutput; - } else { - return { - IdentityId: authAPITestParams.PrimaryIdentityId.id, - } as cogId.GetIdOutput; - } + mockGetId.mockImplementation(async (config: {}, params: GetIdInput) => { + if (params.Logins && Object.keys(params.Logins).length === 0) { + return { + IdentityId: authAPITestParams.GuestIdentityId.id, + } as GetIdOutput; + } else { + return { + IdentityId: authAPITestParams.PrimaryIdentityId.id, + } as GetIdOutput; } - ); + }); }); test('Should return stored guest identityId', async () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( @@ -64,7 +69,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityIdStore: mockDefaultIdentityIdStoreInstance, }) ).toBe(authAPITestParams.GuestIdentityId.id); - expect(getIdClientSpy).toBeCalledTimes(0); + expect(mockGetId).toBeCalledTimes(0); }); test('Should generate a guest identityId and return it', async () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( @@ -86,7 +91,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityIdStore: mockDefaultIdentityIdStoreInstance, }) ).toBe(authAPITestParams.GuestIdentityId.id); - expect(getIdClientSpy).toBeCalledTimes(1); + expect(mockGetId).toBeCalledTimes(1); }); test('Should return stored primary identityId', async () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( @@ -101,7 +106,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityIdStore: mockDefaultIdentityIdStoreInstance, }) ).toBe(authAPITestParams.PrimaryIdentityId.id); - expect(getIdClientSpy).toBeCalledTimes(0); + expect(mockGetId).toBeCalledTimes(0); }); test('Should generate a primary identityId and return it', async () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( @@ -124,6 +129,6 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityIdStore: mockDefaultIdentityIdStoreInstance, }) ).toBe(authAPITestParams.PrimaryIdentityId.id); - expect(getIdClientSpy).toBeCalledTimes(1); + expect(mockGetId).toBeCalledTimes(1); }); }); diff --git a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts index 95d597e017c..6ce812dc43a 100644 --- a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts +++ b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts @@ -5,7 +5,7 @@ import { refreshAuthTokens } from '../../../src/providers/cognito/utils/refreshA import { CognitoAuthTokens } from '../../../src/providers/cognito/tokenProvider/types'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); describe('refresh token tests', () => { const mockedUsername = 'mockedUsername'; diff --git a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts index bb532c63057..b7c46445dd6 100644 --- a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts @@ -1,28 +1,34 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { rememberDevice } from '../../../src/providers/cognito'; import { UpdateDeviceStatusException } from '../../../src/providers/cognito/types/errors'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import * as TokenProvider from '../../../src/providers/cognito/tokenProvider'; import { DeviceMetadata } from '../../../src/providers/cognito/tokenProvider/types'; -import { Amplify } from 'aws-amplify'; import { decodeJWT, retry } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; const mockDeviceMetadata: DeviceMetadata = { @@ -31,22 +37,21 @@ const mockDeviceMetadata: DeviceMetadata = { randomPassword: 'randomPassword', }; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; + describe('rememberDevice API happy path cases', () => { - let fetchAuthSessionsSpy; let updateDeviceStatusClientSpy; let tokenOrchestratorSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); updateDeviceStatusClientSpy = jest .spyOn(clients, 'updateDeviceStatus') .mockImplementationOnce(async () => { @@ -60,7 +65,7 @@ describe('rememberDevice API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); updateDeviceStatusClientSpy.mockClear(); }); @@ -82,17 +87,15 @@ describe('rememberDevice API happy path cases', () => { describe('rememberDevice API error path cases', () => { it('should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts index 59903595d72..a2f1c7b5506 100644 --- a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts @@ -11,7 +11,7 @@ import { ResendConfirmationCodeCommandOutput } from '../../../src/providers/cogn import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { diff --git a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts index 5d9f43fe052..99dccca9c9f 100644 --- a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts @@ -10,7 +10,7 @@ import { ForgotPasswordCommandOutput } from '../../../src/providers/cognito/util import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { diff --git a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts index e6bc9a6680d..301ef39db41 100644 --- a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts @@ -1,46 +1,49 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { authAPITestParams } from './testUtils/authApiTestParams'; import { sendUserAttributeVerificationCode } from '../../../src/providers/cognito'; import { GetUserAttributeVerificationException } from '../../../src/providers/cognito/types/errors'; import * as getUserAttributeVerificationCodeClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { GetUserAttributeVerificationCodeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('resendUserAttributeConfirmationCode API happy path cases', () => { - let fetchAuthSessionsSpy; let getUserAttributeVerificationCodeClientSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); getUserAttributeVerificationCodeClientSpy = jest .spyOn( getUserAttributeVerificationCodeClient, @@ -53,7 +56,7 @@ describe('resendUserAttributeConfirmationCode API happy path cases', () => { }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); getUserAttributeVerificationCodeClientSpy.mockClear(); }); @@ -81,17 +84,15 @@ describe('resendUserAttributeConfirmationCode API happy path cases', () => { describe('resendUserAttributeConfirmationCode API error path cases', () => { test('Should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts index 6dc61a663af..6b2fe0280ae 100644 --- a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts +++ b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts @@ -1,45 +1,51 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 + +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { AssociateSoftwareTokenException } from '../../../src/providers/cognito/types/errors'; import * as associateSoftwareTokenClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { setUpTOTP } from '../../../src/providers/cognito'; import { AssociateSoftwareTokenCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); + const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('setUpTOTP API happy path cases', () => { let associateSoftwareTokenClientSpy; - let fetchAuthSessionsSpy; const secretCode = 'asfdasdfwefasdfasf'; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); associateSoftwareTokenClientSpy = jest .spyOn(associateSoftwareTokenClient, 'associateSoftwareToken') .mockImplementationOnce( @@ -54,15 +60,15 @@ describe('setUpTOTP API happy path cases', () => { afterEach(() => { associateSoftwareTokenClientSpy.mockClear(); - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test('setUpTOTP API should call the UserPoolClient and should return a TOTPSetupDetails', async () => { const result = await setUpTOTP(); expect(associateSoftwareTokenClientSpy).toHaveBeenCalledWith( - { + { region: 'us-west-2', - userAgentValue: expect.any(String) + userAgentValue: expect.any(String), }, { AccessToken: mockedAccessToken, @@ -83,17 +89,15 @@ describe('setUpTOTP API error path cases:', () => { ) ) ); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); try { await setUpTOTP(); } catch (error) { diff --git a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts index 7102a511168..fa948beb54c 100644 --- a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts @@ -15,7 +15,7 @@ import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-uti import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../src/errors/constants'; jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); const authConfig = { Cognito: { diff --git a/packages/auth/__tests__/providers/cognito/signOut.test.ts b/packages/auth/__tests__/providers/cognito/signOut.test.ts index 2ff786247e9..aa65a8d66c5 100644 --- a/packages/auth/__tests__/providers/cognito/signOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/signOut.test.ts @@ -6,7 +6,7 @@ import * as clients from '../../../src/providers/cognito/utils/clients/CognitoId import { DefaultOAuthStore } from '../../../src/providers/cognito/utils/signInWithRedirectStore'; import { openAuthSession } from '../../../src/utils'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); jest.mock('../../../src/utils'); const mockedAccessToken = diff --git a/packages/auth/__tests__/providers/cognito/signUp.test.ts b/packages/auth/__tests__/providers/cognito/signUp.test.ts index 23ac5490f53..6839aa94385 100644 --- a/packages/auth/__tests__/providers/cognito/signUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/signUp.test.ts @@ -11,7 +11,7 @@ import { SignUpCommandOutput } from '../../../src/providers/cognito/utils/client import { Amplify } from 'aws-amplify'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); Amplify.configure({ Auth: { @@ -55,9 +55,9 @@ describe('SignUp API Happy Path Cases:', () => { userId: '1234567890', }); expect(signUpSpy).toHaveBeenCalledWith( - { + { region: 'us-west-2', - userAgentValue: expect.any(String) + userAgentValue: expect.any(String), }, { ClientMetadata: undefined, diff --git a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts index 3b2058b2e18..349418ee95e 100644 --- a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts @@ -1,21 +1,39 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { updateMFAPreference } from '../../../src/providers/cognito'; +import { fetchAuthSession } from '@aws-amplify/core'; +import { + UpdateMFAPreferenceInput, + updateMFAPreference, +} from '../../../src/providers/cognito'; import * as setUserMFAPreferenceClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { AuthError } from '../../../src/errors/AuthError'; import { SetUserMFAPreferenceException } from '../../../src/providers/cognito/types/errors'; -import { UpdateMFAPreferenceRequest } from '../../../src/providers/cognito/types'; import { getMFASettings } from '../../../src/providers/cognito/apis/updateMFAPreference'; import { SetUserMFAPreferenceCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -const mfaChoises: UpdateMFAPreferenceRequest[] = [ +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), + }, +})); + +const mfaChoises: UpdateMFAPreferenceInput[] = [ { sms: 'DISABLED', totp: 'DISABLED' }, { sms: 'DISABLED', totp: 'ENABLED' }, { sms: 'DISABLED', totp: 'PREFERRED' }, @@ -34,34 +52,21 @@ const mfaChoises: UpdateMFAPreferenceRequest[] = [ { sms: 'NOT_PREFERRED', totp: 'NOT_PREFERRED' }, {}, ]; - -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, - }, -}); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('updateMFAPreference Happy Path Cases:', () => { let setUserMFAPreferenceClientSpy; - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); setUserMFAPreferenceClientSpy = jest .spyOn(setUserMFAPreferenceClient, 'setUserMFAPreference') .mockImplementationOnce(async () => { @@ -70,7 +75,7 @@ describe('updateMFAPreference Happy Path Cases:', () => { }); afterEach(() => { setUserMFAPreferenceClientSpy.mockClear(); - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test.each(mfaChoises)( 'setUserMFAPreferenceClient should be called with all possible mfa combinations', @@ -78,9 +83,9 @@ describe('updateMFAPreference Happy Path Cases:', () => { const { totp, sms } = mfaChoise; await updateMFAPreference(mfaChoise); expect(setUserMFAPreferenceClientSpy).toHaveBeenCalledWith( - { + { region: 'us-west-2', - userAgentValue: expect.any(String) + userAgentValue: expect.any(String), }, { AccessToken: mockedAccessToken, @@ -100,17 +105,15 @@ describe('updateMFAPreference Error Path Cases:', () => { buildMockErrorResponse(SetUserMFAPreferenceException.ForbiddenException) ) ); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); try { await updateMFAPreference({ sms: 'ENABLED', totp: 'PREFERRED' }); } catch (error) { diff --git a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts index 7afb0bd5517..9ab20380d61 100644 --- a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts @@ -1,49 +1,52 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { updatePassword } from '../../../src/providers/cognito'; import { ChangePasswordException } from '../../../src/providers/cognito/types/errors'; import * as changePasswordClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { ChangePasswordCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('updatePassword API happy path cases', () => { const oldPassword = 'oldPassword'; const newPassword = 'newPassword'; let changePasswordClientSpy; - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); changePasswordClientSpy = jest .spyOn(changePasswordClient, 'changePassword') .mockImplementationOnce( @@ -55,7 +58,7 @@ describe('updatePassword API happy path cases', () => { afterEach(() => { changePasswordClientSpy.mockClear(); - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test('updatePassword should call changePassword', async () => { @@ -98,17 +101,15 @@ describe('updatePassword API error path cases:', () => { test('updatePassword API should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts index c637e84ece2..abc46c68c17 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { updateUserAttribute, @@ -8,43 +9,48 @@ import { } from '../../../src/providers/cognito'; import * as updateUserAttributesApi from '../../../src/providers/cognito'; import { UpdateUserAttributesException } from '../../../src/providers/cognito/types/errors'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +import { updateUserAttributes } from '../../../src/providers/cognito/apis/updateUserAttributes'; +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); +jest.mock('../../../src/providers/cognito/apis/updateUserAttributes'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'test_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; +const mockUpdateUserAttributes = updateUserAttributes as jest.Mock; describe('updateUserAttribute API happy path cases', () => { - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); it('should call updateUserAttributes with correct input and should return correct output', async () => { @@ -68,15 +74,13 @@ describe('updateUserAttribute API happy path cases', () => { }, }, }; - const updateUserAttributesSpy = jest - .spyOn(updateUserAttributesApi, 'updateUserAttributes') - .mockImplementationOnce(async () => { - return { email: mockOutput } as UpdateUserAttributesOutput; - }); + mockUpdateUserAttributes.mockImplementationOnce(async () => { + return { email: mockOutput } as UpdateUserAttributesOutput; + }); const result = await updateUserAttribute(mockInput); expect(result).toEqual(mockOutput); - expect(updateUserAttributesSpy).toBeCalledTimes(1); - expect(updateUserAttributesSpy).toHaveBeenCalledWith({ + expect(mockUpdateUserAttributes).toBeCalledTimes(1); + expect(mockUpdateUserAttributes).toHaveBeenCalledWith({ userAttributes: { [mockInput.userAttribute.attributeKey]: mockInput.userAttribute.value, }, @@ -84,43 +88,3 @@ describe('updateUserAttribute API happy path cases', () => { }); }); }); - -describe('updateUserAttribute API error path cases:', () => { - it('should raise service error', async () => { - expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); - (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse( - buildMockErrorResponse( - UpdateUserAttributesException.InvalidParameterException - ) - ) - ); - try { - await updateUserAttribute({ - userAttribute: { - attributeKey: 'email', - value: 'mockedEmail', - }, - options: { - clientMetadata: { foo: 'bar' }, - }, - }); - } catch (error) { - expect(error).toBeInstanceOf(AuthError); - expect(error.name).toBe( - UpdateUserAttributesException.InvalidParameterException - ); - } - }); -}); diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts index 907241b878d..f02dcdc017f 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts @@ -1,49 +1,52 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { updateUserAttributes } from '../../../src/providers/cognito'; import { UpdateUserAttributesException } from '../../../src/providers/cognito/types/errors'; import * as updateUserAttributesClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; -import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; import { UpdateUserAttributesCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { toAttributeType } from '../../../src/providers/cognito/utils/apiHelpers'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('updateUserAttributes API happy path cases', () => { - let fetchAuthSessionsSpy; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); }); afterEach(() => { - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test('updateUserAttributes API should return a map with updated and not updated attributes', async () => { @@ -241,17 +244,15 @@ describe('updateUserAttributes API happy path cases', () => { describe('updateUserAttributes API error path cases:', () => { test('updateUserAttributes API should raise service error', async () => { expect.assertions(2); - jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); (fetchTransferHandler as jest.Mock).mockResolvedValue( mockJsonResponse( buildMockErrorResponse( diff --git a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts index fa485b36502..49bf8b3042c 100644 --- a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts +++ b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts @@ -1,49 +1,53 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { fetchAuthSession } from '@aws-amplify/core'; import { AuthError } from '../../../src/errors/AuthError'; import { AuthValidationErrorCode } from '../../../src/errors/types/validation'; import { VerifySoftwareTokenException } from '../../../src/providers/cognito/types/errors'; import { verifyTOTPSetup } from '../../../src/providers/cognito'; import * as verifySoftwareTokenClient from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; import { VerifySoftwareTokenCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { Amplify } from 'aws-amplify'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; import * as authUtils from '../../../src'; import { fetchTransferHandler } from '@aws-amplify/core/internals/aws-client-utils'; import { buildMockErrorResponse, mockJsonResponse } from './testUtils/data'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); -Amplify.configure({ - Auth: { - Cognito: { - userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - userPoolId: 'us-west-2_zzzzz', - identityPoolId: 'us-west-2:xxxxxx', - }, +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + fetchAuthSession: jest.fn(), + Amplify: { + configure: jest.fn(), + getConfig: jest.fn(() => ({ + Auth: { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + identityPoolId: 'us-west-2:xxxxxx', + }, + }, + })), }, -}); +})); const mockedAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; - +const mockFetchAuthSession = fetchAuthSession as jest.Mock; describe('verifyTOTPSetup API happy path cases', () => { let verifySoftwareTokenClientSpy; - let fetchAuthSessionsSpy; const code = '123456'; const friendlyDeviceName = 'FriendlyDeviceName'; beforeEach(() => { - fetchAuthSessionsSpy = jest - .spyOn(authUtils, 'fetchAuthSession') - .mockImplementationOnce( - async (): Promise<{ tokens: { accessToken: any } }> => { - return { - tokens: { - accessToken: decodeJWT(mockedAccessToken), - }, - }; - } - ); + mockFetchAuthSession.mockImplementationOnce( + async (): Promise<{ tokens: { accessToken: any } }> => { + return { + tokens: { + accessToken: decodeJWT(mockedAccessToken), + }, + }; + } + ); verifySoftwareTokenClientSpy = jest .spyOn(verifySoftwareTokenClient, 'verifySoftwareToken') .mockImplementationOnce(async () => { @@ -53,7 +57,7 @@ describe('verifyTOTPSetup API happy path cases', () => { afterEach(() => { verifySoftwareTokenClientSpy.mockClear(); - fetchAuthSessionsSpy.mockClear(); + mockFetchAuthSession.mockClear(); }); test('verifyTOTPSetup API should return successful response', async () => { diff --git a/packages/auth/__tests__/utils/getAuthUserAgentValue.test.ts b/packages/auth/__tests__/utils/getAuthUserAgentValue.test.ts index 0e84cb9e74a..081e6d917a0 100644 --- a/packages/auth/__tests__/utils/getAuthUserAgentValue.test.ts +++ b/packages/auth/__tests__/utils/getAuthUserAgentValue.test.ts @@ -8,7 +8,10 @@ import { } from '@aws-amplify/core/internals/utils'; import { getAuthUserAgentValue } from '../../src/utils'; -jest.mock('@aws-amplify/core/internals/utils'); +jest.mock('@aws-amplify/core/internals/utils', () => ({ + ...jest.requireActual('@aws-amplify/core/internals/utils'), + getAmplifyUserAgent: jest.fn(), +})); describe('getAuthUserAgentValue', () => { // assert mocks diff --git a/packages/auth/cognito/package.json b/packages/auth/cognito/package.json index e34eb233be8..015dea9cc3d 100644 --- a/packages/auth/cognito/package.json +++ b/packages/auth/cognito/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/auth/cognito", - "main": "../lib/providers/cognito/index.js", - "browser": "../lib-esm/providers/cognito/index.js", - "module": "../lib-esm/providers/cognito/index.js", - "typings": "../lib-esm/providers/cognito/index.d.ts" + "main": "../dist/cjs/providers/cognito/index.js", + "react-native": "../src/providers/cognito/index.ts", + "browser": "../dist/esm/providers/cognito/index.mjs", + "module": "../dist/esm/providers/cognito/index.mjs", + "typings": "../dist/esm/providers/cognito/index.d.ts" } diff --git a/packages/auth/cognito/server/package.json b/packages/auth/cognito/server/package.json index dfc8fc1645f..06af806fb99 100644 --- a/packages/auth/cognito/server/package.json +++ b/packages/auth/cognito/server/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/auth/cognito/server", - "main": "../../lib/providers/cognito/apis/server/index.js", - "browser": "../../lib-esm/providers/cognito/apis/server/index.js", - "module": "../../lib-esm/providers/cognito/apis/server/index.js", - "typings": "../../lib-esm/providers/cognito/apis/server/index.d.ts" + "main": "../../dist/cjs/providers/cognito/apis/server/index.js", + "browser": "../../dist/esm/providers/cognito/apis/server/index.mjs", + "module": "../../dist/esm/providers/cognito/apis/server/index.mjs", + "typings": "../../dist/esm/providers/cognito/apis/server/index.d.ts" } diff --git a/packages/auth/package.json b/packages/auth/package.json index c36d03ff74e..ca67788ef1d 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -2,13 +2,13 @@ "name": "@aws-amplify/auth", "version": "6.0.0", "description": "Auth category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": "./lib-esm/index.js", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": [ - "./lib/providers/cognito/apis/signInWithRedirect.js", - "./lib-esm/providers/cognito/apis/signInWithRedirect.js" + "./dist/cjs/providers/cognito/apis/signInWithRedirect.js", + "./dist/esm/providers/cognito/apis/signInWithRedirect.mjs" ], "publishConfig": { "access": "public" @@ -16,11 +16,11 @@ "scripts": { "test": "yarn lint --fix && jest -w 1 --coverage", "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", "clean": "npm run clean:size && rimraf lib-esm lib dist", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", @@ -30,44 +30,38 @@ "typesVersions": { ">=4.2": { "cognito": [ - "./lib-esm/providers/cognito/index.d.ts" + "./dist/esm/providers/cognito/index.d.ts" ], "cognito/server": [ - "./lib-esm/providers/cognito/apis/server/index.d.ts" + "./dist/esm/providers/cognito/apis/server/index.d.ts" ], "server": [ - "./lib-esm/server.d.ts" - ], - "internals": [ - "./lib-esm/lib-esm/internals/index.d.ts" + "./dist/esm/server.d.ts" ] } }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./cognito": { - "types": "./lib-esm/providers/cognito/index.d.ts", - "import": "./lib-esm/providers/cognito/index.js", - "require": "./lib/providers/cognito/index.js" + "types": "./dist/esm/providers/cognito/index.d.ts", + "import": "./dist/esm/providers/cognito/index.mjs", + "require": "./dist/cjs/providers/cognito/index.js", + "react-native": "./src/providers/cognito/index.ts" }, "./cognito/server": { - "types": "./lib-esm/providers/cognito/apis/server/index.d.ts", - "import": "./lib-esm/providers/cognito/apis/server/index.js", - "require": "./lib/providers/cognito/apis/server/index.js" + "types": "./dist/esm/providers/cognito/apis/server/index.d.ts", + "import": "./dist/esm/providers/cognito/apis/server/index.mjs", + "require": "./dist/cjs/providers/cognito/apis/server/index.js" }, "./server": { - "types": "./lib-esm/server.d.ts", - "import": "./lib-esm/server.js", - "require": "./lib/server.js" - }, - "./internals": { - "types": "./lib-esm/lib-esm/internals/index.d.ts", - "import": "./lib-esm/internals/index.js", - "require": "./lib/internals/index.js" + "types": "./dist/esm/server.d.ts", + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.js" }, "./package.json": "./package.json" }, @@ -82,10 +76,9 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", - "internals", "cognito", "server" ], @@ -98,7 +91,9 @@ "devDependencies": { "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", + "@rollup/plugin-typescript": "11.1.5", "@jest/test-sequencer": "^24.9.0", + "rollup": "3.29.4", "typescript": "5.0.2" }, "jest": { diff --git a/packages/auth/rollup.config.mjs b/packages/auth/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/auth/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/auth/server/package.json b/packages/auth/server/package.json index fc9e128f595..5fda3a08009 100644 --- a/packages/auth/server/package.json +++ b/packages/auth/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/auth/server", - "types": "../lib-esm/server.d.ts", - "main": "../lib/server.js", - "module": "../lib-esm/server.js", - "react-native": "../lib-esm/server.js", + "types": "../dist/esm/server.d.ts", + "main": "../dist/cjs/server.js", + "module": "../dist/esm/server.mjs", "sideEffects": false } diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index c97cfade231..37dbc5888d4 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -1,13 +1,15 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { AuthValidationErrorCode } from '../../../errors/types/validation'; import { assertValidationError } from '../../../errors/utils/assertValidationError'; import { verifyUserAttribute } from '../utils/clients/CognitoIdentityProvider'; import { VerifyUserAttributeException } from '../types/errors'; -import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { ConfirmUserAttributeInput } from '../types'; @@ -37,7 +39,7 @@ export async function confirmUserAttribute( await verifyUserAttribute( { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmUserAttribute) + userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmUserAttribute), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index 3f32627c712..1ef4ca242f6 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -1,18 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertTokenProviderConfig, AuthAction, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { deleteUser as serviceDeleteUser } from '../utils/clients/CognitoIdentityProvider'; import { DeleteUserException } from '../types/errors'; import { tokenOrchestrator } from '../tokenProvider'; -import { signOut } from '..'; +import { signOut } from './signOut'; import { getAuthUserAgentValue } from '../../../utils'; /** diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index 9324e3b335b..89201a6ef52 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -1,10 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { deleteUserAttributes as deleteUserAttributesClient } from '../utils/clients/CognitoIdentityProvider'; -import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { DeleteUserAttributesInput } from '../types'; @@ -29,7 +31,7 @@ export async function deleteUserAttributes( await deleteUserAttributesClient( { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUserAttributes) + userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUserAttributes), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index dbe22f19840..3b697ea5c81 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -1,12 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertTokenProviderConfig, AuthAction, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; import { FetchDevicesOutput } from '../types'; import { listDevices } from '../utils/clients/CognitoIdentityProvider'; import { DeviceType } from '../utils/clients/CognitoIdentityProvider/types'; diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index 497121e39a5..44dc90415af 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -5,9 +5,11 @@ import { FetchMFAPreferenceOutput } from '../types'; import { getMFAType, getMFATypes } from '../utils/signInHelpers'; import { GetUserException } from '../types/errors'; import { getUser } from '../utils/clients/CognitoIdentityProvider'; -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; @@ -26,9 +28,9 @@ export async function fetchMFAPreference(): Promise { const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); const { PreferredMfaSetting, UserMFASettingList } = await getUser( - { + { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.FetchMFAPreference) + userAgentValue: getAuthUserAgentValue(AuthAction.FetchMFAPreference), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index 05b1060fb03..8ea78399fef 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -2,13 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { forgetDevice as serviceForgetDevice } from '../utils/clients/CognitoIdentityProvider'; -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; import { assertTokenProviderConfig, AuthAction, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { tokenOrchestrator } from '../tokenProvider'; import { ForgetDeviceInput } from '../types'; diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index 2528cc467f5..0623998cd08 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -2,10 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { updateDeviceStatus } from '../utils/clients/CognitoIdentityProvider'; -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertAuthTokens, assertDeviceMetadata } from '../utils/types'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { tokenOrchestrator } from '../tokenProvider'; import { UpdateDeviceStatusException } from '../../cognito/types/errors'; @@ -29,9 +31,9 @@ export async function rememberDevice(): Promise { assertDeviceMetadata(deviceMetadata); await updateDeviceStatus( - { + { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.RememberDevice) + userAgentValue: getAuthUserAgentValue(AuthAction.RememberDevice), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index a5ef2d7d145..d3e7562073a 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -1,13 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertTokenProviderConfig, AuthAction, AuthVerifiableAttributeKey, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../..'; import { AuthDeliveryMedium } from '../../../types'; import { SendUserAttributeVerificationCodeInput, diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index f445ba7835f..e3e30f72ae3 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -1,9 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { AuthError } from '../../../errors/AuthError'; import { SETUP_TOTP_EXCEPTION, @@ -31,9 +33,9 @@ export async function setUpTOTP(): Promise { assertAuthTokens(tokens); const username = tokens.idToken?.payload['cognito:username'] ?? ''; const { SecretCode } = await associateSoftwareToken( - { + { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.SetUpTOTP) + userAgentValue: getAuthUserAgentValue(AuthAction.SetUpTOTP), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index e5b9c79b0fd..116a384231c 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -1,9 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { UpdateMFAPreferenceInput } from '../types'; import { SetUserMFAPreferenceException } from '../types/errors'; import { MFAPreference } from '../types/models'; @@ -29,9 +31,9 @@ export async function updateMFAPreference( const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); await setUserMFAPreference( - { + { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.UpdateMFAPreference) + userAgentValue: getAuthUserAgentValue(AuthAction.UpdateMFAPreference), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index 99b1a2c34ac..955f4cae51a 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -6,9 +6,11 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { UpdatePasswordInput } from '../types'; import { changePassword } from '../utils/clients/CognitoIdentityProvider'; import { ChangePasswordException } from '../../cognito/types/errors'; -import { Amplify } from '@aws-amplify/core'; -import { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; +import { + assertTokenProviderConfig, + AuthAction, +} from '@aws-amplify/core/internals/utils'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; @@ -39,9 +41,9 @@ export async function updatePassword( const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); await changePassword( - { + { region: getRegion(authConfig.userPoolId), - userAgentValue: getAuthUserAgentValue(AuthAction.UpdatePassword) + userAgentValue: getAuthUserAgentValue(AuthAction.UpdatePassword), }, { AccessToken: tokens.accessToken.toString(), diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts index 7df02abe598..e8a2af55f78 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts @@ -3,7 +3,7 @@ import { UpdateUserAttributeInput, UpdateUserAttributeOutput } from '../types'; import { UpdateUserAttributesException } from '../types/errors'; -import { updateUserAttributes } from '..'; +import { updateUserAttributes } from './updateUserAttributes'; /** * Updates user's attribute while authenticated. diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index 031679102a9..f52e68005ed 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -1,12 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertTokenProviderConfig, AuthAction, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; import { AuthUserAttributes, AuthUpdateUserAttributesOutput, diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 3b1353d6a4a..597a13750e1 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -6,12 +6,11 @@ import { assertValidationError } from '../../../errors/utils/assertValidationErr import { VerifyTOTPSetupInput } from '../types'; import { verifySoftwareToken } from '../utils/clients/CognitoIdentityProvider'; import { VerifySoftwareTokenException } from '../types/errors'; -import { Amplify } from '@aws-amplify/core'; +import { Amplify, fetchAuthSession } from '@aws-amplify/core'; import { assertTokenProviderConfig, AuthAction, } from '@aws-amplify/core/internals/utils'; -import { fetchAuthSession } from '../../../'; import { getRegion } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertAuthTokens } from '../utils/types'; import { getAuthUserAgentValue } from '../../../utils'; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index 36a37316786..1c8be32d077 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -3,11 +3,11 @@ import { AuthTokens, getId, ConsoleLogger } from '@aws-amplify/core'; import { CognitoIdentityPoolConfig } from '@aws-amplify/core/internals/utils'; -import { formLoginsMap } from './credentialsProvider'; import { AuthError } from '../../../errors/AuthError'; import { IdentityIdStore } from './types'; import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; import { Identity } from '@aws-amplify/core'; +import { formLoginsMap } from './utils'; const logger = new ConsoleLogger('CognitoIdentityIdProvider'); diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index b394ebd883e..a2ef6bc38d9 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -19,6 +19,7 @@ import { AuthError } from '../../../errors/AuthError'; import { IdentityIdStore } from './types'; import { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils'; import { assertIdTokenInAuthTokens } from '../utils/types'; +import { formLoginsMap } from './utils'; const logger = new ConsoleLogger('CognitoCredentialsProvider'); const CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future @@ -241,18 +242,3 @@ export class CognitoAWSCredentialsAndIdentityIdProvider ); } } - -export function formLoginsMap(idToken: string) { - const issuer = decodeJWT(idToken).payload.iss; - const res: Record = {}; - if (!issuer) { - throw new AuthError({ - name: 'InvalidIdTokenException', - message: 'Invalid Idtoken.', - }); - } - let domainName: string = issuer.replace(/(^\w+:|^)\/\//, ''); - - res[domainName] = idToken; - return res; -} diff --git a/packages/auth/src/providers/cognito/credentialsProvider/utils.ts b/packages/auth/src/providers/cognito/credentialsProvider/utils.ts new file mode 100644 index 00000000000..f0b5e15cb7c --- /dev/null +++ b/packages/auth/src/providers/cognito/credentialsProvider/utils.ts @@ -0,0 +1,20 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { decodeJWT } from '@aws-amplify/core/internals/utils'; +import { AuthError } from '../../../errors/AuthError'; + +export function formLoginsMap(idToken: string) { + const issuer = decodeJWT(idToken).payload.iss; + const res: Record = {}; + if (!issuer) { + throw new AuthError({ + name: 'InvalidIdTokenException', + message: 'Invalid Idtoken.', + }); + } + let domainName: string = issuer.replace(/(^\w+:|^)\/\//, ''); + + res[domainName] = idToken; + return res; +} diff --git a/packages/auth/webpack.config.dev.js b/packages/auth/webpack.config.dev.js index 962b8a7cc63..42288ca7c74 100644 --- a/packages/auth/webpack.config.dev.js +++ b/packages/auth/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-auth': './lib-esm/index.js', + 'aws-amplify-auth': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/auth/webpack.config.js b/packages/auth/webpack.config.js index d2d729b408e..31a5f06678e 100644 --- a/packages/auth/webpack.config.js +++ b/packages/auth/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-auth.min': './lib-esm/index.js', + 'aws-amplify-auth.min': './dist/esm/index.mjs', }, externals: [ 'react-native', @@ -10,7 +10,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_auth', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index d5f7208356e..d35f392da1d 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -24,252 +24,232 @@ import * as storageS3Exports from '../src/storage/s3'; describe('aws-amplify Exports', () => { describe('Top-level exports', () => { it('should only export expected symbols', () => { - expect(Object.keys(topLevelExports)).toMatchInlineSnapshot(` - Array [ - "Amplify", - ] - `); + expect(Object.keys(topLevelExports).sort()).toEqual(['Amplify'].sort()); }); }); describe('Utils exports', () => { it('should only export expected symbols', () => { - expect(Object.keys(utilsExports)).toMatchInlineSnapshot(` - Array [ - "Hub", - "I18n", - "Cache", - "ConsoleLogger", - "ServiceWorker", - "CookieStorage", - "defaultStorage", - "sessionStorage", - "sharedInMemoryStorage", - ] - `); + expect(Object.keys(utilsExports).sort()).toEqual( + [ + 'Hub', + 'I18n', + 'Cache', + 'ConsoleLogger', + 'ServiceWorker', + 'CookieStorage', + 'defaultStorage', + 'sessionStorage', + 'sharedInMemoryStorage', + ].sort() + ); }); }); describe('API exports', () => { it('should only export expected symbols from the top level', () => { - expect(Object.keys(apiTopLevelExports)).toMatchInlineSnapshot(` - Array [ - "generateClient", - "GraphQLAuthError", - "ConnectionState", - "get", - "put", - "post", - "del", - "head", - "patch", - "isCancelError", - ] - `); + expect(Object.keys(apiTopLevelExports).sort()).toEqual( + [ + 'ConnectionState', + 'GraphQLAuthError', + 'del', + 'generateClient', + 'get', + 'head', + 'isCancelError', + 'patch', + 'post', + 'put', + ].sort() + ); }); }); describe('Analytics exports', () => { it('should only export expected symbols from the top-level', () => { - expect(Object.keys(analyticsTopLevelExports)).toMatchInlineSnapshot(` - Array [ - "record", - "identifyUser", - "configureAutoTrack", - "flushEvents", - "enable", - "disable", - "AnalyticsError", - ] - `); + expect(Object.keys(analyticsTopLevelExports).sort()).toEqual( + [ + 'record', + 'identifyUser', + 'configureAutoTrack', + 'flushEvents', + 'enable', + 'disable', + 'AnalyticsError', + ].sort() + ); }); it('should only export expected symbols from the Pinpoint provider', () => { - expect(Object.keys(analyticsPinpointExports)).toMatchInlineSnapshot(` - Array [ - "record", - "identifyUser", - "flushEvents", - "configureAutoTrack", - ] - `); + expect(Object.keys(analyticsPinpointExports).sort()).toEqual( + ['record', 'identifyUser', 'configureAutoTrack', 'flushEvents'].sort() + ); }); it('should only export expected symbols from the Kinesis provider', () => { - expect(Object.keys(analyticsKinesisExports)).toMatchInlineSnapshot(` - Array [ - "record", - "flushEvents", - ] - `); + expect(Object.keys(analyticsKinesisExports).sort()).toEqual( + ['record', 'flushEvents'].sort() + ); }); it('should only export expected symbols from the Kinesis Firehose provider', () => { - expect(Object.keys(analyticsKinesisFirehoseExports)) - .toMatchInlineSnapshot(` - Array [ - "record", - "flushEvents", - ] - `); + expect(Object.keys(analyticsKinesisFirehoseExports).sort()).toEqual( + ['record', 'flushEvents'].sort() + ); }); it('should only export expected symbols from the Personalize provider', () => { - expect(Object.keys(analyticsPersonalizeExports)).toMatchInlineSnapshot(` - Array [ - "record", - "flushEvents", - ] - `); + expect(Object.keys(analyticsPersonalizeExports).sort()).toEqual( + ['record', 'flushEvents'].sort() + ); }); }); describe('InAppMessaging exports', () => { it('should only export expected symbols from the top-level', () => { - expect(Object.keys(inAppMessagingTopLevelExports)).toMatchInlineSnapshot(` - Array [ - "identifyUser", - "syncMessages", - "dispatchEvent", - "setConflictHandler", - "initializeInAppMessaging", - "onMessageReceived", - "onMessageDisplayed", - "onMessageDismissed", - "onMessageActionTaken", - "notifyMessageInteraction", - "clearMessages", - ] - `); + expect(Object.keys(inAppMessagingTopLevelExports).sort()).toEqual( + [ + 'identifyUser', + 'syncMessages', + 'dispatchEvent', + 'setConflictHandler', + 'initializeInAppMessaging', + 'onMessageReceived', + 'onMessageDismissed', + 'onMessageDisplayed', + 'onMessageActionTaken', + 'notifyMessageInteraction', + 'clearMessages', + ].sort() + ); }); it('should only export expected symbols from the Pinpoint provider', () => { - expect(Object.keys(inAppMessagingPinpointTopLevelExports)) - .toMatchInlineSnapshot(` - Array [ - "identifyUser", - "syncMessages", - "dispatchEvent", - "setConflictHandler", - "initializeInAppMessaging", - "onMessageReceived", - "onMessageDisplayed", - "onMessageDismissed", - "onMessageActionTaken", - "notifyMessageInteraction", - "clearMessages", - ] - `); + expect(Object.keys(inAppMessagingPinpointTopLevelExports).sort()).toEqual( + [ + 'identifyUser', + 'syncMessages', + 'dispatchEvent', + 'setConflictHandler', + 'initializeInAppMessaging', + 'onMessageReceived', + 'onMessageDismissed', + 'onMessageDisplayed', + 'onMessageActionTaken', + 'notifyMessageInteraction', + 'clearMessages', + ].sort() + ); }); }); describe('Auth exports', () => { it('should only export expected symbols from the top-level', () => { - expect(Object.keys(authTopLevelExports)).toMatchInlineSnapshot(` - Array [ - "signUp", - "resetPassword", - "confirmResetPassword", - "signIn", - "resendSignUpCode", - "confirmSignUp", - "confirmSignIn", - "updateMFAPreference", - "fetchMFAPreference", - "verifyTOTPSetup", - "updatePassword", - "setUpTOTP", - "updateUserAttributes", - "updateUserAttribute", - "getCurrentUser", - "confirmUserAttribute", - "signInWithRedirect", - "fetchUserAttributes", - "signOut", - "sendUserAttributeVerificationCode", - "deleteUserAttributes", - "deleteUser", - "rememberDevice", - "forgetDevice", - "fetchDevices", - "autoSignIn", - "AuthError", - "fetchAuthSession", - "decodeJWT", - ] - `); + expect(Object.keys(authTopLevelExports).sort()).toEqual( + [ + 'AuthError', + 'signUp', + 'resetPassword', + 'confirmResetPassword', + 'signIn', + 'resendSignUpCode', + 'confirmSignUp', + 'confirmSignIn', + 'updateMFAPreference', + 'fetchMFAPreference', + 'verifyTOTPSetup', + 'updatePassword', + 'setUpTOTP', + 'updateUserAttributes', + 'updateUserAttribute', + 'getCurrentUser', + 'confirmUserAttribute', + 'signInWithRedirect', + 'fetchUserAttributes', + 'signOut', + 'sendUserAttributeVerificationCode', + 'deleteUserAttributes', + 'deleteUser', + 'rememberDevice', + 'forgetDevice', + 'fetchDevices', + 'autoSignIn', + 'fetchAuthSession', + 'decodeJWT', + ].sort() + ); }); it('should only export expected symbols from the Cognito provider', () => { - expect(Object.keys(authCognitoExports)).toMatchInlineSnapshot(` - Array [ - "signUp", - "resetPassword", - "confirmResetPassword", - "signIn", - "resendSignUpCode", - "confirmSignUp", - "confirmSignIn", - "updateMFAPreference", - "fetchMFAPreference", - "verifyTOTPSetup", - "updatePassword", - "setUpTOTP", - "updateUserAttributes", - "updateUserAttribute", - "getCurrentUser", - "confirmUserAttribute", - "signInWithRedirect", - "fetchUserAttributes", - "signOut", - "sendUserAttributeVerificationCode", - "deleteUserAttributes", - "deleteUser", - "rememberDevice", - "forgetDevice", - "fetchDevices", - "autoSignIn", - "cognitoCredentialsProvider", - "CognitoAWSCredentialsAndIdentityIdProvider", - "DefaultIdentityIdStore", - "CognitoUserPoolsTokenProvider", - "TokenOrchestrator", - "DefaultTokenStore", - "refreshAuthTokens", - ] - `); + expect(Object.keys(authCognitoExports).sort()).toEqual( + [ + 'signUp', + 'resetPassword', + 'confirmResetPassword', + 'signIn', + 'resendSignUpCode', + 'confirmSignUp', + 'confirmSignIn', + 'updateMFAPreference', + 'fetchMFAPreference', + 'verifyTOTPSetup', + 'updatePassword', + 'setUpTOTP', + 'updateUserAttributes', + 'updateUserAttribute', + 'getCurrentUser', + 'confirmUserAttribute', + 'signInWithRedirect', + 'fetchUserAttributes', + 'signOut', + 'sendUserAttributeVerificationCode', + 'deleteUserAttributes', + 'deleteUser', + 'rememberDevice', + 'forgetDevice', + 'fetchDevices', + 'autoSignIn', + 'cognitoCredentialsProvider', + 'CognitoUserPoolsTokenProvider', + 'CognitoAWSCredentialsAndIdentityIdProvider', + 'DefaultIdentityIdStore', + 'TokenOrchestrator', + 'DefaultTokenStore', + 'refreshAuthTokens', + ].sort() + ); }); }); describe('Storage exports', () => { it('should only export expected symbols from the top-level', () => { - expect(Object.keys(storageTopLevelExports)).toMatchInlineSnapshot(` - Array [ - "uploadData", - "downloadData", - "remove", - "list", - "getProperties", - "copy", - "getUrl", - "isCancelError", - "StorageError", - ] - `); + expect(Object.keys(storageTopLevelExports).sort()).toEqual( + [ + 'uploadData', + 'downloadData', + 'remove', + 'list', + 'getProperties', + 'copy', + 'getUrl', + 'isCancelError', + 'StorageError', + ].sort() + ); }); it('should only export expected symbols from the S3 provider', () => { - expect(Object.keys(storageS3Exports)).toMatchInlineSnapshot(` - Array [ - "uploadData", - "downloadData", - "remove", - "list", - "getProperties", - "copy", - "getUrl", - ] - `); + expect(Object.keys(storageS3Exports).sort()).toEqual( + [ + 'uploadData', + 'downloadData', + 'remove', + 'list', + 'getProperties', + 'copy', + 'getUrl', + ].sort() + ); }); }); }); diff --git a/packages/aws-amplify/adapter-core/package.json b/packages/aws-amplify/adapter-core/package.json index ac0e6c503f6..2454c169688 100644 --- a/packages/aws-amplify/adapter-core/package.json +++ b/packages/aws-amplify/adapter-core/package.json @@ -1,8 +1,7 @@ { "name": "aws-amplify/adapter-core", - "types": "../lib-esm/adapterCore/index.d.ts", - "main": "../lib/adapterCore/index.js", - "module": "../lib-esm/adapterCore/index.js", - "react-native": "../lib-esm/adapterCore/index.js", + "types": "../dist/esm/adapterCore/index.d.ts", + "main": "../dist/cjs/adapterCore/index.js", + "module": "../dist/esm/adapterCore/index.mjs", "sideEffects": false } diff --git a/packages/aws-amplify/analytics/kinesis-firehose/package.json b/packages/aws-amplify/analytics/kinesis-firehose/package.json index 898110219f5..19cc7a27289 100644 --- a/packages/aws-amplify/analytics/kinesis-firehose/package.json +++ b/packages/aws-amplify/analytics/kinesis-firehose/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/analytics/kinesis-firehose", - "main": "../../lib/analytics/kinesis-firehose/index.js", - "browser": "../../lib-esm/analytics/kinesis-firehose/index.js", - "module": "../../lib-esm/analytics/kinesis-firehose/index.js", - "typings": "../../lib-esm/analytics/kinesis-firehose/index.d.ts" + "main": "../../dist/cjs/analytics/kinesis-firehose/index.js", + "react-native": "../../src/analytics/kinesis-firehose/index.ts", + "browser": "../../dist/esm/analytics/kinesis-firehose/index.mjs", + "module": "../../dist/esm/analytics/kinesis-firehose/index.mjs", + "typings": "../../dist/esm/analytics/kinesis-firehose/index.d.ts" } diff --git a/packages/aws-amplify/analytics/kinesis/package.json b/packages/aws-amplify/analytics/kinesis/package.json index c2ad6f363d6..9fa7a2ef371 100644 --- a/packages/aws-amplify/analytics/kinesis/package.json +++ b/packages/aws-amplify/analytics/kinesis/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/analytics/kinesis", - "main": "../../lib/analytics/kinesis/index.js", - "browser": "../../lib-esm/analytics/kinesis/index.js", - "module": "../../lib-esm/analytics/kinesis/index.js", - "typings": "../../lib-esm/analytics/kinesis/index.d.ts" + "main": "../../dist/cjs/analytics/kinesis/index.js", + "react-native": "../../src/analytics/kinesis/index.ts", + "browser": "../../dist/esm/analytics/kinesis/index.mjs", + "module": "../../dist/esm/analytics/kinesis/index.mjs", + "typings": "../../dist/esm/analytics/kinesis/index.d.ts" } diff --git a/packages/aws-amplify/analytics/package.json b/packages/aws-amplify/analytics/package.json index 106424a20bc..6a9899eae41 100644 --- a/packages/aws-amplify/analytics/package.json +++ b/packages/aws-amplify/analytics/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/analytics", - "main": "../lib/analytics/index.js", - "browser": "../lib-esm/analytics/index.js", - "module": "../lib-esm/analytics/index.js", - "typings": "../lib-esm/analytics/index.d.ts" + "main": "../dist/cjs/analytics/index.js", + "react-native": "../src/analytics/index.ts", + "browser": "../dist/esm/analytics/index.mjs", + "module": "../dist/esm/analytics/index.mjs", + "typings": "../dist/esm/analytics/index.d.ts" } diff --git a/packages/aws-amplify/analytics/personalize/package.json b/packages/aws-amplify/analytics/personalize/package.json index 8f692e56fb6..5d0bc2b9811 100644 --- a/packages/aws-amplify/analytics/personalize/package.json +++ b/packages/aws-amplify/analytics/personalize/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/analytics/personalize", - "main": "../../lib/analytics/personalize/index.js", - "browser": "../../lib-esm/analytics/personalize/index.js", - "module": "../../lib-esm/analytics/personalize/index.js", - "typings": "../../lib-esm/analytics/personalize/index.d.ts" + "main": "../../dist/cjs/analytics/personalize/index.js", + "react-native": "../../src/analytics/personalize/index.ts", + "browser": "../../dist/esm/analytics/personalize/index.mjs", + "module": "../../dist/esm/analytics/personalize/index.mjs", + "typings": "../../dist/esm/analytics/personalize/index.d.ts" } diff --git a/packages/aws-amplify/analytics/pinpoint/package.json b/packages/aws-amplify/analytics/pinpoint/package.json index 6e387747281..7b56fc2ab4f 100644 --- a/packages/aws-amplify/analytics/pinpoint/package.json +++ b/packages/aws-amplify/analytics/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/analytics/pinpoint", - "main": "../../lib/analytics/pinpoint/index.js", - "browser": "../../lib-esm/analytics/pinpoint/index.js", - "module": "../../lib-esm/analytics/pinpoint/index.js", - "typings": "../../lib-esm/analytics/pinpoint/index.d.ts" + "main": "../../dist/cjs/analytics/pinpoint/index.js", + "react-native": "../../src/analytics/pinpoint/index.ts", + "browser": "../../dist/esm/analytics/pinpoint/index.mjs", + "module": "../../dist/esm/analytics/pinpoint/index.mjs", + "typings": "../../dist/esm/analytics/pinpoint/index.d.ts" } diff --git a/packages/aws-amplify/api/package.json b/packages/aws-amplify/api/package.json index 0c463014b64..0834c28f3ba 100644 --- a/packages/aws-amplify/api/package.json +++ b/packages/aws-amplify/api/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/api", - "main": "../lib/api/index.js", - "browser": "../lib-esm/api/index.js", - "module": "../lib-esm/api/index.js", - "typings": "../lib-esm/api/index.d.ts" + "main": "../dist/cjs/api/index.js", + "react-native": "../src/api/index.ts", + "browser": "../dist/esm/api/index.mjs", + "module": "../dist/esm/api/index.mjs", + "typings": "../dist/esm/api/index.d.ts" } diff --git a/packages/aws-amplify/api/server/package.json b/packages/aws-amplify/api/server/package.json index 69b97ab3061..210bed8dd01 100644 --- a/packages/aws-amplify/api/server/package.json +++ b/packages/aws-amplify/api/server/package.json @@ -1,7 +1,7 @@ { "name": "aws-amplify/api/server", - "main": "../../lib/api/server.js", - "browser": "../../lib-esm/api/server.js", - "module": "../../lib-esm/api/server.js", - "typings": "../../lib-esm/api/server.d.ts" + "main": "../../dist/cjs/api/server.js", + "browser": "../../dist/esm/api/server.mjs", + "module": "../../dist/esm/api/server.mjs", + "typings": "../../dist/esm/api/server.d.ts" } diff --git a/packages/aws-amplify/auth/cognito/package.json b/packages/aws-amplify/auth/cognito/package.json index d260801552b..b56835a1543 100644 --- a/packages/aws-amplify/auth/cognito/package.json +++ b/packages/aws-amplify/auth/cognito/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/auth/cognito", - "main": "../../lib/auth/cognito/index.js", - "browser": "../../lib-esm/auth/cognito/index.js", - "module": "../../lib-esm/auth/cognito/index.js", - "typings": "../../lib-esm/auth/cognito/index.d.ts" + "main": "../../dist/cjs/auth/cognito/index.js", + "react-native": "../../src/auth/cognito/index.ts", + "browser": "../../dist/esm/auth/cognito/index.mjs", + "module": "../../dist/esm/auth/cognito/index.mjs", + "typings": "../../dist/esm/auth/cognito/index.d.ts" } diff --git a/packages/aws-amplify/auth/cognito/server/package.json b/packages/aws-amplify/auth/cognito/server/package.json index bf9f1becd56..23d21cdad80 100644 --- a/packages/aws-amplify/auth/cognito/server/package.json +++ b/packages/aws-amplify/auth/cognito/server/package.json @@ -1,7 +1,7 @@ { "name": "aws-amplify/auth/cognito/server", - "main": "../../../lib/auth/cognito/server/index.js", - "browser": "../../../lib-esm/auth/cognito/server/index.js", - "module": "../../../lib-esm/auth/cognito/server/index.js", - "typings": "../../../lib-esm/auth/cognito/server/index.d.ts" + "main": "../../../dist/cjs/auth/cognito/server/index.js", + "browser": "../../../dist/esm/auth/cognito/server/index.mjs", + "module": "../../../dist/esm/auth/cognito/server/index.mjs", + "typings": "../../../dist/esm/auth/cognito/server/index.d.ts" } diff --git a/packages/aws-amplify/auth/package.json b/packages/aws-amplify/auth/package.json index 6253f2a5396..c143fac98b1 100644 --- a/packages/aws-amplify/auth/package.json +++ b/packages/aws-amplify/auth/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/auth", - "main": "../lib/auth/index.js", - "browser": "../lib-esm/auth/index.js", - "module": "../lib-esm/auth/index.js", - "typings": "../lib-esm/auth/index.d.ts" + "main": "../dist/cjs/auth/index.js", + "react-native": "../src/auth/index.ts", + "browser": "../dist/esm/auth/index.mjs", + "module": "../dist/esm/auth/index.mjs", + "typings": "../dist/esm/auth/index.d.ts" } diff --git a/packages/aws-amplify/auth/server/package.json b/packages/aws-amplify/auth/server/package.json index 4680f2db3d7..e1a116ac1f6 100644 --- a/packages/aws-amplify/auth/server/package.json +++ b/packages/aws-amplify/auth/server/package.json @@ -1,7 +1,7 @@ { "name": "aws-amplify/auth/server", - "main": "../../lib/auth/server.js", - "browser": "../../lib-esm/auth/server.js", - "module": "../../lib-esm/auth/server.js", - "typings": "../../lib-esm/auth/server.d.ts" -} \ No newline at end of file + "main": "../../dist/cjs/auth/server.js", + "browser": "../../dist/esm/auth/server.mjs", + "module": "../../dist/esm/auth/server.mjs", + "typings": "../../dist/esm/auth/server.d.ts" +} diff --git a/packages/aws-amplify/datastore/package.json b/packages/aws-amplify/datastore/package.json index 77f448cf192..4c351f754d8 100644 --- a/packages/aws-amplify/datastore/package.json +++ b/packages/aws-amplify/datastore/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/datastore", - "main": "../lib/datastore/index.js", - "browser": "../lib-esm/datastore/index.js", - "module": "../lib-esm/datastore/index.js", - "typings": "../lib-esm/datastore/index.d.ts" + "main": "../dist/cjs/datastore/index.js", + "react-native": "../src/datastore/index.ts", + "browser": "../dist/esm/datastore/index.mjs", + "module": "../dist/esm/datastore/index.mjs", + "typings": "../dist/esm/datastore/index.d.ts" } diff --git a/packages/aws-amplify/in-app-messaging/package.json b/packages/aws-amplify/in-app-messaging/package.json index bf6161334fb..f74447a1f4c 100644 --- a/packages/aws-amplify/in-app-messaging/package.json +++ b/packages/aws-amplify/in-app-messaging/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/in-app-messaging", - "main": "../lib/in-app-messaging/index.js", - "browser": "../lib-esm/in-app-messaging/index.js", - "module": "../lib-esm/in-app-messaging/index.js", - "typings": "../lib-esm/in-app-messaging/index.d.ts" + "main": "../dist/cjs/in-app-messaging/index.js", + "react-native": "../src/in-app-messaging/index.ts", + "browser": "../dist/esm/in-app-messaging/index.mjs", + "module": "../dist/esm/in-app-messaging/index.mjs", + "typings": "../dist/esm/in-app-messaging/index.d.ts" } diff --git a/packages/aws-amplify/in-app-messaging/pinpoint/package.json b/packages/aws-amplify/in-app-messaging/pinpoint/package.json index e48699607cd..b4b3969fde6 100644 --- a/packages/aws-amplify/in-app-messaging/pinpoint/package.json +++ b/packages/aws-amplify/in-app-messaging/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/in-app-messaging/pinpoint", - "main": "../../lib/in-app-messaging/pinpoint/index.js", - "browser": "../../lib-esm/in-app-messaging/pinpoint/index.js", - "module": "../../lib-esm/in-app-messaging/pinpoint/index.js", - "typings": "../../lib-esm/in-app-messaging/pinpoint/index.d.ts" + "main": "../../dist/cjs/in-app-messaging/pinpoint/index.js", + "react-native": "../../src/in-app-messaging/pinpoint/index.ts", + "browser": "../../dist/esm/in-app-messaging/pinpoint/index.mjs", + "module": "../../dist/esm/in-app-messaging/pinpoint/index.mjs", + "typings": "../../dist/esm/in-app-messaging/pinpoint/index.d.ts" } diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index e9d1fe42a8f..23f059e5db4 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -2,192 +2,209 @@ "name": "aws-amplify", "version": "6.0.0", "description": "AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": "./lib-esm/index.js", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./utils": { - "types": "./lib-esm/utils/index.d.ts", - "import": "./lib-esm/utils/index.js", - "require": "./lib/utils/index.js" + "types": "./dist/esm/utils/index.d.ts", + "import": "./dist/esm/utils/index.mjs", + "require": "./dist/cjs/utils/index.js", + "react-native": "./src/utils/index.ts" }, "./auth": { - "types": "./lib-esm/auth/index.d.ts", - "import": "./lib-esm/auth/index.js", - "require": "./lib/auth/index.js" + "types": "./dist/esm/auth/index.d.ts", + "import": "./dist/esm/auth/index.mjs", + "require": "./dist/cjs/auth/index.js", + "react-native": "./src/auth/index.ts" }, "./api": { - "types": "./lib-esm/api/index.d.ts", - "import": "./lib-esm/api/index.js", - "require": "./lib/api/index.js" + "types": "./dist/esm/api/index.d.ts", + "import": "./dist/esm/api/index.mjs", + "require": "./dist/cjs/api/index.js", + "react-native": "./src/api/index.ts" }, "./api/server": { - "types": "./lib-esm/api/server.d.ts", - "import": "./lib-esm/api/server.js", - "require": "./lib/api/server.js" + "types": "./dist/esm/api/server.d.ts", + "import": "./dist/esm/api/server.mjs", + "require": "./dist/cjs/api/server.js" }, "./datastore": { - "types": "./lib-esm/datastore/index.d.ts", - "import": "./lib-esm/datastore/index.js", - "require": "./lib/datastore/index.js" + "types": "./dist/esm/datastore/index.d.ts", + "import": "./dist/esm/datastore/index.mjs", + "require": "./dist/cjs/datastore/index.js", + "react-native": "./src/datastore/index.ts" }, "./auth/cognito": { - "types": "./lib-esm/auth/cognito/index.d.ts", - "import": "./lib-esm/auth/cognito/index.js", - "require": "./lib/auth/cognito/index.js" + "types": "./dist/esm/auth/cognito/index.d.ts", + "import": "./dist/esm/auth/cognito/index.mjs", + "require": "./dist/cjs/auth/cognito/index.js", + "react-native": "./src/auth/cognito/index.ts" }, "./auth/cognito/server": { - "types": "./lib-esm/auth/cognito/server/index.d.ts", - "import": "./lib-esm/auth/cognito/server/index.js", - "require": "./lib/auth/cognito/server/index.js" + "types": "./dist/esm/auth/cognito/server/index.d.ts", + "import": "./dist/esm/auth/cognito/server/index.mjs", + "require": "./dist/cjs/auth/cognito/server/index.js" }, "./auth/server": { - "types": "./lib-esm/auth/server.d.ts", - "import": "./lib-esm/auth/server.js", - "require": "./lib/auth/server.js" + "types": "./dist/esm/auth/server.d.ts", + "import": "./dist/esm/auth/server.mjs", + "require": "./dist/cjs/auth/server.js" }, "./analytics": { - "types": "./lib-esm/analytics/index.d.ts", - "import": "./lib-esm/analytics/index.js", - "require": "./lib/analytics/index.js" + "types": "./dist/esm/analytics/index.d.ts", + "import": "./dist/esm/analytics/index.mjs", + "require": "./dist/cjs/analytics/index.js", + "react-native": "./src/analytics/index.ts" }, "./analytics/pinpoint": { - "types": "./lib-esm/analytics/pinpoint/index.d.ts", - "import": "./lib-esm/analytics/pinpoint/index.js", - "require": "./lib/analytics/pinpoint/index.js" + "types": "./dist/esm/analytics/pinpoint/index.d.ts", + "import": "./dist/esm/analytics/pinpoint/index.mjs", + "require": "./dist/cjs/analytics/pinpoint/index.js", + "react-native": "./src/analytics/pinpoint/index.ts" }, "./analytics/kinesis": { - "types": "./lib-esm/analytics/kinesis/index.d.ts", - "import": "./lib-esm/analytics/kinesis/index.js", - "require": "./lib/analytics/kinesis/index.js" + "types": "./dist/esm/analytics/kinesis/index.d.ts", + "import": "./dist/esm/analytics/kinesis/index.mjs", + "require": "./dist/cjs/analytics/kinesis/index.js", + "react-native": "./src/analytics/kinesis/index.ts" }, "./analytics/kinesis-firehose": { - "types": "./lib-esm/analytics/kinesis-firehose/index.d.ts", - "import": "./lib-esm/analytics/kinesis-firehose/index.js", - "require": "./lib/analytics/kinesis-firehose/index.js" + "types": "./dist/esm/analytics/kinesis-firehose/index.d.ts", + "import": "./dist/esm/analytics/kinesis-firehose/index.mjs", + "require": "./dist/cjs/analytics/kinesis-firehose/index.js", + "react-native": "./src/analytics/kinesis-firehose/index.ts" }, "./analytics/personalize": { - "types": "./lib-esm/analytics/personalize/index.d.ts", - "import": "./lib-esm/analytics/personalize/index.js", - "require": "./lib/analytics/personalize/index.js" + "types": "./dist/esm/analytics/personalize/index.d.ts", + "import": "./dist/esm/analytics/personalize/index.mjs", + "require": "./dist/cjs/analytics/personalize/index.js", + "react-native": "./src/analytics/personalize/index.ts" }, "./storage": { - "types": "./lib-esm/storage/index.d.ts", - "import": "./lib-esm/storage/index.js", - "require": "./lib/storage/index.js" + "types": "./dist/esm/storage/index.d.ts", + "import": "./dist/esm/storage/index.mjs", + "require": "./dist/cjs/storage/index.js", + "react-native": "./src/storage/index.ts" }, "./storage/s3": { - "types": "./lib-esm/storage/s3/index.d.ts", - "import": "./lib-esm/storage/s3/index.js", - "require": "./lib/storage/s3/index.js" + "types": "./dist/esm/storage/s3/index.d.ts", + "import": "./dist/esm/storage/s3/index.mjs", + "require": "./dist/cjs/storage/s3/index.js", + "react-native": "./src/storage/s3/index.ts" }, "./storage/server": { - "types": "./lib-esm/storage/server.d.ts", - "import": "./lib-esm/storage/server.js", - "require": "./lib/storage/server.js" + "types": "./dist/esm/storage/server.d.ts", + "import": "./dist/esm/storage/server.mjs", + "require": "./dist/cjs/storage/server.js" }, "./storage/s3/server": { - "types": "./lib-esm/storage/s3/server.d.ts", - "import": "./lib-esm/storage/s3/server.js", - "require": "./lib/storage/s3/server.js" + "types": "./dist/esm/storage/s3/server.d.ts", + "import": "./dist/esm/storage/s3/server.mjs", + "require": "./dist/cjs/storage/s3/server.js" }, "./in-app-messaging": { - "types": "./lib-esm/in-app-messaging/index.d.ts", - "import": "./lib-esm/in-app-messaging/index.js", - "require": "./lib/in-app-messaging/index.js" + "types": "./dist/esm/in-app-messaging/index.d.ts", + "import": "./dist/esm/in-app-messaging/index.mjs", + "require": "./dist/cjs/in-app-messaging/index.js", + "react-native": "./src/in-app-messaging/index.ts" }, "./push-notifications": { - "types": "./lib-esm/push-notifications/index.d.ts", - "import": "./lib-esm/push-notifications/index.js", - "require": "./lib/push-notifications/index.js" + "types": "./dist/esm/push-notifications/index.d.ts", + "import": "./dist/esm/push-notifications/index.mjs", + "require": "./dist/cjs/push-notifications/index.js", + "react-native": "./src/push-notifications/index.ts" }, "./in-app-messaging/pinpoint": { - "types": "./lib-esm/in-app-messaging/pinpoint/index.d.ts", - "import": "./lib-esm/in-app-messaging/pinpoint/index.js", - "require": "./lib/in-app-messaging/pinpoint/index.js" + "types": "./dist/esm/in-app-messaging/pinpoint/index.d.ts", + "import": "./dist/esm/in-app-messaging/pinpoint/index.mjs", + "require": "./dist/cjs/in-app-messaging/pinpoint/index.js", + "react-native": "./src/in-app-messaging/pinpoint/index.ts" }, "./push-notifications/pinpoint": { - "types": "./lib-esm/push-notifications/pinpoint/index.d.ts", - "import": "./lib-esm/push-notifications/pinpoint/index.js", - "require": "./lib/push-notifications/pinpoint/index.js" + "types": "./dist/esm/push-notifications/pinpoint/index.d.ts", + "import": "./dist/esm/push-notifications/pinpoint/index.mjs", + "require": "./dist/cjs/push-notifications/pinpoint/index.js", + "react-native": "./src/push-notifications/pinpoint/index.ts" }, "./adapter-core": { - "types": "./lib-esm/adapterCore/index.d.ts", - "import": "./lib-esm/adapterCore/index.js", - "require": "./lib/adapterCore/index.js" + "types": "./dist/esm/adapterCore/index.d.ts", + "import": "./dist/esm/adapterCore/index.mjs", + "require": "./dist/cjs/adapterCore/index.js" }, "./package.json": "./package.json" }, "typesVersions": { ">=4.2": { "api": [ - "./lib-esm/api/index.d.ts" + "./dist/esm/api/index.d.ts" ], "api/server": [ - "./lib-esm/api/server.d.ts" + "./dist/esm/api/server.d.ts" ], "utils": [ - "./lib-esm/utils/index.d.ts" + "./dist/esm/utils/index.d.ts" ], "auth": [ - "./lib-esm/auth/index.d.ts" + "./dist/esm/auth/index.d.ts" ], "auth/cognito": [ - "./lib-esm/auth/cognito/index.d.ts" + "./dist/esm/auth/cognito/index.d.ts" ], "auth/cognito/server": [ - "./lib-esm/auth/cognito/server/index.d.ts" + "./dist/esm/auth/cognito/server/index.d.ts" ], "auth/server": [ - "./lib-esm/auth/server.d.ts" + "./dist/esm/auth/server.d.ts" ], "analytics": [ - "./lib-esm/analytics/index.d.ts" + "./dist/esm/analytics/index.d.ts" ], "analytics/pinpoint": [ - "./lib-esm/analytics/pinpoint/index.d.ts" + "./dist/esm/analytics/pinpoint/index.d.ts" ], "analytics/kinesis": [ - "./lib-esm/analytics/kinesis/index.d.ts" + "./dist/esm/analytics/kinesis/index.d.ts" ], "analytics/kinesis-firehose": [ - "./lib-esm/analytics/kinesis-firehose/index.d.ts" + "./dist/esm/analytics/kinesis-firehose/index.d.ts" ], "analytics/personalize": [ - "./lib-esm/analytics/personalize/index.d.ts" + "./dist/esm/analytics/personalize/index.d.ts" ], "storage": [ - "./lib-esm/storage/index.d.ts" + "./dist/esm/storage/index.d.ts" ], "storage/s3": [ - "./lib-esm/storage/s3/index.d.ts" + "./dist/esm/storage/s3/index.d.ts" ], "storage/server": [ - "./lib-esm/storage/server.d.ts" + "./dist/esm/storage/server.d.ts" ], "storage/s3/server": [ - "./lib-esm/storage/s3/server.d.ts" + "./dist/esm/storage/s3/server.d.ts" ], "in-app-messaging": [ - "./lib-esm/in-app-messaging/index.d.ts" + "./dist/esm/in-app-messaging/index.d.ts" ], "in-app-messaging/pinpoint": [ - "./lib-esm/in-app-messaging/pinpoint/index.d.ts" + "./dist/esm/in-app-messaging/pinpoint/index.d.ts" ], "push-notifications": [ - "./lib-esm/push-notifications/index.d.ts" + "./dist/esm/push-notifications/index.d.ts" ], "push-notifications/pinpoint": [ - "./lib-esm/push-notifications/pinpoint/index.d.ts" + "./dist/esm/push-notifications/pinpoint/index.d.ts" ], "adapter-core": [ - "./lib-esm/adapterCore/index.d.ts" + "./dist/esm/adapterCore/index.d.ts" ] } }, @@ -196,11 +213,11 @@ "test": "npm run lint && jest -w 1 --coverage", "test:size": "size-limit", "build-with-test": "npm run clean && npm test && tsc && webpack -p", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m es6 --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m es6 --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m es6 --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -219,8 +236,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "analytics", "adapter-core", @@ -243,218 +260,220 @@ "tslib": "^2.5.0" }, "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "[Analytics] record (Pinpoint)", - "path": "./lib-esm/analytics/index.js", + "path": "./dist/esm/analytics/index.mjs", "import": "{ record }", - "limit": "16.0 kB" + "limit": "16.50 kB" }, { "name": "[Analytics] record (Kinesis)", - "path": "./lib-esm/analytics/kinesis/index.js", + "path": "./dist/esm/analytics/kinesis/index.mjs", "import": "{ record }", "limit": "44.05 kB" }, { "name": "[Analytics] record (Kinesis Firehose)", - "path": "./lib-esm/analytics/kinesis-firehose/index.js", + "path": "./dist/esm/analytics/kinesis-firehose/index.mjs", "import": "{ record }", "limit": "41.23 kB" }, { "name": "[Analytics] record (Personalize)", - "path": "./lib-esm/analytics/personalize/index.js", + "path": "./dist/esm/analytics/personalize/index.mjs", "import": "{ record }", "limit": "45.12 kB" }, { "name": "[Analytics] identifyUser (Pinpoint)", - "path": "./lib-esm/analytics/index.js", + "path": "./dist/esm/analytics/index.mjs", "import": "{ identifyUser }", - "limit": "14.51 kB" + "limit": "15.00 kB" }, { "name": "[Analytics] enable", - "path": "./lib-esm/analytics/index.js", + "path": "./dist/esm/analytics/index.mjs", "import": "{ enable }", "limit": "0.50 kB" }, { "name": "[Analytics] disable", - "path": "./lib-esm/analytics/index.js", + "path": "./dist/esm/analytics/index.mjs", "import": "{ disable }", "limit": "0.50 kB" }, { "name": "[API] generateClient (AppSync)", - "path": "./lib-esm/api/index.js", + "path": "./dist/esm/api/index.mjs", "import": "{ generateClient }", "limit": "32.49 kB" }, { "name": "[API] REST API handlers", - "path": "./lib-esm/api/index.js", + "path": "./dist/esm/api/index.mjs", "import": "{ get, post, put, del, patch, head, isCancelError }", "limit": "9.65 kB" }, { "name": "[Auth] signUp (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ signUp }", "limit": "26.51 kB" }, { "name": "[Auth] resetPassword (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ resetPassword }", "limit": "8.91 kB" }, { "name": "[Auth] confirmResetPassword (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ confirmResetPassword }", "limit": "8.86 kB" }, { "name": "[Auth] signIn (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ signIn }", "limit": "25.70 kB" }, { "name": "[Auth] resendSignUpCode (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ resendSignUpCode }", "limit": "8.9 kB" }, { "name": "[Auth] confirmSignUp (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ confirmSignUp }", "limit": "26.24 kB" }, { "name": "[Auth] confirmSignIn (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ confirmSignIn }", "limit": "25.55 kB" }, { "name": "[Auth] updateMFAPreference (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ updateMFAPreference }", "limit": "8.6 kB" }, { "name": "[Auth] fetchMFAPreference (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ fetchMFAPreference }", "limit": "8.18 kB" }, { "name": "[Auth] verifyTOTPSetup (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ verifyTOTPSetup }", "limit": "9.0 kB" }, { "name": "[Auth] updatePassword (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ updatePassword }", "limit": "9.01 kB" }, { "name": "[Auth] setUpTOTP (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ setUpTOTP }", "limit": "9.18 kB" }, { "name": "[Auth] updateUserAttributes (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ updateUserAttributes }", "limit": "8.27 kB" }, { "name": "[Auth] getCurrentUser (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ getCurrentUser }", "limit": "4.09 kB" }, { "name": "[Auth] confirmUserAttribute (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ confirmUserAttribute }", "limit": "8.99 kB" }, { "name": "[Auth] signInWithRedirect (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ signInWithRedirect }", "limit": "19.24 kB" }, { "name": "[Auth] fetchUserAttributes (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ fetchUserAttributes }", "limit": "8.09 kB" }, { "name": "[Auth] Basic Auth Flow (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ signIn, signOut, fetchAuthSession, confirmSignIn }", "limit": "27.40 kB" }, { "name": "[Auth] OAuth Auth Flow (Cognito)", - "path": "./lib-esm/auth/index.js", + "path": "./dist/esm/auth/index.mjs", "import": "{ signInWithRedirect, signOut, fetchAuthSession }", "limit": "19.61 kB" }, { "name": "[Storage] copy (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ copy }", "limit": "12.98 kB" }, { "name": "[Storage] downloadData (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ downloadData }", - "limit": "13.68 kB" + "limit": "13.76 kB" }, { "name": "[Storage] getProperties (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ getProperties }", - "limit": "12.95 kB" + "limit": "13.01 kB" }, { "name": "[Storage] getUrl (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ getUrl }", - "limit": "14.03 kB" + "limit": "14.09 kB" }, { "name": "[Storage] list (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ list }", "limit": "13.39 kB" }, { "name": "[Storage] remove (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ remove }", "limit": "12.82 kB" }, { "name": "[Storage] uploadData (S3)", - "path": "./lib-esm/storage/index.js", + "path": "./dist/esm/storage/index.mjs", "import": "{ uploadData }", - "limit": "17.99 kB" + "limit": "18.09 kB" } ], "jest": { @@ -479,6 +498,7 @@ "jsx" ], "testEnvironment": "jsdom", + "testPathIgnorePatterns": ["dual-publish-tmp"], "testURL": "http://localhost/", "coverageThreshold": { "global": { @@ -491,8 +511,7 @@ "coveragePathIgnorePatterns": [ "node_modules", "dist", - "lib", - "lib-esm" + "dual-publish-tmp" ] } } diff --git a/packages/aws-amplify/push-notifications/package.json b/packages/aws-amplify/push-notifications/package.json index 14dfb42dcab..9b863ccdd7e 100644 --- a/packages/aws-amplify/push-notifications/package.json +++ b/packages/aws-amplify/push-notifications/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/push-notifications", - "main": "../lib/push-notifications/index.js", - "browser": "../lib-esm/push-notifications/index.js", - "module": "../lib-esm/push-notifications/index.js", - "typings": "../lib-esm/push-notifications/index.d.ts" + "main": "../dist/cjs/push-notifications/index.js", + "react-native": "../src/push-notifications/index.ts", + "browser": "../dist/esm/push-notifications/index.mjs", + "module": "../dist/esm/push-notifications/index.mjs", + "typings": "../dist/esm/push-notifications/index.d.ts" } diff --git a/packages/aws-amplify/push-notifications/pinpoint/package.json b/packages/aws-amplify/push-notifications/pinpoint/package.json index b2a34785592..62091dffe08 100644 --- a/packages/aws-amplify/push-notifications/pinpoint/package.json +++ b/packages/aws-amplify/push-notifications/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/push-notifications/pinpoint", - "main": "../../lib/push-notifications/pinpoint/index.js", - "browser": "../../lib-esm/push-notifications/pinpoint/index.js", - "module": "../../lib-esm/push-notifications/pinpoint/index.js", - "typings": "../../lib-esm/push-notifications/pinpoint/index.d.ts" + "main": "../../dist/cjs/push-notifications/pinpoint/index.js", + "react-native": "../../src/push-notifications/pinpoint/index.ts", + "browser": "../../dist/esm/push-notifications/pinpoint/index.mjs", + "module": "../../dist/esm/push-notifications/pinpoint/index.mjs", + "typings": "../../dist/esm/push-notifications/pinpoint/index.d.ts" } diff --git a/packages/aws-amplify/rollup.config.mjs b/packages/aws-amplify/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/aws-amplify/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/aws-amplify/storage/package.json b/packages/aws-amplify/storage/package.json index 46b59271982..98503c8230a 100644 --- a/packages/aws-amplify/storage/package.json +++ b/packages/aws-amplify/storage/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/storage", - "main": "../lib/storage/index.js", - "browser": "../lib-esm/storage/index.js", - "module": "../lib-esm/storage/index.js", - "typings": "../lib-esm/storage/index.d.ts" + "main": "../dist/cjs/storage/index.js", + "react-native": "../src/storage/index.ts", + "browser": "../dist/esm/storage/index.mjs", + "module": "../dist/esm/storage/index.mjs", + "typings": "../dist/esm/storage/index.d.ts" } diff --git a/packages/aws-amplify/storage/s3/package.json b/packages/aws-amplify/storage/s3/package.json index 2447a24ce64..3255250c795 100644 --- a/packages/aws-amplify/storage/s3/package.json +++ b/packages/aws-amplify/storage/s3/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/storage/s3", - "main": "../../lib/storage/s3/index.js", - "browser": "../../lib-esm/storage/s3/index.js", - "module": "../../lib-esm/storage/s3/index.js", - "typings": "../../lib-esm/storage/s3/index.d.ts" + "main": "../../dist/cjs/storage/s3/index.js", + "react-native": "../../src/storage/s3/index.ts", + "browser": "../../dist/esm/storage/s3/index.mjs", + "module": "../../dist/esm/storage/s3/index.mjs", + "typings": "../../dist/esm/storage/s3/index.d.ts" } diff --git a/packages/aws-amplify/storage/s3/server/package.json b/packages/aws-amplify/storage/s3/server/package.json index 2e7e364ae58..f1084db2356 100644 --- a/packages/aws-amplify/storage/s3/server/package.json +++ b/packages/aws-amplify/storage/s3/server/package.json @@ -1,7 +1,7 @@ { "name": "aws-amplify/storage/s3/server", - "main": "../../../lib/storage/s3/server.js", - "browser": "../../../lib-esm/storage/s3/server.js", - "module": "../../../lib-esm/storage/s3/server.js", - "typings": "../../../lib-esm/storage/s3/server.d.ts" + "main": "../../../dist/cjs/storage/s3/server.js", + "browser": "../../../dist/esm/storage/s3/server.mjs", + "module": "../../../dist/esm/storage/s3/server.mjs", + "typings": "../../../dist/esm/storage/s3/server.d.ts" } diff --git a/packages/aws-amplify/storage/server/package.json b/packages/aws-amplify/storage/server/package.json index 1ff08116be9..d7fbd88abc3 100644 --- a/packages/aws-amplify/storage/server/package.json +++ b/packages/aws-amplify/storage/server/package.json @@ -1,7 +1,7 @@ { "name": "aws-amplify/storage/server", - "main": "../../lib/storage/server.js", - "browser": "../../lib-esm/storage/server.js", - "module": "../../lib-esm/storage/server.js", - "typings": "../../lib-esm/storage/server.d.ts" + "main": "../../dist/cjs/storage/server.js", + "browser": "../../dist/esm/storage/server.mjs", + "module": "../../dist/esm/storage/server.mjs", + "typings": "../../dist/esm/storage/server.d.ts" } diff --git a/packages/aws-amplify/utils/package.json b/packages/aws-amplify/utils/package.json index 05f75bf43e0..095d2da8a9f 100644 --- a/packages/aws-amplify/utils/package.json +++ b/packages/aws-amplify/utils/package.json @@ -1,7 +1,8 @@ { "name": "aws-amplify/utils", - "main": "../lib/utils/index.js", - "browser": "../lib-esm/utils/index.js", - "module": "../lib-esm/utils/index.js", - "typings": "../lib-esm/utils/index.d.ts" + "main": "../dist/cjs/utils/index.js", + "react-native": "../src/utils/index.ts", + "browser": "../dist/esm/utils/index.mjs", + "module": "../dist/esm/utils/index.mjs", + "typings": "../dist/esm/utils/index.d.ts" } diff --git a/packages/aws-amplify/webpack.config.dev.js b/packages/aws-amplify/webpack.config.dev.js index d221ea296e8..6ac1f868821 100644 --- a/packages/aws-amplify/webpack.config.dev.js +++ b/packages/aws-amplify/webpack.config.dev.js @@ -2,12 +2,12 @@ var config = require('./webpack.config.js'); var entry = { 'aws-amplify': [ - './lib-esm/index.js', - './lib-esm/utils/index.js', - './lib-esm/auth/index.js', - './lib-esm/auth/cognito/index.js', - './lib-esm/storage/index.js', - './lib-esm/storage/s3/index.js', + './dist/esm/index.mjs', + './dist/esm/utils/index.mjs', + './dist/esm/auth/index.mjs', + './dist/esm/auth/cognito/index.mjs', + './dist/esm/storage/index.mjs', + './dist/esm/storage/s3/index.mjs', ], }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/aws-amplify/webpack.config.js b/packages/aws-amplify/webpack.config.js index a3eff075fa5..6eae9dae3ab 100644 --- a/packages/aws-amplify/webpack.config.js +++ b/packages/aws-amplify/webpack.config.js @@ -1,17 +1,17 @@ module.exports = { entry: { 'aws-amplify.min': [ - './lib-esm/index.js', - './lib-esm/utils/index.js', - './lib-esm/auth/index.js', - './lib-esm/auth/cognito/index.js', - './lib-esm/storage/index.js', - './lib-esm/storage/s3/index.js', + './dist/esm/index.mjs', + './dist/esm/utils/index.mjs', + './dist/esm/auth/index.mjs', + './dist/esm/auth/cognito/index.mjs', + './dist/esm/storage/index.mjs', + './dist/esm/storage/s3/index.mjs', ], }, output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts index 083d2b9b1ef..dcfdaee1154 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts @@ -4,10 +4,8 @@ import { v4 } from 'uuid'; import { getClientInfo } from '../../../../src/utils/getClientInfo'; import { updateEndpoint as clientUpdateEndpoint } from '../../../../src/awsClients/pinpoint'; -import { - cacheEndpointId, - getEndpointId, -} from '../../../../src/providers/pinpoint/utils'; +import { cacheEndpointId } from '../../../../src/providers/pinpoint/utils/cacheEndpointId'; +import { getEndpointId } from '../../../../src/providers/pinpoint/utils/getEndpointId'; import { updateEndpoint } from '../../../../src/providers/pinpoint/apis'; import { appId, @@ -24,7 +22,8 @@ import { getExpectedInput } from './testUtils/getExpectedInput'; jest.mock('uuid'); jest.mock('../../../../src/awsClients/pinpoint'); -jest.mock('../../../../src/providers/pinpoint/utils'); +jest.mock('../../../../src/providers/pinpoint/utils/cacheEndpointId'); +jest.mock('../../../../src/providers/pinpoint/utils/getEndpointId'); jest.mock('../../../../src/utils/getClientInfo'); describe('Pinpoint Provider API: updateEndpoint', () => { diff --git a/packages/core/internals/adapter-core/package.json b/packages/core/internals/adapter-core/package.json index c9c39d09a1d..2f5f02afaf0 100644 --- a/packages/core/internals/adapter-core/package.json +++ b/packages/core/internals/adapter-core/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/core/internals/adapter-core", - "types": "../../lib-esm/adapterCore/index.d.ts", - "main": "../../lib/adapterCore/index.js", - "module": "../../lib-esm/adapterCore/index.js", - "react-native": "../../lib-esm/adapterCore/index.js", + "types": "../../dist/esm/adapterCore/index.d.ts", + "main": "../../dist/cjs/adapterCore/index.js", + "module": "../../dist/esm/adapterCore/index.mjs", "sideEffects": false } diff --git a/packages/core/internals/aws-client-utils/composers/package.json b/packages/core/internals/aws-client-utils/composers/package.json index d48d6d2a5ac..ce008304ba2 100644 --- a/packages/core/internals/aws-client-utils/composers/package.json +++ b/packages/core/internals/aws-client-utils/composers/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/core/internals/aws-client-utils/composers", - "types": "../../../lib-esm/clients/internal/index.d.ts", - "main": "../../../lib/clients/internal/index.js", - "module": "../../../lib-esm/clients/internal/index.js", - "react-native": "../../../lib-esm/clients/internal/index.js", + "types": "../../../dist/esm/clients/internal/index.d.ts", + "main": "../../../dist/cjs/clients/internal/index.js", + "module": "../../../dist/esm/clients/internal/index.mjs", + "react-native": "../../../src/clients/internal/index.ts", "sideEffects": false } diff --git a/packages/core/internals/aws-client-utils/package.json b/packages/core/internals/aws-client-utils/package.json index a174f93783e..107436a7e1b 100644 --- a/packages/core/internals/aws-client-utils/package.json +++ b/packages/core/internals/aws-client-utils/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/core/internals/aws-client-utils", - "types": "../../lib-esm/clients/index.d.ts", - "main": "../../lib/clients/index.js", - "module": "../../lib-esm/clients/index.js", - "react-native": "../../lib-esm/clients/index.js", + "types": "../../dist/esm/clients/index.d.ts", + "main": "../../dist/cjs/clients/index.js", + "module": "../../dist/esm/clients/index.mjs", + "react-native": "../../src/clients/index.ts", "sideEffects": false -} \ No newline at end of file +} diff --git a/packages/core/internals/aws-clients/cognitoIdentity/package.json b/packages/core/internals/aws-clients/cognitoIdentity/package.json index 221c2b67bb2..6067a3956d2 100644 --- a/packages/core/internals/aws-clients/cognitoIdentity/package.json +++ b/packages/core/internals/aws-clients/cognitoIdentity/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/core/internals/aws-clients/cognitoIdentity", - "types": "../../../lib-esm/awsClients/cognitoIdentity/index.d.ts", - "main": "../../../lib/awsClients/cognitoIdentity/index.js", - "module": "../../../lib-esm/awsClients/cognitoIdentity/index.js", - "react-native": "../../../lib-esm/awsClients/cognitoIdentity/index.js", + "types": "../../../dist/esm/awsClients/cognitoIdentity/index.d.ts", + "main": "../../../dist/cjs/awsClients/cognitoIdentity/index.js", + "module": "../../../dist/esm/awsClients/cognitoIdentity/index.mjs", + "react-native": "../../../src/awsClients/cognitoIdentity/index.ts", "sideEffects": false } diff --git a/packages/core/internals/aws-clients/pinpoint/package.json b/packages/core/internals/aws-clients/pinpoint/package.json index 321819a9c6d..0228eed0898 100644 --- a/packages/core/internals/aws-clients/pinpoint/package.json +++ b/packages/core/internals/aws-clients/pinpoint/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/core/internals/aws-clients/pinpoint", - "types": "../../../lib-esm/awsClients/pinpoint/index.d.ts", - "main": "../../../lib/awsClients/pinpoint/index.js", - "module": "../../../lib-esm/awsClients/pinpoint/index.js", - "react-native": "../../../lib-esm/awsClients/pinpoint/index.js", + "types": "../../../dist/esm/awsClients/pinpoint/index.d.ts", + "main": "../../../dist/cjs/awsClients/pinpoint/index.js", + "module": "../../../dist/esm/awsClients/pinpoint/index.mjs", + "react-native": "../../../src/awsClients/pinpoint/index.ts", "sideEffects": false -} \ No newline at end of file +} diff --git a/packages/core/internals/providers/pinpoint/package.json b/packages/core/internals/providers/pinpoint/package.json index 8968508f37a..9dbb81869e7 100644 --- a/packages/core/internals/providers/pinpoint/package.json +++ b/packages/core/internals/providers/pinpoint/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/core/internals/providers/pinpoint", - "types": "../../../lib-esm/providers/pinpoint/index.d.ts", - "main": "../../../lib/providers/pinpoint/index.js", - "module": "../../../lib-esm/providers/pinpoint/index.js", - "react-native": "../../../lib-esm/providers/pinpoint/index.js", + "types": "../../../dist/esm/providers/pinpoint/index.d.ts", + "main": "../../../dist/cjs/providers/pinpoint/index.js", + "module": "../../../dist/esm/providers/pinpoint/index.mjs", + "react-native": "../../../src/providers/pinpoint/index.ts", "sideEffects": false } diff --git a/packages/core/internals/utils/package.json b/packages/core/internals/utils/package.json index 97a667e2288..bcc0c2201dd 100644 --- a/packages/core/internals/utils/package.json +++ b/packages/core/internals/utils/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/core/internals/utils", - "types": "../../lib-esm/libraryUtils.d.ts", - "main": "../../lib/libraryUtils.js", - "module": "../../lib-esm/libraryUtils.js", - "react-native": "../../lib-esm/libraryUtils.js" + "types": "../../dist/esm/libraryUtils.d.ts", + "main": "../../dist/cjs/libraryUtils.js", + "module": "../../dist/esm/libraryUtils.mjs", + "react-native": "../../src/libraryUtils.ts" } diff --git a/packages/core/package.json b/packages/core/package.json index ac03fe0b106..4ae42c16766 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -2,40 +2,36 @@ "name": "@aws-amplify/core", "version": "6.0.0", "description": "Core category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "publishConfig": { "access": "public" }, "sideEffects": [ - "./lib/I18n/index.js", - "./lib/Credentials.js", - "./lib-esm/I18n/index.js", - "./lib-esm/Credentials.js", - "./lib/Cache/index.js", - "./lib-esm/Cache/index.js" + "./dist/cjs/I18n/index.js", + "./dist/cjs/Cache/index.js", + "./dist/esm/I18n/index.mjs", + "./dist/esm/Cache/index.mjs" ], "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:size": "size-limit", "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run generate-version && npm run build:esm && npm run build:cjs", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run generate-version && npm run build:esm-cjs && npm run build:umd", "generate-version": "genversion src/Platform/version.ts --es6 --semi --source ../aws-amplify", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "prepublishOnly": "npm run build", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 92.36" }, - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -47,73 +43,157 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", - "typings.d.ts", "internals", "server" ], "dependencies": { "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/types": "3.398.0", - "@types/uuid": "^9.0.0", "@smithy/util-hex-encoding": "2.0.0", + "@types/uuid": "^9.0.0", "js-cookie": "^3.0.5", + "rxjs": "^7.8.1", "tslib": "^2.5.0", - "uuid": "^9.0.0", - "rxjs": "^7.8.1" + "uuid": "^9.0.0" }, "devDependencies": { "@aws-amplify/react-native": "^1.0.0", + "@rollup/plugin-typescript": "11.1.5", "@types/js-cookie": "3.0.2", "genversion": "^2.2.0", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "Core (Hub)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Hub }", "limit": "1.43 kB" }, { "name": "Core (I18n)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ I18n }", "limit": "1.46 kB" }, { "name": "Custom clients (fetch handler)", - "path": "./lib-esm/clients/handlers/fetch.js", + "path": "./dist/esm/clients/handlers/fetch.mjs", "import": "{ fetchTransferHandler }", "limit": "500 B" }, { "name": "Custom clients (unauthenticated handler)", - "path": "./lib-esm/clients/handlers/unauthenticated.js", + "path": "./dist/esm/clients/handlers/unauthenticated.mjs", "import": "{ unauthenticatedHandler }", "limit": "1 kB" }, { "name": "Custom clients (request signer)", - "path": "./lib-esm/clients/middleware/signing/signer/signatureV4/index.js", + "path": "./dist/esm/clients/middleware/signing/signer/signatureV4/index.mjs", "import": "{ signRequest }", "limit": "3.53 kB" }, { "name": "Custom clients (url presigner)", - "path": "./lib-esm/clients/middleware/signing/signer/signatureV4/index.js", + "path": "./dist/esm/clients/middleware/signing/signer/signatureV4/index.mjs", "import": "{ presignUrl }", "limit": "3.58 kB" }, { "name": "Cache (default browser storage)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Cache }", "limit": "3.3 kB" } ], + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./server": { + "types": "./dist/esm/server.d.ts", + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.js" + }, + "./internals/adapter-core": { + "types": "./dist/esm/adapterCore/index.d.ts", + "import": "./dist/esm/adapterCore/index.mjs", + "require": "./dist/cjs/adapterCore/index.js" + }, + "./internals/aws-client-utils": { + "types": "./dist/esm/clients/index.d.ts", + "import": "./dist/esm/clients/index.mjs", + "require": "./dist/cjs/clients/index.js", + "react-native": "./src/clients/index.ts" + }, + "./internals/aws-client-utils/composers": { + "types": "./dist/esm/clients/internal/index.d.ts", + "import": "./dist/esm/clients/internal/index.mjs", + "require": "./dist/cjs/clients/internal/index.js", + "react-native": "./src/clients/internal/index.ts" + }, + "./internals/aws-clients/cognitoIdentity": { + "types": "./dist/esm/awsClients/cognitoIdentity/index.d.ts", + "import": "./dist/esm/awsClients/cognitoIdentity/index.mjs", + "require": "./dist/cjs/awsClients/cognitoIdentity/index.js", + "react-native": "./src/awsClients/cognitoIdentity/index.ts" + }, + "./internals/aws-clients/pinpoint": { + "types": "./dist/esm/awsClients/pinpoint/index.d.ts", + "import": "./dist/esm/awsClients/pinpoint/index.mjs", + "require": "./dist/cjs/awsClients/pinpoint/index.js", + "react-native": "./src/awsClients/pinpoint/index.ts" + }, + "./internals/providers/pinpoint": { + "types": "./dist/esm/providers/pinpoint/index.d.ts", + "import": "./dist/esm/providers/pinpoint/index.mjs", + "require": "./dist/cjs/providers/pinpoint/index.js", + "react-native": "./src/providers/pinpoint/index.ts" + }, + "./internals/utils": { + "types": "./dist/esm/libraryUtils.d.ts", + "import": "./dist/esm/libraryUtils.mjs", + "require": "./dist/cjs/libraryUtils.js", + "react-native": "./src/libraryUtils.ts" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + ">=4.2": { + "server": [ + "./dist/esm/server.d.ts" + ], + "internals/adapter-core": [ + "./dist/esm/adapterCore/index.d.ts" + ], + "internals/aws-client-utils": [ + "./dist/esm/clients/index.d.ts" + ], + "internals/aws-client-utils/composers": [ + "./dist/esm/clients/internal/index.d.ts" + ], + "internals/aws-clients/cognitoIdentity": [ + "./dist/esm/awsClients/cognitoIdentity/index.d.ts" + ], + "internals/aws-clients/pinpoint": [ + "./dist/esm/awsClients/pinpoint/index.d.ts" + ], + "internals/providers/pinpoint": [ + "./dist/esm/providers/pinpoint/index.d.ts" + ], + "internals/utils": [ + "./dist/esm/libraryUtils.d.ts" + ] + } + }, "jest": { "globals": { "ts-jest": { @@ -151,9 +231,7 @@ "testURL": "http://localhost/", "coveragePathIgnorePatterns": [ "/node_modules/", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/core/rollup.config.mjs b/packages/core/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/core/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/core/server/package.json b/packages/core/server/package.json index 05dfcd7f94d..b1c27e6f6f3 100644 --- a/packages/core/server/package.json +++ b/packages/core/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/core/server", - "types": "../lib-esm/server.d.ts", - "main": "../lib/server.js", - "module": "../lib-esm/server.js", - "react-native": "../lib-esm/server.js", + "types": "../dist/esm/server.d.ts", + "main": "../dist/cjs/server.js", + "module": "../dist/esm/server.mjs", "sideEffects": false } diff --git a/packages/core/src/Reachability/Reachability.ts b/packages/core/src/Reachability/Reachability.ts index 60e85b9e77d..db77ccadc6c 100644 --- a/packages/core/src/Reachability/Reachability.ts +++ b/packages/core/src/Reachability/Reachability.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { CompletionObserver, Observable, from } from 'rxjs'; -import { isWebWorker } from '../libraryUtils'; import { NetworkStatus } from './types'; +import { isWebWorker } from '../utils'; export class Reachability { private static _observers: Array> = []; diff --git a/packages/core/src/providers/pinpoint/apis/updateEndpoint.ts b/packages/core/src/providers/pinpoint/apis/updateEndpoint.ts index 044fbd76ebf..e74c5537c2a 100644 --- a/packages/core/src/providers/pinpoint/apis/updateEndpoint.ts +++ b/packages/core/src/providers/pinpoint/apis/updateEndpoint.ts @@ -8,7 +8,8 @@ import { UpdateEndpointInput, } from '../../../awsClients/pinpoint'; import { PinpointUpdateEndpointInput } from '../types'; -import { cacheEndpointId, getEndpointId } from '../utils'; +import { cacheEndpointId } from '../utils/cacheEndpointId'; +import { getEndpointId } from '../utils/getEndpointId'; /** * @internal diff --git a/packages/core/src/providers/pinpoint/utils/cacheEndpointId.ts b/packages/core/src/providers/pinpoint/utils/cacheEndpointId.ts index 001c2e9bc6c..d34ac4c796a 100644 --- a/packages/core/src/providers/pinpoint/utils/cacheEndpointId.ts +++ b/packages/core/src/providers/pinpoint/utils/cacheEndpointId.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Cache } from '../../..'; +import { Cache } from '../../../Cache'; import { SupportedCategory } from '../types'; import { getCacheKey } from './getCacheKey'; diff --git a/packages/core/src/providers/pinpoint/utils/getEndpointId.ts b/packages/core/src/providers/pinpoint/utils/getEndpointId.ts index 8c1a13f2a00..a8b6492d4bd 100644 --- a/packages/core/src/providers/pinpoint/utils/getEndpointId.ts +++ b/packages/core/src/providers/pinpoint/utils/getEndpointId.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Cache } from '../../..'; +import { Cache } from '../../../Cache'; import { SupportedCategory } from '../types'; import { getCacheKey } from './getCacheKey'; diff --git a/packages/core/src/providers/pinpoint/utils/resolveEndpointId.ts b/packages/core/src/providers/pinpoint/utils/resolveEndpointId.ts index ee0bb884a35..6cf3ccdc1ce 100644 --- a/packages/core/src/providers/pinpoint/utils/resolveEndpointId.ts +++ b/packages/core/src/providers/pinpoint/utils/resolveEndpointId.ts @@ -3,7 +3,7 @@ import { assert } from '../../../errors'; import { AmplifyErrorCode } from '../../../types'; -import { updateEndpoint } from '../apis'; +import { updateEndpoint } from '../apis/updateEndpoint'; import { PinpointUpdateEndpointInput } from '../types'; import { getEndpointId } from './getEndpointId'; diff --git a/packages/core/src/utils/amplifyUrl/polyfill.native.ts b/packages/core/src/utils/amplifyUrl/index.native.ts similarity index 61% rename from packages/core/src/utils/amplifyUrl/polyfill.native.ts rename to packages/core/src/utils/amplifyUrl/index.native.ts index 4e06280116a..0cf76721a99 100644 --- a/packages/core/src/utils/amplifyUrl/polyfill.native.ts +++ b/packages/core/src/utils/amplifyUrl/index.native.ts @@ -4,3 +4,8 @@ import { loadUrlPolyfill } from '@aws-amplify/react-native'; loadUrlPolyfill(); + +const AmplifyUrl = URL; +const AmplifyUrlSearchParams = URLSearchParams; + +export { AmplifyUrl, AmplifyUrlSearchParams }; diff --git a/packages/core/src/utils/amplifyUrl/index.ts b/packages/core/src/utils/amplifyUrl/index.ts index 3de929beee5..eacaa421cf7 100644 --- a/packages/core/src/utils/amplifyUrl/index.ts +++ b/packages/core/src/utils/amplifyUrl/index.ts @@ -1,8 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import './polyfill'; - const AmplifyUrl = URL; const AmplifyUrlSearchParams = URLSearchParams; diff --git a/packages/core/src/utils/amplifyUrl/polyfill.ts b/packages/core/src/utils/amplifyUrl/polyfill.ts deleted file mode 100644 index f0daa8d350d..00000000000 --- a/packages/core/src/utils/amplifyUrl/polyfill.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// noop - polyfills not required on platform diff --git a/packages/core/src/utils/amplifyUuid/polyfill.native.ts b/packages/core/src/utils/amplifyUuid/index.native.ts similarity index 68% rename from packages/core/src/utils/amplifyUuid/polyfill.native.ts rename to packages/core/src/utils/amplifyUuid/index.native.ts index 82f9ccf7dc3..1ca4b5b2a01 100644 --- a/packages/core/src/utils/amplifyUuid/polyfill.native.ts +++ b/packages/core/src/utils/amplifyUuid/index.native.ts @@ -1,6 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 - import { loadGetRandomValues } from '@aws-amplify/react-native'; +import { v4 } from 'uuid'; loadGetRandomValues(); + +const amplifyUuid: () => string = v4; + +export { amplifyUuid }; diff --git a/packages/core/src/utils/amplifyUuid/index.ts b/packages/core/src/utils/amplifyUuid/index.ts index 7789b6245bd..d318b9cbc37 100644 --- a/packages/core/src/utils/amplifyUuid/index.ts +++ b/packages/core/src/utils/amplifyUuid/index.ts @@ -1,7 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import './polyfill'; import { v4 } from 'uuid'; const amplifyUuid: () => string = v4; diff --git a/packages/core/src/utils/amplifyUuid/polyfill.ts b/packages/core/src/utils/amplifyUuid/polyfill.ts deleted file mode 100644 index f0daa8d350d..00000000000 --- a/packages/core/src/utils/amplifyUuid/polyfill.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// noop - polyfills not required on platform diff --git a/packages/core/webpack.config.dev.js b/packages/core/webpack.config.dev.js index cf6d3b2c8ad..23a0efad256 100644 --- a/packages/core/webpack.config.dev.js +++ b/packages/core/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-core': './lib-esm/index.js', + 'aws-amplify-core': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/core/webpack.config.js b/packages/core/webpack.config.js index a653fc02845..077a52e5a0e 100644 --- a/packages/core/webpack.config.js +++ b/packages/core/webpack.config.js @@ -1,11 +1,11 @@ module.exports = { entry: { - 'aws-amplify-core.min': './lib-esm/index.js', + 'aws-amplify-core.min': './dist/esm/index.mjs', }, externals: ['aws-sdk/global'], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_core', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts b/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts index f9431b35808..5daf5775d80 100644 --- a/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts +++ b/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts @@ -14,7 +14,7 @@ import { testSchema, InnerSQLiteDatabase, } from './helpers'; -import { SyncEngine } from '@aws-amplify/datastore/lib-esm/sync'; +import { SyncEngine } from '@aws-amplify/datastore/dist/esm/sync'; import { Observable } from 'rxjs'; import { pause, diff --git a/packages/datastore-storage-adapter/package.json b/packages/datastore-storage-adapter/package.json index 015cf28411b..8428795dbcd 100644 --- a/packages/datastore-storage-adapter/package.json +++ b/packages/datastore-storage-adapter/package.json @@ -2,27 +2,25 @@ "name": "@aws-amplify/datastore-storage-adapter", "version": "2.1.0", "description": "SQLite storage adapter for Amplify DataStore ", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "publishConfig": { "access": "public" }, "scripts": { "test": "npm run lint && jest -w 1 --coverage", "build-with-test": "npm test && npm run build", - "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "node ./build es6", - "build:cjs:watch": "node ./build es5 --watch", - "build:esm:watch": "rimraf lib-esm && node ./build es6 --watch", - "build": "yarn clean && yarn build:esm && npm run build:cjs", - "clean": "rimraf lib-esm lib dist", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "rimraf dist lib lib-esm", "format": "echo \"Not implemented\"", "lint": "tslint '{__tests__,src}/**/*.ts' && npm run ts-coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 94.16" + "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 94.16" }, "repository": { "type": "git", @@ -41,10 +39,13 @@ "@aws-amplify/core": "6.0.0", "@aws-amplify/datastore": "5.0.0", "@types/react-native-sqlite-storage": "5.0.1", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "expo-file-system": "13.1.4", "expo-sqlite": "10.1.0", "react-native-sqlite-storage": "5.0.0", - "sqlite3": "^5.0.2" + "sqlite3": "^5.0.2", + "typescript": "5.0.2" }, "jest": { "globals": { @@ -93,8 +94,6 @@ "coveragePathIgnorePatterns": [ "/node_modules/", "dist", - "lib", - "lib-esm", "../datastore" ], "setupFilesAfterEnv": [ diff --git a/packages/datastore-storage-adapter/rollup.config.mjs b/packages/datastore-storage-adapter/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/datastore-storage-adapter/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/datastore-storage-adapter/tsconfig.build.json b/packages/datastore-storage-adapter/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/datastore-storage-adapter/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/datastore-storage-adapter/tsconfig.json b/packages/datastore-storage-adapter/tsconfig.json index 6e7a815e15f..de8a2d6ebd7 100755 --- a/packages/datastore-storage-adapter/tsconfig.json +++ b/packages/datastore-storage-adapter/tsconfig.json @@ -1,7 +1,6 @@ //WARNING: If you are manually specifying files to compile then the tsconfig.json is completely ignored, you must use command line flags { "compilerOptions": { - "outDir": "./lib/", "target": "es2020", "noImplicitAny": false, "downlevelIteration": true, @@ -16,7 +15,6 @@ "es2020.promise" ], "sourceMap": true, - "module": "commonjs", "moduleResolution": "node", "allowJs": false, "declaration": true, diff --git a/packages/datastore-storage-adapter/webpack.config.dev.js b/packages/datastore-storage-adapter/webpack.config.dev.js index 768369c8530..721e8b987c6 100644 --- a/packages/datastore-storage-adapter/webpack.config.dev.js +++ b/packages/datastore-storage-adapter/webpack.config.dev.js @@ -1,8 +1,8 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-datastore-storage-adapter': './lib-esm/index.js', + 'aws-amplify-datastore-storage-adapter': './dist/esm/index.mjs', 'aws-amplify-datastore-sqlite-adapter-expo': - './lib-esm/ExpoSQLiteAdapter/ExpoSQLiteAdapter.js', + './dist/esm/ExpoSQLiteAdapter/ExpoSQLiteAdapter.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/datastore-storage-adapter/webpack.config.js b/packages/datastore-storage-adapter/webpack.config.js index 37b331d5b05..38aef820dee 100644 --- a/packages/datastore-storage-adapter/webpack.config.js +++ b/packages/datastore-storage-adapter/webpack.config.js @@ -1,8 +1,8 @@ module.exports = { entry: { - 'aws-amplify-datastore-storage-adapter.min': './lib-esm/index.js', + 'aws-amplify-datastore-storage-adapter.min': './dist/esm/index.mjs', 'aws-amplify-datastore-sqlite-adapter-expo.min': - './lib-esm/ExpoSQLiteAdapter/ExpoSQLiteAdapter.js', + './dist/esm/ExpoSQLiteAdapter/ExpoSQLiteAdapter.mjs', }, externals: [ '@aws-amplify/datastore', @@ -13,7 +13,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws-amplify-datastore-storage-adapter', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/datastore/build.js b/packages/datastore/build.js deleted file mode 100644 index 5bdcce15dc5..00000000000 --- a/packages/datastore/build.js +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -'use strict'; - -const build = require('../../scripts/build'); - -build(process.argv[2], process.argv[3]); diff --git a/packages/datastore/package.json b/packages/datastore/package.json index 4b7aba9ef09..d7569422e4e 100644 --- a/packages/datastore/package.json +++ b/packages/datastore/package.json @@ -2,33 +2,31 @@ "name": "@aws-amplify/datastore", "version": "5.0.0", "description": "AppSyncLocal support for aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "publishConfig": { "access": "public" }, "sideEffects": [ - "./lib/datastore/datastore.js", - "./lib-esm/datastore/datastore.js" + "./dist/cjs/datastore/datastore.js", + "./dist/esm/datastore/datastore.mjs" ], "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:size": "size-limit", "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "yarn clean && yarn build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\" && npm run ts-coverage", "lint": "tslint '{__tests__,src}/**/*.ts' && npm run ts-coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 92.05" + "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 92.05" }, "repository": { "type": "git", @@ -41,10 +39,9 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", - "src", - "ssr" + "dist/cjs", + "dist/esm", + "src" ], "dependencies": { "@aws-amplify/api": "6.0.0", @@ -62,6 +59,8 @@ "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", "@types/uuid-validate": "^0.0.1", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "dexie": "3.2.2", "dexie-export-import": "1.0.3", "fake-indexeddb": "3.0.0", @@ -71,7 +70,7 @@ "size-limit": [ { "name": "DataStore (top-level class)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Amplify, DataStore }", "limit": "65.25 kB" } @@ -125,9 +124,7 @@ }, "coveragePathIgnorePatterns": [ "/node_modules/", - "dist", - "lib", - "lib-esm" + "dist" ], "setupFilesAfterEnv": [ "/jest.setup.js" diff --git a/packages/datastore/rollup.config.mjs b/packages/datastore/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/datastore/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/datastore/src/ssr/index.ts b/packages/datastore/src/ssr/index.ts deleted file mode 100644 index bef554c3991..00000000000 --- a/packages/datastore/src/ssr/index.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -import { - PersistentModel, - PersistentModelConstructor, -} from '@aws-amplify/datastore'; - -// Helper for converting JSON back into DataStore models (while respecting IDs) -export function deserializeModel( - Model: PersistentModelConstructor, - init: T | T[] -) { - if (Array.isArray(init)) { - return init.map(init => deserializeModel(Model, init)); - } - - // `fromJSON` is intentionally hidden from types as a "private" method (though it exists on the instance) - // @ts-ignore Property 'fromJSON' does not exist on type 'PersistentModelConstructor'.ts(2339) - return Model.fromJSON(init); -} - -// Helper for converting DataStore models to JSON -export function serializeModel( - model: T | T[] -): JSON { - return JSON.parse(JSON.stringify(model)); -} diff --git a/packages/datastore/ssr/package.json b/packages/datastore/ssr/package.json deleted file mode 100644 index a8b1d454e94..00000000000 --- a/packages/datastore/ssr/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "main": "../lib/ssr/index.js", - "module": "../lib-esm/ssr/index.js", - "typings": "../lib-esm/ssr/index.d.ts", - "react-native": { - "../lib/ssr/index": "../lib-esm/ssr/index.js" - } -} diff --git a/packages/datastore/tsconfig.build.json b/packages/datastore/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/datastore/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/datastore/webpack.config.dev.js b/packages/datastore/webpack.config.dev.js index 5cea6eba60a..421b4bf2b23 100644 --- a/packages/datastore/webpack.config.dev.js +++ b/packages/datastore/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-datastore': './lib-esm/index.js', + 'aws-amplify-datastore': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/datastore/webpack.config.js b/packages/datastore/webpack.config.js index d1be6073387..739e81c6b00 100644 --- a/packages/datastore/webpack.config.js +++ b/packages/datastore/webpack.config.js @@ -1,11 +1,11 @@ module.exports = { entry: { - 'aws-amplify-datastore.min': './lib-esm/index.js', + 'aws-amplify-datastore.min': './dist/esm/index.mjs', }, externals: [{ '@aws-amplify/pubsub': 'aws_amplify_pubsub' }], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_datastore', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/geo/location-service/package.json b/packages/geo/location-service/package.json index aa04d0f9b6a..3a1485804e6 100644 --- a/packages/geo/location-service/package.json +++ b/packages/geo/location-service/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/geo/location-service", - "main": "../lib/providers/location-service/AmazonLocationServiceProvider.js", - "browser": "../lib-esm/providers/location-service/AmazonLocationServiceProvider.js", - "module": "../lib-esm/providers/location-service/AmazonLocationServiceProvider.js", - "typings": "../lib-esm/providers/location-service/AmazonLocationServiceProvider.d.ts" + "main": "../dist/cjs/providers/location-service/AmazonLocationServiceProvider.js", + "browser": "../dist/esm/providers/location-service/AmazonLocationServiceProvider.mjs", + "module": "../dist/esm/providers/location-service/AmazonLocationServiceProvider.mjs", + "react-native": "../src/providers/location-service/AmazonLocationServiceProvider.ts", + "typings": "../dist/esm/providers/location-service/AmazonLocationServiceProvider.d.ts" } diff --git a/packages/geo/package.json b/packages/geo/package.json index a36f4b9cf27..cf27cb9f709 100644 --- a/packages/geo/package.json +++ b/packages/geo/package.json @@ -2,38 +2,51 @@ "name": "@aws-amplify/geo", "version": "3.0.0", "description": "Geo category for aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "publishConfig": { "access": "public" }, "sideEffects": [ - "./lib/geo/geo.js", - "./lib-esm/geo/geo.js" + "./dist/cjs/geo/geo.js", + "./dist/esm/geo/geo.mjs" ], "scripts": { "test": "yarn run lint && jest -w 1 --coverage", "test:size": "size-limit", - "build-with-test": "yarn test && yarn run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "yarn clean && yarn build:esm && yarn run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm test && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint '{__tests__,src}/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 84.00" }, + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./location-service": { + "types": "./dist/esm/providers/location-service/AmazonLocationServiceProvider.d.ts", + "import": "./dist/esm/providers/location-service/AmazonLocationServiceProvider.mjs", + "require": "./dist/cjs/providers/location-service/AmazonLocationServiceProvider.js", + "react-native": "./src/providers/location-service/AmazonLocationServiceProvider.ts" + }, + "./package.json": "./package.json" + }, "typesVersions": { ">=4.2": { - "pinpoint": [ - "./lib-esm/providers/pinpoint/AmazonLocationServiceProvider.d.ts" + "location-service": [ + "./dist/esm/providers/location-service/AmazonLocationServiceProvider.d.ts" ] } }, @@ -48,8 +61,9 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", + "location-service", "src" ], "dependencies": { @@ -63,12 +77,14 @@ }, "devDependencies": { "@aws-amplify/core": "6.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "Geo (top-level class)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ Amplify, Geo }", "limit": "43.9 kB" } @@ -122,9 +138,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/geo/rollup.config.mjs b/packages/geo/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/geo/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/geo/webpack.config.dev.js b/packages/geo/webpack.config.dev.js index 42968552e77..08501c32731 100644 --- a/packages/geo/webpack.config.dev.js +++ b/packages/geo/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-geo': './lib-esm/index.js', + 'aws-amplify-geo': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/geo/webpack.config.js b/packages/geo/webpack.config.js index fa129d52894..845818f29fb 100644 --- a/packages/geo/webpack.config.js +++ b/packages/geo/webpack.config.js @@ -1,11 +1,11 @@ module.exports = { entry: { - 'aws-amplify-geo.min': './lib-esm/index.js', + 'aws-amplify-geo.min': './dist/esm/index.mjs', }, externals: ['react-native', { '@aws-amplify/core': 'aws_amplify_core' }], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_geo', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/interactions/lex-v1/package.json b/packages/interactions/lex-v1/package.json index aa1807be6ac..15f7856c6e5 100644 --- a/packages/interactions/lex-v1/package.json +++ b/packages/interactions/lex-v1/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/interactions/lex-v1", - "main": "../lib/lex-v1/index.js", - "browser": "../lib-esm/lex-v1/index.js", - "module": "../lib-esm/lex-v1/index.js", - "typings": "../lib-esm/lex-v1/index.d.ts" + "main": "../dist/cjs/lex-v1/index.js", + "browser": "../dist/esm/lex-v1/index.mjs", + "module": "../dist/esm/lex-v1/index.mjs", + "react-native": "../src/lex-v1/index.ts", + "typings": "../dist/esm/lex-v1/index.d.ts" } diff --git a/packages/interactions/lex-v2/package.json b/packages/interactions/lex-v2/package.json index 8aada79f295..30786d2b2b1 100644 --- a/packages/interactions/lex-v2/package.json +++ b/packages/interactions/lex-v2/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/interactions/lex-v2", - "main": "../lib/lex-v2/index.js", - "browser": "../lib-esm/lex-v2/index.js", - "module": "../lib-esm/lex-v2/index.js", - "typings": "../lib-esm/lex-v2/index.d.ts" + "main": "../dist/cjs/lex-v2/index.js", + "browser": "../dist/esm/lex-v2/index.mjs", + "module": "../dist/esm/lex-v2/index.mjs", + "react-native": "../src/lex-v2/index.ts", + "typings": "../dist/esm/lex-v2/index.d.ts" } diff --git a/packages/interactions/package.json b/packages/interactions/package.json index 4a878b3e540..a222d63c844 100644 --- a/packages/interactions/package.json +++ b/packages/interactions/package.json @@ -2,12 +2,10 @@ "name": "@aws-amplify/interactions", "version": "6.0.0", "description": "Interactions category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -15,13 +13,13 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:size": "size-limit", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm run clean && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -30,28 +28,30 @@ "typesVersions": { ">=4.2": { "lex-v1": [ - "./lib-esm/lex-v1/index.d.ts" + "./dist/esm/lex-v1/index.d.ts" ], "lex-v2": [ - "./lib-esm/lex-v2/index.d.ts" + "./dist/esm/lex-v2/index.d.ts" ] } }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js" }, "./lex-v1": { - "types": "./lib-esm/lex-v1/index.d.ts", - "import": "./lib-esm/lex-v1/index.js", - "require": "./lib/lex-v1/index.js" + "types": "./dist/esm/lex-v1/index.d.ts", + "import": "./dist/esm/lex-v1/index.mjs", + "require": "./dist/cjs/lex-v1/index.js", + "react-native": "./src/lex-v1/index.ts" }, "./lex-v2": { - "types": "./lib-esm/lex-v2/index.d.ts", - "import": "./lib-esm/lex-v2/index.js", - "require": "./lib/lex-v2/index.js" + "types": "./dist/esm/lex-v2/index.d.ts", + "import": "./dist/esm/lex-v2/index.mjs", + "require": "./dist/cjs/lex-v2/index.js", + "react-native": "./src/lex-v2/index.ts" } }, "repository": { @@ -65,8 +65,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "lex-v1", "lex-v2" @@ -82,25 +82,27 @@ }, "devDependencies": { "@aws-amplify/core": "6.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "^5.0.2" }, "size-limit": [ { "name": "Interactions (default to Lex v2)", - "path": "./lib-esm/index.js", - "import": "{ Amplify, Interactions }", + "path": "./dist/esm/index.mjs", + "import": "{ Interactions }", "limit": "52.00 kB" }, { "name": "Interactions (Lex v2)", - "path": "./lib-esm/lex-v2/index.js", - "import": "{ Amplify, Interactions }", + "path": "./dist/esm/lex-v2/index.mjs", + "import": "{ Interactions }", "limit": "52.00 kB" }, { "name": "Interactions (Lex v1)", - "path": "./lib-esm/lex-v1/index.js", - "import": "{ Amplify, Interactions }", + "path": "./dist/esm/lex-v1/index.mjs", + "import": "{ Interactions }", "limit": "47.00 kB" } ], @@ -140,9 +142,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/interactions/rollup.config.mjs b/packages/interactions/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/interactions/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/interactions/webpack.config.dev.js b/packages/interactions/webpack.config.dev.js index bf79bc71240..71606475c2c 100644 --- a/packages/interactions/webpack.config.dev.js +++ b/packages/interactions/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-interactions': './lib-esm/index.js', + 'aws-amplify-interactions': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/interactions/webpack.config.js b/packages/interactions/webpack.config.js index ab4b8567bc4..0623fe0c90a 100644 --- a/packages/interactions/webpack.config.js +++ b/packages/interactions/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-interactions.min': './lib-esm/index.js', + 'aws-amplify-interactions.min': './dist/esm/index.mjs', }, externals: [ 'aws-sdk/clients/lexruntime', @@ -8,7 +8,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_interactions', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts index 21913d6c78e..a16c0dd6323 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts @@ -16,7 +16,6 @@ import { InAppMessagingError } from '../../../../../src/inAppMessaging/errors'; import { notifyEventListeners } from '../../../../../src/eventListeners'; jest.mock('@aws-amplify/core'); -jest.mock('@aws-amplify/core/internals/utils'); jest.mock('../../../../../src/inAppMessaging/providers/pinpoint/utils'); jest.mock('../../../../../src/eventListeners'); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts index 405b34d0485..37bc2c90f72 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts @@ -22,7 +22,6 @@ import { InAppMessagingError } from '../../../../../src/inAppMessaging/errors'; jest.mock('@aws-amplify/core/internals/aws-clients/pinpoint'); jest.mock('@aws-amplify/core'); -jest.mock('@aws-amplify/core/internals/utils'); jest.mock('@aws-amplify/core/internals/providers/pinpoint'); jest.mock('../../../../../src/inAppMessaging/providers/pinpoint/utils'); diff --git a/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts b/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts index e915cfe5f4e..bd392f0d356 100644 --- a/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts +++ b/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts @@ -9,7 +9,10 @@ import { import { getPushNotificationUserAgentString } from '../../../src/pushNotifications/utils/getPushNotificationUserAgentString'; import { userAgentValue } from '../../testUtils/data'; -jest.mock('@aws-amplify/core/internals/utils'); +jest.mock('@aws-amplify/core/internals/utils', () => ({ + ...jest.requireActual('@aws-amplify/core/internals/utils'), + getAmplifyUserAgent: jest.fn(), +})); describe('getPushNotificationUserAgentString', () => { // assert mocks diff --git a/packages/notifications/in-app-messaging/package.json b/packages/notifications/in-app-messaging/package.json index 1cbdf40eb27..b809d100bd5 100644 --- a/packages/notifications/in-app-messaging/package.json +++ b/packages/notifications/in-app-messaging/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/notifications/in-app-messaging", - "main": "../lib/inAppMessaging/index.js", - "browser": "../lib-esm/inAppMessaging/index.js", - "module": "../lib-esm/inAppMessaging/index.js", - "typings": "../lib-esm/inAppMessaging/index.d.ts" + "main": "../dist/cjs/inAppMessaging/index.js", + "browser": "../dist/esm/inAppMessaging/index.mjs", + "module": "../dist/esm/inAppMessaging/index.mjs", + "react-native": "../src/inAppMessaging/index.ts", + "typings": "../dist/esm/inAppMessaging/index.d.ts" } diff --git a/packages/notifications/in-app-messaging/pinpoint/package.json b/packages/notifications/in-app-messaging/pinpoint/package.json index b8c5a421577..b22f1723a12 100644 --- a/packages/notifications/in-app-messaging/pinpoint/package.json +++ b/packages/notifications/in-app-messaging/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/notifications/in-app-messaging/pinpoint", - "main": "../../lib/inAppMessaging/providers/pinpoint/index.js", - "browser": "../../lib-esm/inAppMessaging/providers/pinpoint/index.js", - "module": "../../lib-esm/inAppMessaging/providers/pinpoint/index.js", - "typings": "../../lib-esm/inAppMessaging/providers/pinpoint/index.d.ts" + "main": "../../dist/cjs/inAppMessaging/providers/pinpoint/index.js", + "browser": "../../dist/esm/inAppMessaging/providers/pinpoint/index.mjs", + "module": "../../dist/esm/inAppMessaging/providers/pinpoint/index.mjs", + "react-native": "../../src/inAppMessaging/providers/pinpoint/index.ts", + "typings": "../../dist/esm/inAppMessaging/providers/pinpoint/index.d.ts" } diff --git a/packages/notifications/package.json b/packages/notifications/package.json index 7ce32ce825e..229fb10c657 100644 --- a/packages/notifications/package.json +++ b/packages/notifications/package.json @@ -2,9 +2,10 @@ "name": "@aws-amplify/notifications", "version": "2.0.0", "description": "Notifications category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -12,13 +13,13 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm run clean && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -27,48 +28,51 @@ "typesVersions": { ">=4.2": { "in-app-messaging": [ - "./lib-esm/inAppMessaging/index.d.ts" + "./dist/esm/inAppMessaging/index.d.ts" ], "push-notifications": [ - "./lib-esm/pushNotifications/providers/index.d.ts" + "./dist/esm/pushNotifications/providers/index.d.ts" ], "in-app-messaging/pinpoint": [ - "./lib-esm/inAppMessaging/providers/pinpoint/index.d.ts" + "./dist/esm/inAppMessaging/providers/pinpoint/index.d.ts" ], "push-notifications/pinpoint": [ - "./lib-esm/pushNotifications/providers/pinpoint/index.d.ts" + "./dist/esm/pushNotifications/providers/pinpoint/index.d.ts" ] } }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./in-app-messaging": { - "types": "./lib-esm/inAppMessaging/index.d.ts", - "import": "./lib-esm/inAppMessaging/index.js", - "require": "./lib/inAppMessaging/index.js" + "types": "./dist/esm/inAppMessaging/index.d.ts", + "import": "./dist/esm/inAppMessaging/index.mjs", + "require": "./dist/cjs/inAppMessaging/index.js", + "react-native": "./src/inAppMessaging/index.ts" }, "./push-notifications": { - "types": "./lib-esm/pushNotifications/index.d.ts", - "import": "./lib-esm/pushNotifications/index.js", - "require": "./lib/pushNotifications/index.js" + "types": "./dist/esm/pushNotifications/index.d.ts", + "import": "./dist/esm/pushNotifications/index.mjs", + "require": "./dist/cjs/pushNotifications/index.js", + "react-native": "./src/pushNotifications/index.ts" }, "./in-app-messaging/pinpoint": { - "types": "./lib-esm/inAppMessaging/providers/pinpoint/index.d.ts", - "import": "./lib-esm/inAppMessaging/providers/pinpoint/index.js", - "require": "./lib/inAppMessaging/providers/pinpoint/index.js" + "types": "./dist/esm/inAppMessaging/providers/pinpoint/index.d.ts", + "import": "./dist/esm/inAppMessaging/providers/pinpoint/index.mjs", + "require": "./dist/cjs/inAppMessaging/providers/pinpoint/index.js", + "react-native": "./src/inAppMessaging/providers/pinpoint/index.ts" }, "./push-notifications/pinpoint": { - "types": "./lib-esm/pushNotifications/providers/pinpoint/index.d.ts", - "import": "./lib-esm/pushNotifications/providers/pinpoint/index.js", - "require": "./lib/pushNotifications/providers/pinpoint/index.js" + "types": "./dist/esm/pushNotifications/providers/pinpoint/index.d.ts", + "import": "./dist/esm/pushNotifications/providers/pinpoint/index.mjs", + "require": "./dist/cjs/pushNotifications/providers/pinpoint/index.js", + "react-native": "./src/pushNotifications/providers/pinpoint/index.ts" }, "./package.json": "./package.json" }, - "react-native": "./lib-esm/index.js", "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -80,8 +84,8 @@ }, "homepage": "https://docs.amplify.aws/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "in-app-messaging", "push-notifications" @@ -96,6 +100,8 @@ "devDependencies": { "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "jest": { @@ -135,9 +141,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/notifications/push-notifications/package.json b/packages/notifications/push-notifications/package.json index 9a433dbdee6..d2aea468732 100644 --- a/packages/notifications/push-notifications/package.json +++ b/packages/notifications/push-notifications/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/notifications/push-notifications", - "main": "../lib/pushNotifications/index.js", - "browser": "../lib-esm/pushNotifications/index.js", - "module": "../lib-esm/pushNotifications/index.js", - "typings": "../lib-esm/pushNotifications/index.d.ts" + "main": "../dist/cjs/pushNotifications/index.js", + "browser": "../dist/esm/pushNotifications/index.mjs", + "module": "../dist/esm/pushNotifications/index.mjs", + "react-native": "../src/pushNotifications/index.ts", + "typings": "../dist/esm/pushNotifications/index.d.ts" } diff --git a/packages/notifications/push-notifications/pinpoint/package.json b/packages/notifications/push-notifications/pinpoint/package.json index 812450835af..33fc235656b 100644 --- a/packages/notifications/push-notifications/pinpoint/package.json +++ b/packages/notifications/push-notifications/pinpoint/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/notifications/push-notifications/pinpoint", - "main": "../../lib/pushNotifications/providers/pinpoint/index.js", - "browser": "../../lib-esm/pushNotifications/providers/pinpoint/index.js", - "module": "../../lib-esm/pushNotifications/providers/pinpoint/index.js", - "typings": "../../lib-esm/pushNotifications/providers/pinpoint/index.d.ts" + "main": "../../dist/cjs/pushNotifications/providers/pinpoint/index.js", + "browser": "../../dist/esm/pushNotifications/providers/pinpoint/index.mjs", + "module": "../../dist/esm/pushNotifications/providers/pinpoint/index.mjs", + "react-native": "../../src/pushNotifications/providers/pinpoint/index.ts", + "typings": "../../dist/esm/pushNotifications/providers/pinpoint/index.d.ts" } diff --git a/packages/notifications/rollup.config.mjs b/packages/notifications/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/notifications/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts index 8ae2eb61bd6..a371217c767 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts @@ -7,7 +7,7 @@ import { processInAppMessages, } from '../utils'; import { InAppMessage } from '../../../types'; -import flatten from 'lodash/flatten'; +import flatten from 'lodash/flatten.js'; import { defaultStorage } from '@aws-amplify/core'; import { notifyEventListeners } from '../../../../eventListeners'; import { assertServiceError } from '../../../errors'; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts index 52a1f996ff9..8b596b43a1d 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts @@ -4,7 +4,7 @@ import { ConsoleLogger } from '@aws-amplify/core'; import { InAppMessagingAction } from '@aws-amplify/core/internals/utils'; import type { InAppMessageCampaign as PinpointInAppMessage } from '@aws-amplify/core/internals/aws-clients/pinpoint'; -import isEmpty from 'lodash/isEmpty'; +import isEmpty from 'lodash/isEmpty.js'; import { InAppMessage, InAppMessageAction, diff --git a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts index bfd79b64d5e..20e54209095 100644 --- a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts +++ b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts @@ -6,7 +6,7 @@ import { AssertionFunction, createAssertionFunction, } from '@aws-amplify/core/internals/utils'; -import { isInitialized } from '../utils'; +import { isInitialized } from '../utils/initializationManager'; import { PushNotificationError } from './PushNotificationError'; export enum PushNotificationValidationErrorCode { diff --git a/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts b/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts index 0f1f29e386e..9067f56b1b8 100644 --- a/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts +++ b/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { fetchAuthSession } from '@aws-amplify/core'; -import { assert, PushNotificationValidationErrorCode } from '../errors'; +import { + assert, + PushNotificationValidationErrorCode, +} from '../errors/errorHelpers'; /** * @internal diff --git a/packages/notifications/webpack.config.dev.js b/packages/notifications/webpack.config.dev.js index 87df7075063..8123b5bfbd7 100644 --- a/packages/notifications/webpack.config.dev.js +++ b/packages/notifications/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-notifications': './lib-esm/index.js', + 'aws-amplify-notifications': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/notifications/webpack.config.js b/packages/notifications/webpack.config.js index 26bb5170ab5..d2d05dedac3 100644 --- a/packages/notifications/webpack.config.js +++ b/packages/notifications/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-notifications.min': './lib-esm/index.js', + 'aws-amplify-notifications.min': './dist/esm/index.mjs', }, externals: [ 'react-native', @@ -11,7 +11,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_notifications', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/predictions/package.json b/packages/predictions/package.json index 1ecfa826ca7..b50b1a6b715 100644 --- a/packages/predictions/package.json +++ b/packages/predictions/package.json @@ -2,26 +2,24 @@ "name": "@aws-amplify/predictions", "version": "6.0.0", "description": "Machine learning category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": [ - "./lib/Predictions.js", - "./lib-esm/Predictions.js" + "./dist/cjs/Predictions.js", + "./dist/esm/Predictions.mjs" ], "scripts": { "test": "npm run lint && jest -w 1 --passWithNoTests --coverage --maxWorkers 2", "test:size": "size-limit", - "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm run clean && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -40,8 +38,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src" ], "dependencies": { @@ -62,14 +60,16 @@ }, "devDependencies": { "@aws-amplify/core": "6.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "Predictions", - "path": "./lib-esm/index.js", - "import": "{ Amplify, Predictions }", - "limit": "66 kB" + "path": "./dist/esm/index.mjs", + "import": "{ Predictions }", + "limit": "69.8 kB" } ], "jest": { @@ -112,9 +112,7 @@ }, "coveragePathIgnorePatterns": [ "/node_modules/", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/predictions/rollup.config.mjs b/packages/predictions/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/predictions/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/predictions/webpack.config.dev.js b/packages/predictions/webpack.config.dev.js index a9152d2dc16..ad663e82f0d 100644 --- a/packages/predictions/webpack.config.dev.js +++ b/packages/predictions/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-predictions': './lib-esm/index.js', + 'aws-amplify-predictions': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/predictions/webpack.config.js b/packages/predictions/webpack.config.js index a3a6edcb31d..16a38ad3590 100644 --- a/packages/predictions/webpack.config.js +++ b/packages/predictions/webpack.config.js @@ -1,11 +1,11 @@ module.exports = { entry: { - 'aws-amplify-predictions.min': './lib-esm/index.js', + 'aws-amplify-predictions.min': './dist/esm/index.mjs', }, externals: [{ '@aws-amplify/core': 'aws_amplify_core' }], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_predictions', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/pubsub/build.js b/packages/pubsub/build.js deleted file mode 100644 index 5bdcce15dc5..00000000000 --- a/packages/pubsub/build.js +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -'use strict'; - -const build = require('../../scripts/build'); - -build(process.argv[2], process.argv[3]); diff --git a/packages/pubsub/internals/package.json b/packages/pubsub/internals/package.json index 95d8a3e1e1c..154efbeee85 100644 --- a/packages/pubsub/internals/package.json +++ b/packages/pubsub/internals/package.json @@ -1,8 +1,8 @@ { "name": "@aws-amplify/pubsub/internals", - "types": "../lib-esm/internals/index.d.ts", - "main": "../lib/internals/index.js", - "module": "../lib-esm/internals/index.js", - "react-native": "../lib-esm/internals/index.js", + "types": "../dist/esm/internals/index.d.ts", + "main": "../dist/cjs/internals/index.js", + "module": "../dist/esm/internals/index.mjs", + "react-native": "../src/internals/index.ts", "sideEffects": false } diff --git a/packages/pubsub/iot/packages.json b/packages/pubsub/iot/packages.json index c46241c615d..0dda3dc6a3a 100644 --- a/packages/pubsub/iot/packages.json +++ b/packages/pubsub/iot/packages.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/pubsub/iot", - "main": "../lib/clients/iot.js", - "browser": "../lib-esm/clients/iot.js", - "module": "../lib-esm/clients/iot.js", - "typings": "../lib-esm/clients/iot.d.ts" + "main": "../dist/cjs/clients/iot.js", + "browser": "../dist/esm/clients/iot.mjs", + "module": "../dist/esm/clients/iot.mjs", + "typings": "../dist/esm/clients/iot.d.ts", + "react-native": "../src/clients/iot.ts" } diff --git a/packages/pubsub/mqtt/packages.json b/packages/pubsub/mqtt/packages.json index d7661f9ed58..301b5280a49 100644 --- a/packages/pubsub/mqtt/packages.json +++ b/packages/pubsub/mqtt/packages.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/pubsub/mqtt", - "main": "../lib/clients/mqtt.js", - "browser": "../lib-esm/clients/mqtt.js", - "module": "../lib-esm/clients/mqtt.js", - "typings": "../lib-esm/clients/mqtt.d.ts" + "main": "../dist/cjs/clients/mqtt.js", + "browser": "../dist/esm/clients/mqtt.mjs", + "module": "../dist/esm/clients/mqtt.mjs", + "typings": "../dist/esm/clients/mqtt.d.ts", + "react-native": "../src/clients/mqtt.ts" } diff --git a/packages/pubsub/package.json b/packages/pubsub/package.json index f7332c626ae..d6f518465a7 100644 --- a/packages/pubsub/package.json +++ b/packages/pubsub/package.json @@ -2,12 +2,10 @@ "name": "@aws-amplify/pubsub", "version": "6.0.0", "description": "Pubsub category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -15,13 +13,13 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:size": "size-limit", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && cp -R src/vendor lib/vendor && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm && cp -R src/vendor lib-esm/vendor", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "npm run clean:size && rimraf lib-esm lib dist", + "build-with-test": "npm run clean && npm run build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs && cp -R src/vendor dist/cjs/vendor && cp -R src/vendor dist/esm/vendor", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -30,28 +28,31 @@ "typesVersions": { ">=4.2": { "iot": [ - "./lib-esm/clients/iot.d.ts" + "./dist/esm/clients/iot.d.ts" ], "mqtt": [ - "./lib-esm/clients/mqtt.d.ts" + "./dist/esm/clients/mqtt.d.ts" ] } }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./iot": { - "types": "./lib-esm/clients/iot.d.ts", - "import": "./lib-esm/clients/iot.js", - "require": "./lib/clients/iot.js" + "types": "./dist/esm/clients/iot.d.ts", + "import": "./dist/esm/clients/iot.mjs", + "require": "./dist/cjs/clients/iot.js", + "react-native": "./src/clients/iot.ts" }, "./mqtt": { - "types": "./lib-esm/clients/mqtt.d.ts", - "import": "./lib-esm/clients/mqtt.js", - "require": "./lib/clients/mqtt.js" + "types": "./dist/esm/clients/mqtt.d.ts", + "import": "./dist/esm/clients/mqtt.mjs", + "require": "./dist/cjs/clients/mqtt.js", + "react-native": "./src/clients/mqtt.ts" } }, "repository": { @@ -65,8 +66,8 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", "iot", "mqtt" @@ -84,18 +85,20 @@ }, "devDependencies": { "@aws-amplify/core": "6.0.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ { "name": "PubSub (IoT provider)", - "path": "./lib-esm/index.js", + "path": "./dist/esm/index.mjs", "import": "{ generateClient }", "limit": "1.2 kB" }, { "name": "PubSub (Mqtt provider)", - "path": "./lib-esm/clients/mqtt.js", + "path": "./dist/esm/clients/mqtt.mjs", "import": "{ generateClient }", "limit": "1.07 kB" } @@ -139,9 +142,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/pubsub/rollup.config.mjs b/packages/pubsub/rollup.config.mjs new file mode 100644 index 00000000000..4712f943f40 --- /dev/null +++ b/packages/pubsub/rollup.config.mjs @@ -0,0 +1,38 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { fileURLToPath } from 'node:url'; +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + external: [ + fileURLToPath(new URL('src/vendor/paho-mqtt.js', import.meta.url)), + ], + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + external: [ + fileURLToPath(new URL('src/vendor/paho-mqtt.js', import.meta.url)), + ], + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/pubsub/src/Providers/MqttOverWS.ts b/packages/pubsub/src/Providers/MqttOverWS.ts index dfd374d1280..1d3444036d9 100644 --- a/packages/pubsub/src/Providers/MqttOverWS.ts +++ b/packages/pubsub/src/Providers/MqttOverWS.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore -import * as Paho from '../vendor/paho-mqtt'; +import * as Paho from '../vendor/paho-mqtt.js'; import { Observable, SubscriptionLike as Subscription, Observer } from 'rxjs'; import { AbstractPubSub } from './PubSub'; diff --git a/packages/pubsub/webpack.config.dev.js b/packages/pubsub/webpack.config.dev.js index 80372c0a752..a9e027f06ec 100644 --- a/packages/pubsub/webpack.config.dev.js +++ b/packages/pubsub/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-pubsub': './lib-esm/index.js', + 'aws-amplify-pubsub': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/pubsub/webpack.config.js b/packages/pubsub/webpack.config.js index 93dc19c954e..8b9545a39ce 100644 --- a/packages/pubsub/webpack.config.js +++ b/packages/pubsub/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-pubsub.min': './lib-esm/index.js', + 'aws-amplify-pubsub.min': './dist/esm/index.mjs', }, externals: [ 'graphql', @@ -11,7 +11,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_pubsub', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 6b120d744d0..9bc0af6ae21 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -2,9 +2,10 @@ "name": "@aws-amplify/react-native", "version": "1.0.0", "description": "React Native core module for aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -13,11 +14,10 @@ "test": "tslint 'src/**/*.ts'", "test:android": "./android/gradlew test -p ./android", "build-with-test": "npm run clean && npm test && tsc", - "build:cjs": "rimraf lib && tsc -p ./tsconfig.build.json -m commonjs --outDir lib", - "build:esm": "rimraf lib-esm && tsc -p ./tsconfig.build.json -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -p ./tsconfig.build.json -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -p ./tsconfig.build.json -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -p ./tsconfig.build.json -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -p ./tsconfig.build.json -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs", "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", @@ -37,15 +37,14 @@ "@aws-amplify/rtn-web-browser": "^1.0.0", "@react-native-async-storage/async-storage": "^1.17.12", "@react-native-community/netinfo": "4.7.0", + "@rollup/plugin-typescript": "11.1.5", "@types/base-64": "1.0.0", "@types/react-native": "0.70.0", "react-native": "0.70.0", "react-native-get-random-values": "1.9.0", + "rollup": "3.29.4", "typescript": "5.1.6" }, - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -60,8 +59,8 @@ "Amplify*.podspec", "android", "ios", - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src" ], "source": "src/index" diff --git a/packages/react-native/rollup.config.mjs b/packages/react-native/rollup.config.mjs new file mode 100644 index 00000000000..a299129900e --- /dev/null +++ b/packages/react-native/rollup.config.mjs @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [ + typescript({ + ...cjsTSOptions, + tsconfig: 'tsconfig.build.json', + }), + ], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [ + typescript({ + ...esmTSOptions, + tsconfig: 'tsconfig.build.json', + }), + ], + }, +]); + +export default config; diff --git a/packages/react-native/tsconfig.build.json b/packages/react-native/tsconfig.build.json index 72c8d901801..507d6e739b0 100644 --- a/packages/react-native/tsconfig.build.json +++ b/packages/react-native/tsconfig.build.json @@ -1,5 +1,5 @@ { "extends": "./tsconfig.json", - "include": ["lib*/**/*.ts", "src"], + "include": ["src"], "exclude": ["example"] } diff --git a/packages/react-native/tsconfig.json b/packages/react-native/tsconfig.json index caaaa898f6a..eee06a92ae0 100755 --- a/packages/react-native/tsconfig.json +++ b/packages/react-native/tsconfig.json @@ -1,22 +1,14 @@ //WARNING: If you are manually specifying files to compile then the tsconfig.json is completely ignored, you must use command line flags { + "extends": "../tsconfig.base.json", "compilerOptions": { "paths": { "@aws-amplify/react-native": ["./src/index"] }, "allowSyntheticDefaultImports": true, - "outDir": "./lib/", - "target": "esnext", "noImplicitAny": true, "jsx": "react", "lib": ["esnext"], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": ["./node_modules/@types", "../../node_modules/@types"], - "esModuleInterop": true, "resolveJsonModule": true, "strict": true, "skipLibCheck": true diff --git a/packages/rtn-push-notification/build.js b/packages/rtn-push-notification/build.js deleted file mode 100644 index 5bdcce15dc5..00000000000 --- a/packages/rtn-push-notification/build.js +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -'use strict'; - -const build = require('../../scripts/build'); - -build(process.argv[2], process.argv[3]); diff --git a/packages/rtn-push-notification/index.js b/packages/rtn-push-notification/index.js deleted file mode 100644 index 23cd3fb17f1..00000000000 --- a/packages/rtn-push-notification/index.js +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -'use strict'; - -if (process.env.NODE_ENV === 'production') { - module.exports = require('./dist/aws-amplify-rtn-push-notification.min.js'); -} else { - module.exports = require('./dist/aws-amplify-rtn-push-notification.js'); -} diff --git a/packages/rtn-push-notification/package.json b/packages/rtn-push-notification/package.json index 9b6a21cedc2..fc83003929f 100644 --- a/packages/rtn-push-notification/package.json +++ b/packages/rtn-push-notification/package.json @@ -2,9 +2,10 @@ "name": "@aws-amplify/rtn-push-notification", "version": "1.2.0", "description": "React Native module for aws-amplify push notifications", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -12,24 +13,22 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "test:android": "./android/gradlew test -p ./android", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", + "build-with-test": "npm run clean && npm test && tsc", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs", "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 99" }, "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", "@types/react-native": "0.70.0", + "rollup": "3.29.4", "typescript": "5.0.2" }, - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -44,8 +43,8 @@ "Amplify*.podspec", "android", "ios", - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src" ], "jest": { @@ -84,9 +83,7 @@ }, "coveragePathIgnorePatterns": [ "node_modules", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/rtn-push-notification/rollup.config.mjs b/packages/rtn-push-notification/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/rtn-push-notification/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts b/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts index 00484db38cd..93d52f4886b 100644 --- a/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts +++ b/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { isEmpty } from 'lodash'; +import isEmpty from 'lodash/isEmpty.js'; import { ApnsMessage, FcmMessage, diff --git a/packages/rtn-push-notification/tsconfig.json b/packages/rtn-push-notification/tsconfig.json index 3c0bca8b5e2..b0bed2b668d 100755 --- a/packages/rtn-push-notification/tsconfig.json +++ b/packages/rtn-push-notification/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "../tsconfig.base.json", "compilerOptions": { - "target": "esnext", - "lib": ["dom", "es2019", "esnext.asynciterable", "esnext"], "importHelpers": false, "strict": true, "noImplicitAny": true diff --git a/packages/rtn-push-notification/webpack.config.dev.js b/packages/rtn-push-notification/webpack.config.dev.js deleted file mode 100644 index 76723aae1c8..00000000000 --- a/packages/rtn-push-notification/webpack.config.dev.js +++ /dev/null @@ -1,6 +0,0 @@ -var config = require('./webpack.config.js'); - -var entry = { - 'aws-amplify-rtn-push-notification': './lib-esm/index.js', -}; -module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/rtn-push-notification/webpack.config.js b/packages/rtn-push-notification/webpack.config.js deleted file mode 100644 index e8cf7f361c9..00000000000 --- a/packages/rtn-push-notification/webpack.config.js +++ /dev/null @@ -1,39 +0,0 @@ -module.exports = { - entry: { - 'aws-amplify-rtn-push-notification.min': './lib-esm/index.js', - }, - externals: ['react-native'], - output: { - filename: '[name].js', - path: __dirname + '/dist', - library: 'aws_amplify_rtn_push_notification', - libraryTarget: 'umd', - umdNamedDefine: true, - globalObject: 'this', - devtoolModuleFilenameTemplate: require('../aws-amplify/webpack-utils') - .devtoolModuleFilenameTemplate, - }, - // Enable sourcemaps for debugging webpack's output. - devtool: 'source-map', - resolve: { - extensions: ['.js', '.json'], - }, - mode: 'production', - module: { - rules: [ - { - test: /\.js?$/, - exclude: /node_modules/, - use: [ - 'babel-loader', - { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'], - }, - }, - ], - }, - ], - }, -}; diff --git a/packages/rtn-web-browser/package.json b/packages/rtn-web-browser/package.json index 4057148d309..a71beb2542a 100644 --- a/packages/rtn-web-browser/package.json +++ b/packages/rtn-web-browser/package.json @@ -2,9 +2,10 @@ "name": "@aws-amplify/rtn-web-browser", "version": "1.0.0", "description": "React Native module for aws-amplify web browser", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": "./src/index.ts", + "typings": "./dist/esm/index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" @@ -13,24 +14,22 @@ "test": "tslint 'src/**/*.ts'", "test:android": "./android/gradlew test -p ./android", "build-with-test": "npm run clean && npm test && tsc", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", - "clean": "rimraf lib-esm lib dist", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs", + "clean": "rimraf dist lib lib-esm", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 88.21" }, "devDependencies": { "@types/react-native": "0.70.0", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "react-native": "0.72.3", "typescript": "5.1.6" }, - "react-native": { - "./lib/index": "./lib-esm/index.js" - }, "repository": { "type": "git", "url": "https://github.com/aws-amplify/amplify-js.git" @@ -45,8 +44,8 @@ "Amplify*.podspec", "android", "ios", - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src" ] } diff --git a/packages/rtn-web-browser/rollup.config.mjs b/packages/rtn-web-browser/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/rtn-web-browser/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/rtn-web-browser/tsconfig.build.json b/packages/rtn-web-browser/tsconfig.build.json deleted file mode 100644 index af6adca185d..00000000000 --- a/packages/rtn-web-browser/tsconfig.build.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": {}, - "include": ["lib*/**/*.ts", "src"] -} diff --git a/packages/rtn-web-browser/tsconfig.json b/packages/rtn-web-browser/tsconfig.json index 164cc548a41..b0bed2b668d 100755 --- a/packages/rtn-web-browser/tsconfig.json +++ b/packages/rtn-web-browser/tsconfig.json @@ -1,22 +1,9 @@ -//WARNING: If you are manually specifying files to compile then the tsconfig.json is completely ignored, you must use command line flags { + "extends": "../tsconfig.base.json", "compilerOptions": { - "allowSyntheticDefaultImports": true, - "outDir": "./lib/", - "target": "esnext", - "noImplicitAny": true, - "lib": ["esnext"], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": ["./node_modules/@types", "../../node_modules/@types"], - "esModuleInterop": true, - "resolveJsonModule": true, + "importHelpers": false, "strict": true, - "skipLibCheck": true + "noImplicitAny": true }, - "include": ["src/**/*"], - "exclude": ["src/setupTests.ts"] + "include": ["./src"] } diff --git a/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts b/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts index 5b2ab2277c4..c185e6cc3cb 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts @@ -2,12 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { HttpResponse } from '@aws-amplify/core/internals/aws-client-utils'; -import { fetchTransferHandler } from '@aws-amplify/core/lib/clients/handlers/fetch'; +import { fetchTransferHandler } from '@aws-amplify/core/dist/cjs/clients/handlers/fetch'; import cases from './cases'; import { StorageError } from '../../../../../../src/errors/StorageError'; -jest.mock('@aws-amplify/core/lib/clients/handlers/fetch'); +jest.mock('@aws-amplify/core/dist/cjs/clients/handlers/fetch'); const mockFetchTransferHandler = fetchTransferHandler as jest.Mock; const mockBinaryResponse = ({ diff --git a/packages/storage/package.json b/packages/storage/package.json index f893260c3d0..b80ebb47d52 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -2,12 +2,20 @@ "name": "@aws-amplify/storage", "version": "6.0.0", "description": "Storage category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib-esm/index.js", - "react-native": "./lib-esm/index.js", - "typings": "./lib-esm/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "react-native": { + "./dist/cjs/index": "./src/index.ts", + "fast-xml-parser": "fast-xml-parser", + "buffer": "buffer" + }, + "typings": "./dist/esm/index.d.ts", "browser": { - "./lib-esm/lib-esm/providers/s3/utils/client/runtime/index": "./lib-esm/providers/s3/utils/client/runtime/index.browser.js" + "./dist/esm/providers/s3/utils/client/runtime/base64/index.native.mjs": "./dist/esm/providers/s3/utils/client/runtime/base64/index.browser.mjs", + "./dist/esm/providers/s3/utils/client/runtime/s3TransferHandler/fetch.mjs": "./dist/esm/providers/s3/utils/client/runtime/s3TransferHandler/xhr.mjs", + "./dist/esm/providers/s3/utils/client/runtime/xmlParser/pureJs.mjs": "./dist/esm/providers/s3/utils/client/runtime/xmlParser/dom.mjs", + "fast-xml-parser": false, + "buffer": false }, "sideEffects": false, "publishConfig": { @@ -16,11 +24,11 @@ "scripts": { "test": "npm run lint && jest -w 1 --coverage", "build-with-test": "npm test && npm run build", - "build:cjs": "rimraf lib && tsc -m commonjs --outDir lib && webpack && webpack --config ./webpack.config.dev.js", - "build:esm": "rimraf lib-esm && tsc -m esnext --outDir lib-esm", - "build:cjs:watch": "rimraf lib && tsc -m commonjs --outDir lib --watch", - "build:esm:watch": "rimraf lib-esm && tsc -m esnext --outDir lib-esm --watch", - "build": "npm run clean && npm run build:esm && npm run build:cjs", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", "clean": "npm run clean:size && rimraf lib-esm lib dist", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", @@ -30,16 +38,13 @@ "typesVersions": { ">=4.2": { "s3": [ - "./lib-esm/providers/s3/index.d.ts" + "./dist/esm/providers/s3/index.d.ts" ], "server": [ - "./lib-esm/server.d.ts" - ], - "internals": [ - "./lib-esm/lib-esm/internals/index.d.ts" + "./dist/esm/server.d.ts" ], "s3/server": [ - "./lib-esm/providers/s3/server.d.ts" + "./dist/esm/providers/s3/server.d.ts" ] } }, @@ -54,45 +59,41 @@ }, "homepage": "https://aws-amplify.github.io/", "files": [ - "lib", - "lib-esm", + "dist/cjs", + "dist/esm", "src", - "internals", "server", "s3" ], "dependencies": { - "@smithy/md5-js": "2.0.7", "@aws-sdk/types": "3.398.0", - "fast-xml-parser": "^4.2.5", + "@smithy/md5-js": "2.0.7", "buffer": "4.9.2", + "fast-xml-parser": "^4.2.5", "tslib": "^2.5.0" }, "exports": { ".": { - "types": "./lib-esm/index.d.ts", - "import": "./lib-esm/index.js", - "require": "./lib/index.js" + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" }, "./server": { - "types": "./lib-esm/server.d.ts", - "import": "./lib-esm/server.js", - "require": "./lib/server.js" - }, - "./internals": { - "types": "./lib-esm/lib-esm/internals/index.d.ts", - "import": "./lib-esm/internals/index.js", - "require": "./lib/internals/index.js" + "types": "./dist/esm/server.d.ts", + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.js" }, "./s3": { - "types": "./lib-esm/providers/s3/index.d.ts", - "import": "./lib-esm/providers/s3/index.js", - "require": "./lib/providers/s3/index.js" + "types": "./dist/esm/providers/s3/index.d.ts", + "import": "./dist/esm/providers/s3/index.mjs", + "require": "./dist/cjs/providers/s3/index.js", + "react-native": "./src/providers/s3/index.ts" }, "./s3/server": { - "types": "./lib-esm/providers/s3/server.d.ts", - "import": "./lib-esm/providers/s3/server.js", - "require": "./lib/providers/s3/server.js" + "types": "./dist/esm/providers/s3/server.d.ts", + "import": "./dist/esm/providers/s3/server.mjs", + "require": "./dist/cjs/providers/s3/server.js" }, "./package.json": "./package.json" }, @@ -102,6 +103,9 @@ "devDependencies": { "@aws-amplify/core": "6.0.0", "@aws-amplify/react-native": "^1.0.0", + "@rollup/plugin-json": "6.0.1", + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4", "typescript": "5.0.2" }, "jest": { @@ -113,7 +117,9 @@ "tsConfig": { "downlevelIteration": true, "allowJs": true, - "types": ["@types/jest"], + "types": [ + "@types/jest" + ], "outDir": "./tsconfig.json", "noEmitOnError": false, "noImplicitAny": false, @@ -131,9 +137,7 @@ "cases" ], "modulePathIgnorePatterns": [ - "dist", - "lib", - "lib-esm" + "dist" ], "moduleFileExtensions": [ "ts", @@ -154,9 +158,7 @@ }, "coveragePathIgnorePatterns": [ "/node_modules/", - "dist", - "lib", - "lib-esm" + "dist" ] } } diff --git a/packages/storage/rollup.config.mjs b/packages/storage/rollup.config.mjs new file mode 100644 index 00000000000..5f2e054bc06 --- /dev/null +++ b/packages/storage/rollup.config.mjs @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { defineConfig } from 'rollup'; +import typescript from '@rollup/plugin-typescript'; +import { getInputForGlob } from '../../rollup/utils.mjs'; +import { + cjsOutput, + cjsTSOptions, + esmOutput, + esmTSOptions, +} from '../../rollup/common.mjs'; + +const input = getInputForGlob('src/**/*.ts'); + +const config = defineConfig([ + // CJS config + { + input: input, + output: cjsOutput, + plugins: [typescript(cjsTSOptions)], + }, + // ESM config + { + input: input, + output: esmOutput, + plugins: [typescript(esmTSOptions)], + }, +]); + +export default config; diff --git a/packages/storage/s3/package.json b/packages/storage/s3/package.json index d45ec7e8290..10b55880abf 100644 --- a/packages/storage/s3/package.json +++ b/packages/storage/s3/package.json @@ -1,7 +1,8 @@ { "name": "@aws-amplify/storage/s3", - "main": "../lib/providers/s3/index.js", - "browser": "../lib-esm/providers/s3/index.js", - "module": "../lib-esm/providers/s3/index.js", - "typings": "../lib-esm/providers/s3/index.d.ts" + "main": "../dist/cjs/providers/s3/index.js", + "react-native": "../src/providers/s3/index.ts", + "browser": "../dist/esm/providers/s3/index.mjs", + "module": "../dist/esm/providers/s3/index.mjs", + "typings": "../dist/esm/providers/s3/index.d.ts" } diff --git a/packages/storage/s3/server/package.json b/packages/storage/s3/server/package.json index f00e619da0b..72e0a285550 100644 --- a/packages/storage/s3/server/package.json +++ b/packages/storage/s3/server/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/storage/s3/server", - "main": "../../lib/providers/s3/server.js", - "browser": "../../lib-esm/providers/s3/server.js", - "module": "../../lib-esm/providers/s3/server.js", - "typings": "../../lib-esm/providers/s3/server.d.ts" + "main": "../../dist/cjs/providers/s3/server.js", + "browser": "../../dist/esm/providers/s3/server.mjs", + "module": "../../dist/esm/providers/s3/server.mjs", + "typings": "../../dist/esm/providers/s3/server.d.ts" } diff --git a/packages/storage/server/package.json b/packages/storage/server/package.json index 53044d20ac6..c458ff54a6d 100644 --- a/packages/storage/server/package.json +++ b/packages/storage/server/package.json @@ -1,8 +1,7 @@ { "name": "@aws-amplify/storage/server", - "types": "../lib-esm/server.d.ts", - "main": "../lib/server.js", - "module": "../lib-esm/server.js", - "react-native": "../lib-esm/server.js", + "types": "../dist/esm/server.d.ts", + "main": "../dist/cjs/server.js", + "module": "../dist/esm/server.mjs", "sideEffects": false -} \ No newline at end of file +} diff --git a/packages/storage/src/providers/s3/utils/client/runtime/index.ts b/packages/storage/src/providers/s3/utils/client/runtime/index.ts index dcc005f85e3..2efc5628918 100644 --- a/packages/storage/src/providers/s3/utils/client/runtime/index.ts +++ b/packages/storage/src/providers/s3/utils/client/runtime/index.ts @@ -12,7 +12,3 @@ export { export { s3TransferHandler } from './s3TransferHandler/fetch'; export { parser } from './xmlParser/pureJs'; export { toBase64, utf8Encode } from './index.native'; - -// Make sure package.json is included in the TypeScript build output. -// This is necessary for bundlers to pick up the correct implementation for given platform(web/node). -import './package.json'; diff --git a/packages/storage/src/providers/s3/utils/client/runtime/package.json b/packages/storage/src/providers/s3/utils/client/runtime/package.json deleted file mode 100644 index 92bc95cfabe..00000000000 --- a/packages/storage/src/providers/s3/utils/client/runtime/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@aws-amplify/storage/src/providers/s3/utils/client/runtime", - "react-native": { - "./index.js": "./index.native.js", - "fast-xml-parser": "fast-xml-parser", - "buffer": "buffer" - }, - "browser": { - "./index.js": "./index.browser.js", - "fast-xml-parser": false, - "buffer": false - }, - "module": "./index.js" -} diff --git a/packages/storage/webpack.config.dev.js b/packages/storage/webpack.config.dev.js index a28938c82a5..8677f19b474 100644 --- a/packages/storage/webpack.config.dev.js +++ b/packages/storage/webpack.config.dev.js @@ -1,6 +1,6 @@ var config = require('./webpack.config.js'); var entry = { - 'aws-amplify-storage': './lib-esm/index.js', + 'aws-amplify-storage': './dist/esm/index.mjs', }; module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/storage/webpack.config.js b/packages/storage/webpack.config.js index 0ffabf991d8..4e2c978f395 100644 --- a/packages/storage/webpack.config.js +++ b/packages/storage/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { entry: { - 'aws-amplify-storage.min': './lib-esm/index.js', + 'aws-amplify-storage.min': './dist/esm/index.mjs', }, externals: [ { '@aws-amplify/core': 'aws_amplify_core' }, @@ -8,7 +8,7 @@ module.exports = { ], output: { filename: '[name].js', - path: __dirname + '/dist', + path: __dirname + '/dist/umd', library: 'aws_amplify_storage', libraryTarget: 'umd', umdNamedDefine: true, diff --git a/rollup/common.mjs b/rollup/common.mjs new file mode 100644 index 00000000000..a054b04f82a --- /dev/null +++ b/rollup/common.mjs @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +const defaultTSConfigPath = './tsconfig.json'; + +/** @type {import("rollup").OutputOptions}*/ +export const cjsOutput = { + dir: 'dist/cjs', + format: 'cjs', + entryFileNames: '[name].js', + preserveModules: true, + preserveModulesRoot: 'src', + sourcemap: true, +}; + +export const cjsTSOptions = { + outDir: 'dist/cjs', + declaration: false, // declarations are handled by the ESM build + module: 'CommonJS', + sourceMap: false, + tsconfig: defaultTSConfigPath, + tsBuildInfoFile: 'dist/meta/cjs.tsbuildinfo', +}; + +/** @type {import("rollup").OutputOptions}*/ +export const esmOutput = { + dir: 'dist/esm', + format: 'es', + entryFileNames: '[name].mjs', + preserveModules: true, + preserveModulesRoot: 'src', + sourcemap: true, +}; + +export const esmTSOptions = { + outDir: 'dist/esm', + declaration: true, + sourceMap: false, + tsconfig: defaultTSConfigPath, + tsBuildInfoFile: 'dist/meta/cjs.tsbuildinfo', +}; diff --git a/rollup/utils.mjs b/rollup/utils.mjs new file mode 100644 index 00000000000..d9b7d1875b0 --- /dev/null +++ b/rollup/utils.mjs @@ -0,0 +1,30 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from 'node:path'; +import * as glob from 'glob'; + +/** + * Return a map that contains relative file path <-> absolute file path. + * @param {string} matcher The glob matcher + * @param {{ ignore?: string[] }?} options The glob options + * @returns {object} A key value object. + */ +export const getInputForGlob = (matcher, { ignore } = {}) => + Object.fromEntries( + glob + .sync(matcher, { + ignore: ['src/**/global.d.ts', ...(ignore ?? [])], + }) + .map(file => [ + // This remove `src/` as well as the file extension from each + // file, so e.g. src/nested/foo.js becomes nested/foo + path.relative( + 'src', + file.slice(0, file.length - path.extname(file).length) + ), + // This expands the relative paths to absolute paths, so e.g. + // src/nested/foo becomes //packages/src/nested/foo.js + path.resolve(path.resolve('.'), file), + ]) + ); diff --git a/yarn.lock b/yarn.lock index d9eafe0534a..df6f2cf1944 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3691,6 +3691,30 @@ invariant "^2.2.4" nullthrows "^1.1.1" +"@rollup/plugin-json@6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/@rollup/plugin-json/-/plugin-json-6.0.1.tgz#7e2efcf5ed549963f1444e010611d22f463931c0" + integrity sha512-RgVfl5hWMkxN1h/uZj8FVESvPuBJ/uf6ly6GTj0GONnkfoBN5KC0MSz+PN2OLDgYXMhtG0mWpTrkiOjoxAIevw== + dependencies: + "@rollup/pluginutils" "^5.0.1" + +"@rollup/plugin-typescript@11.1.5": + version "11.1.5" + resolved "https://registry.yarnpkg.com/@rollup/plugin-typescript/-/plugin-typescript-11.1.5.tgz#039c763bf943a5921f3f42be255895e75764cb91" + integrity sha512-rnMHrGBB0IUEv69Q8/JGRD/n4/n6b3nfpufUu26axhUcboUzv/twfZU8fIBbTOphRAe0v8EyxzeDpKXqGHfyDA== + dependencies: + "@rollup/pluginutils" "^5.0.1" + resolve "^1.22.1" + +"@rollup/pluginutils@^5.0.1": + version "5.0.5" + resolved "https://registry.yarnpkg.com/@rollup/pluginutils/-/pluginutils-5.0.5.tgz#bbb4c175e19ebfeeb8c132c2eea0ecb89941a66c" + integrity sha512-6aEYR910NyP73oHiJglti74iRyOwgFU4x3meH/H8OJx6Ry0j6cOVZ5X/wTvub7G7Ao6qaHBEaNsV3GLJkSsF+Q== + dependencies: + "@types/estree" "^1.0.0" + estree-walker "^2.0.2" + picomatch "^2.3.1" + "@semantic-ui-react/event-stack@^3.1.0": version "3.1.3" resolved "https://registry.yarnpkg.com/@semantic-ui-react/event-stack/-/event-stack-3.1.3.tgz#2862d2631d67dd846c705db2fc1ede1c468be3a1" @@ -7192,6 +7216,11 @@ estree-walker@^0.6.0, estree-walker@^0.6.1: resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-0.6.1.tgz#53049143f40c6eb918b23671d1fe3219f3a1b362" integrity sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w== +estree-walker@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac" + integrity sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w== + esutils@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.1.6.tgz#c01ccaa9ae4b897c6d0c3e210ae52f3c7a844375" @@ -8079,7 +8108,7 @@ glob@7.1.6: once "^1.3.0" path-is-absolute "^1.0.0" -glob@^10.2.2: +glob@^10.2.2, glob@^10.3.10: version "10.3.10" resolved "https://registry.yarnpkg.com/glob/-/glob-10.3.10.tgz#0351ebb809fd187fe421ab96af83d3a70715df4b" integrity sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g== @@ -13906,6 +13935,13 @@ rollup-pluginutils@^2.0.1, rollup-pluginutils@^2.3.1, rollup-pluginutils@^2.5.0, dependencies: estree-walker "^0.6.1" +rollup@3.29.4: + version "3.29.4" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-3.29.4.tgz#4d70c0f9834146df8705bfb69a9a19c9e1109981" + integrity sha512-oWzmBZwvYrU0iJHtDmhsm662rC15FRXmcjCk1xD771dFDx5jJ02ufAQQTn0etB2emNk4J9EZg/yWKpsn9BWGRw== + optionalDependencies: + fsevents "~2.3.2" + rollup@^0.67.4: version "0.67.4" resolved "https://registry.yarnpkg.com/rollup/-/rollup-0.67.4.tgz#8ed6b0993337f84ec8a0387f824fa6c197e833ec" From 5f52c64a47d3828f0f0f20f6588566647ccf871f Mon Sep 17 00:00:00 2001 From: Chris F <5827964+cshfang@users.noreply.github.com> Date: Tue, 7 Nov 2023 16:11:43 -0800 Subject: [PATCH 37/45] fix(auth): Do not sign out client if Oauth signout fails (#12520) * fix(auth): Do not sign out client if Oauth signout fails * Do not block local data/tokens clearing for private sessions * Update to perform slightly different OAuth handling on web vs native --------- Co-authored-by: Jim Blanchard --- packages/auth/src/errors/constants.ts | 1 + .../src/providers/cognito/apis/signOut.ts | 112 ++++++------------ .../utils/oauth/completeOAuthSignOut.ts | 14 +++ .../utils/oauth/handleOAuthSignOut.native.ts | 32 +++++ .../cognito/utils/oauth/handleOAuthSignOut.ts | 24 ++++ .../providers/cognito/utils/oauth/index.ts | 1 + .../utils/oauth/oAuthSignOutRedirect.ts | 30 +++++ 7 files changed, 138 insertions(+), 76 deletions(-) create mode 100644 packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts create mode 100644 packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts create mode 100644 packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts create mode 100644 packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts diff --git a/packages/auth/src/errors/constants.ts b/packages/auth/src/errors/constants.ts index 0493a55e6c5..d7b9f929b08 100644 --- a/packages/auth/src/errors/constants.ts +++ b/packages/auth/src/errors/constants.ts @@ -24,3 +24,4 @@ export const invalidOriginException = new AuthError({ 'redirect is coming from a different origin. The oauth flow needs to be initiated from the same origin', recoverySuggestion: 'Please call signInWithRedirect from the same origin.', }); +export const OAUTH_SIGNOUT_EXCEPTION = 'OAuthSignOutException'; diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 59d85055d22..5c801b14748 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -3,14 +3,14 @@ import { Amplify, - CognitoUserPoolConfig, - Hub, clearCredentials, + CognitoUserPoolConfig, defaultStorage, + Hub, } from '@aws-amplify/core'; -import { getAuthUserAgentValue, openAuthSession } from '../../../utils'; + +import { getAuthUserAgentValue } from '../../../utils'; import { SignOutInput } from '../types'; -import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; import { tokenOrchestrator } from '../tokenProvider'; import { AuthAction, @@ -28,7 +28,10 @@ import { assertAuthTokens, assertAuthTokensWithRefreshToken, } from '../utils/types'; -import { getRedirectUrl } from '../utils/oauth/getRedirectUrl'; +import { handleOAuthSignOut } from '../utils/oauth'; +import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; +import { AuthError } from '../../../errors/AuthError'; +import { OAUTH_SIGNOUT_EXCEPTION } from '../../../errors/constants'; /** * Signs a user out @@ -46,7 +49,33 @@ export async function signOut(input?: SignOutInput): Promise { await clientSignOut(cognitoConfig); } - Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL); + let hasOAuthConfig; + + try { + assertOAuthConfig(cognitoConfig); + hasOAuthConfig = true; + } catch (err) { + hasOAuthConfig = false; + } + + if (hasOAuthConfig) { + const oAuthStore = new DefaultOAuthStore(defaultStorage); + oAuthStore.setAuthConfig(cognitoConfig); + const { type } = + (await handleOAuthSignOut(cognitoConfig, oAuthStore)) ?? {}; + if (type === 'error') { + throw new AuthError({ + name: OAUTH_SIGNOUT_EXCEPTION, + message: + 'An error occurred when attempting to log out from OAuth provider.', + }); + } + } else { + // complete sign out + tokenOrchestrator.clearTokens(); + await clearCredentials(); + Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL); + } } async function clientSignOut(cognitoConfig: CognitoUserPoolConfig) { @@ -65,14 +94,9 @@ async function clientSignOut(cognitoConfig: CognitoUserPoolConfig) { } ); } - - await handleOAuthSignOut(cognitoConfig); } catch (err) { // this shouldn't throw // TODO(v6): add logger message - } finally { - tokenOrchestrator.clearTokens(); - await clearCredentials(); } } @@ -89,74 +113,10 @@ async function globalSignOut(cognitoConfig: CognitoUserPoolConfig) { AccessToken: tokens.accessToken.toString(), } ); - - await handleOAuthSignOut(cognitoConfig); } catch (err) { // it should not throw // TODO(v6): add logger - } finally { - tokenOrchestrator.clearTokens(); - await clearCredentials(); - } -} - -async function handleOAuthSignOut(cognitoConfig: CognitoUserPoolConfig) { - try { - assertOAuthConfig(cognitoConfig); - } catch (err) { - // all good no oauth handling - return; - } - - const oauthStore = new DefaultOAuthStore(defaultStorage); - oauthStore.setAuthConfig(cognitoConfig); - const { isOAuthSignIn, preferPrivateSession } = - await oauthStore.loadOAuthSignIn(); - await oauthStore.clearOAuthData(); - - if (isOAuthSignIn) { - oAuthSignOutRedirect(cognitoConfig, preferPrivateSession); } } -async function oAuthSignOutRedirect( - authConfig: CognitoUserPoolConfig, - preferPrivateSession: boolean -) { - assertOAuthConfig(authConfig); - const { loginWith, userPoolClientId } = authConfig; - const { domain, redirectSignOut } = loginWith.oauth; - const signoutUri = getRedirectUrl(redirectSignOut); - const oAuthLogoutEndpoint = `https://${domain}/logout?${Object.entries({ - client_id: userPoolClientId, - logout_uri: encodeURIComponent(signoutUri), - }) - .map(([k, v]) => `${k}=${v}`) - .join('&')}`; - - // dispatchAuthEvent( - // 'oAuthSignOut', - // { oAuth: 'signOut' }, - // `Signing out from ${oAuthLogoutEndpoint}` - // ); - // logger.debug(`Signing out from ${oAuthLogoutEndpoint}`); - - await openAuthSession( - oAuthLogoutEndpoint, - redirectSignOut, - preferPrivateSession - ); -} - -function isSessionRevocable(token: JWT) { - if (token) { - try { - const { origin_jti } = token.payload; - return !!origin_jti; - } catch (err) { - // Nothing to do, token doesnt have origin_jti claim - } - } - - return false; -} +const isSessionRevocable = (token: JWT) => !!token?.payload?.origin_jti; diff --git a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts new file mode 100644 index 00000000000..0a904f3e5f9 --- /dev/null +++ b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts @@ -0,0 +1,14 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { clearCredentials, Hub } from '@aws-amplify/core'; +import { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils'; +import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; +import { tokenOrchestrator } from '../../tokenProvider'; + +export const completeOAuthSignOut = async (store: DefaultOAuthStore) => { + await store.clearOAuthData(); + tokenOrchestrator.clearTokens(); + await clearCredentials(); + Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL); +}; diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts new file mode 100644 index 00000000000..3cdb0315a28 --- /dev/null +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts @@ -0,0 +1,32 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { CognitoUserPoolConfig } from '@aws-amplify/core'; +import { OpenAuthSessionResult } from '../../../../utils/types'; +import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; +import { completeOAuthSignOut } from './completeOAuthSignOut'; +import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; + +export const handleOAuthSignOut = async ( + cognitoConfig: CognitoUserPoolConfig, + store: DefaultOAuthStore +): Promise => { + const { isOAuthSignIn, preferPrivateSession } = await store.loadOAuthSignIn(); + + if (isOAuthSignIn) { + const result = await oAuthSignOutRedirect( + cognitoConfig, + preferPrivateSession + ); + // If this was a private session, clear data and tokens regardless of what happened with logout + // endpoint. Otherwise, only do so if the logout endpoint was succesfully visited. + const shouldCompleteSignOut = + preferPrivateSession || result?.type === 'success'; + if (shouldCompleteSignOut) { + await completeOAuthSignOut(store); + } + return result; + } + + return completeOAuthSignOut(store); +}; diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts new file mode 100644 index 00000000000..a583af266fb --- /dev/null +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts @@ -0,0 +1,24 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { CognitoUserPoolConfig } from '@aws-amplify/core'; +import { OpenAuthSessionResult } from '../../../../utils/types'; +import { DefaultOAuthStore } from '../../utils/signInWithRedirectStore'; +import { completeOAuthSignOut } from './completeOAuthSignOut'; +import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; + +export const handleOAuthSignOut = async ( + cognitoConfig: CognitoUserPoolConfig, + store: DefaultOAuthStore +): Promise => { + const { isOAuthSignIn } = await store.loadOAuthSignIn(); + + // Clear everything before attempting to visted logout endpoint since the current application + // state could be wiped away on redirect + await completeOAuthSignOut(store); + + if (isOAuthSignIn) { + // On web, this will always end up being a void action + return oAuthSignOutRedirect(cognitoConfig); + } +}; diff --git a/packages/auth/src/providers/cognito/utils/oauth/index.ts b/packages/auth/src/providers/cognito/utils/oauth/index.ts index ebc87458430..519122a5d3e 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/index.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/index.ts @@ -3,3 +3,4 @@ export { generateCodeVerifier } from './generateCodeVerifier'; export { generateState } from './generateState'; +export { handleOAuthSignOut } from './handleOAuthSignOut'; diff --git a/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts new file mode 100644 index 00000000000..2cebfefc521 --- /dev/null +++ b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts @@ -0,0 +1,30 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { CognitoUserPoolConfig } from '@aws-amplify/core'; +import { assertOAuthConfig } from '@aws-amplify/core/internals/utils'; +import { openAuthSession } from '../../../../utils'; +import { OpenAuthSessionResult } from '../../../../utils/types'; +import { getRedirectUrl } from './getRedirectUrl'; + +export const oAuthSignOutRedirect = async ( + authConfig: CognitoUserPoolConfig, + preferPrivateSession: boolean = false +): Promise => { + assertOAuthConfig(authConfig); + const { loginWith, userPoolClientId } = authConfig; + const { domain, redirectSignOut } = loginWith.oauth; + const signoutUri = getRedirectUrl(redirectSignOut); + const oAuthLogoutEndpoint = `https://${domain}/logout?${Object.entries({ + client_id: userPoolClientId, + logout_uri: encodeURIComponent(signoutUri), + }) + .map(([k, v]) => `${k}=${v}`) + .join('&')}`; + + return openAuthSession( + oAuthLogoutEndpoint, + redirectSignOut, + preferPrivateSession + ); +}; From 5b52c3a08e651577ced89a31c24615374630ee57 Mon Sep 17 00:00:00 2001 From: Di Wu Date: Tue, 7 Nov 2023 16:23:26 -0800 Subject: [PATCH 38/45] fix(analytics): add options for configuring pinpoint event buffer (#12521) Co-authored-by: Jim Blanchard --- .../pinpoint/apis/flushEvents.test.ts | 11 +++--- .../pinpoint/utils/resolveConfig.test.ts | 4 ++ .../providers/pinpoint/apis/flushEvents.ts | 13 +++++-- .../src/providers/pinpoint/apis/record.ts | 7 +++- .../providers/pinpoint/utils/resolveConfig.ts | 6 ++- .../pinpoint/apis/flushEvents.test.ts | 26 ++++++++----- .../core/src/ServiceWorker/ServiceWorker.ts | 13 ++++++- .../providers/pinpoint/apis/flushEvents.ts | 39 ++++++++++++------- .../src/providers/pinpoint/apis/record.ts | 16 +++++--- .../src/providers/pinpoint/types/buffer.ts | 11 ++++-- .../src/providers/pinpoint/types/index.ts | 10 ++++- .../src/providers/pinpoint/types/pinpoint.ts | 10 +++-- .../pinpoint/utils/PinpointEventBuffer.ts | 6 +-- .../pinpoint/utils/getEventBuffer.ts | 30 ++++++++------ 14 files changed, 137 insertions(+), 65 deletions(-) diff --git a/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts b/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts index ace1313da1a..c89a31694f8 100644 --- a/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts @@ -6,7 +6,7 @@ import { resolveCredentials, } from '../../../../src/providers/pinpoint/utils'; import { config, credentials, identityId } from './testUtils/data'; -import { flushEvents } from '../../../../src/providers/pinpoint'; +import { flushEvents } from '../../../../src'; import { flushEvents as pinpointFlushEvents } from '@aws-amplify/core/internals/providers/pinpoint'; import { AnalyticsAction } from '@aws-amplify/core/internals/utils'; import { ConsoleLogger } from '@aws-amplify/core'; @@ -44,13 +44,12 @@ describe('Pinpoint API: flushEvents', () => { expect(mockResolveCredentials).toBeCalledTimes(1); await new Promise(process.nextTick); - expect(mockPinpointFlushEvents).toBeCalledWith( - config.appId, - config.region, + expect(mockPinpointFlushEvents).toBeCalledWith({ + ...config, credentials, identityId, - getAnalyticsUserAgentString(AnalyticsAction.Record) - ); + userAgentValue: getAnalyticsUserAgentString(AnalyticsAction.Record), + }); }); it('logs an error when credentials can not be fetched', async () => { diff --git a/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts b/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts index 5672b1c3c79..84e9ff30d06 100644 --- a/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts @@ -8,6 +8,10 @@ describe('Analytics Pinpoint Provider Util: resolveConfig', () => { const pinpointConfig = { appId: 'app-id', region: 'region', + bufferSize: 100, + flushSize: 10, + flushInterval: 50, + resendLimit: 3, }; // create spies const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); diff --git a/packages/analytics/src/providers/pinpoint/apis/flushEvents.ts b/packages/analytics/src/providers/pinpoint/apis/flushEvents.ts index ac41ee5fe95..4dc6425b77b 100644 --- a/packages/analytics/src/providers/pinpoint/apis/flushEvents.ts +++ b/packages/analytics/src/providers/pinpoint/apis/flushEvents.ts @@ -17,16 +17,21 @@ const logger = new ConsoleLogger('Analytics'); * this API may not be included in the flush. */ export const flushEvents = () => { - const { appId, region } = resolveConfig(); + const { appId, region, bufferSize, flushSize, flushInterval, resendLimit } = + resolveConfig(); resolveCredentials() .then(({ credentials, identityId }) => - flushEventsCore( + flushEventsCore({ appId, region, credentials, identityId, - getAnalyticsUserAgentString(AnalyticsAction.Record) - ) + bufferSize, + flushSize, + flushInterval, + resendLimit, + userAgentValue: getAnalyticsUserAgentString(AnalyticsAction.Record), + }) ) .catch(e => logger.warn('Failed to flush events', e)); }; diff --git a/packages/analytics/src/providers/pinpoint/apis/record.ts b/packages/analytics/src/providers/pinpoint/apis/record.ts index 8422d0ffb20..c9de36b02ee 100644 --- a/packages/analytics/src/providers/pinpoint/apis/record.ts +++ b/packages/analytics/src/providers/pinpoint/apis/record.ts @@ -49,7 +49,8 @@ const logger = new ConsoleLogger('Analytics'); * ``` */ export const record = (input: RecordInput): void => { - const { appId, region } = resolveConfig(); + const { appId, region, bufferSize, flushSize, flushInterval, resendLimit } = + resolveConfig(); if (!isAnalyticsEnabled()) { logger.debug('Analytics is disabled, event will not be recorded.'); @@ -74,6 +75,10 @@ export const record = (input: RecordInput): void => { identityId, region, userAgentValue: getAnalyticsUserAgentString(AnalyticsAction.Record), + bufferSize, + flushSize, + flushInterval, + resendLimit, }); }) .catch(e => { diff --git a/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts b/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts index e5b16a8641d..28d60e258cf 100644 --- a/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts @@ -11,8 +11,10 @@ import { * @internal */ export const resolveConfig = () => { - const { appId, region } = Amplify.getConfig().Analytics?.Pinpoint ?? {}; + const { appId, region, bufferSize, flushSize, flushInterval, resendLimit } = + Amplify.getConfig().Analytics?.Pinpoint ?? {}; assertValidationError(!!appId, AnalyticsValidationErrorCode.NoAppId); assertValidationError(!!region, AnalyticsValidationErrorCode.NoRegion); - return { appId, region }; + + return { appId, region, bufferSize, flushSize, flushInterval, resendLimit }; }; diff --git a/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts b/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts index 9f0549684c8..f324bc7054f 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts @@ -4,6 +4,12 @@ import { getEventBuffer } from '../../../../src/providers/pinpoint/utils/getEventBuffer'; import { flushEvents } from '../../../../src/providers/pinpoint'; import { appId, region, credentials, identityId } from '../testUtils/data'; +import { + BUFFER_SIZE, + FLUSH_INTERVAL, + FLUSH_SIZE, + RESEND_LIMIT, +} from '../../../../src/providers/pinpoint/utils/constants'; jest.mock('../../../../src/providers/pinpoint/utils/getEventBuffer'); @@ -22,15 +28,17 @@ describe('Pinpoint Provider API: flushEvents', () => { }); it('invokes flushAll on pinpoint buffer', () => { - flushEvents(appId, region, credentials, identityId); - expect(mockGetEventBuffer).toBeCalledWith( - expect.objectContaining({ - appId, - region, - credentials, - identityId, - }) - ); + flushEvents({ appId, region, credentials, identityId }); + expect(mockGetEventBuffer).toBeCalledWith({ + appId, + region, + credentials, + identityId, + bufferSize: BUFFER_SIZE, + flushInterval: FLUSH_INTERVAL, + flushSize: FLUSH_SIZE, + resendLimit: RESEND_LIMIT, + }); expect(mockFlushAll).toBeCalledTimes(1); }); }); diff --git a/packages/core/src/ServiceWorker/ServiceWorker.ts b/packages/core/src/ServiceWorker/ServiceWorker.ts index 12cc7b5e4fc..d7abfede978 100644 --- a/packages/core/src/ServiceWorker/ServiceWorker.ts +++ b/packages/core/src/ServiceWorker/ServiceWorker.ts @@ -211,7 +211,14 @@ export class ServiceWorkerClass { const currentState = this.serviceWorker.state; this._logger.debug(`ServiceWorker statechange: ${currentState}`); - const { appId, region } = Amplify.getConfig().Analytics?.Pinpoint ?? {}; + const { + appId, + region, + bufferSize, + flushInterval, + flushSize, + resendLimit, + } = Amplify.getConfig().Analytics?.Pinpoint ?? {}; const { credentials } = await fetchAuthSession(); if (appId && region && credentials) { @@ -221,6 +228,10 @@ export class ServiceWorkerClass { region, category: 'Core', credentials, + bufferSize, + flushInterval, + flushSize, + resendLimit, event: { name: 'ServiceWorker', attributes: { diff --git a/packages/core/src/providers/pinpoint/apis/flushEvents.ts b/packages/core/src/providers/pinpoint/apis/flushEvents.ts index 8d07b0591e9..95c8281771a 100644 --- a/packages/core/src/providers/pinpoint/apis/flushEvents.ts +++ b/packages/core/src/providers/pinpoint/apis/flushEvents.ts @@ -1,8 +1,9 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { AWSCredentials } from '../../../libraryUtils'; import { getEventBuffer } from '../utils/getEventBuffer'; +import { EventBufferConfig } from '../types/buffer'; +import { AuthSession } from '../../../singleton/Auth/types'; import { BUFFER_SIZE, FLUSH_INTERVAL, @@ -10,22 +11,34 @@ import { RESEND_LIMIT, } from '../utils/constants'; -export const flushEvents = ( - appId: string, - region: string, - credentials: AWSCredentials, - identityId?: string, - userAgentValue?: string -) => { +export type PinpointFlushEventsInput = Partial & { + appId: string; + region: string; + credentials: Required['credentials']; + identityId?: AuthSession['identityId']; + userAgentValue?: string; +}; + +export const flushEvents = ({ + appId, + region, + credentials, + bufferSize, + flushInterval, + flushSize, + resendLimit, + identityId, + userAgentValue, +}: PinpointFlushEventsInput) => { getEventBuffer({ appId, - bufferSize: BUFFER_SIZE, + region, credentials, - flushInterval: FLUSH_INTERVAL, - flushSize: FLUSH_SIZE, + bufferSize: bufferSize ?? BUFFER_SIZE, + flushInterval: flushInterval ?? FLUSH_INTERVAL, + flushSize: flushSize ?? FLUSH_SIZE, + resendLimit: resendLimit ?? RESEND_LIMIT, identityId, - region, - resendLimit: RESEND_LIMIT, userAgentValue, }).flushAll(); }; diff --git a/packages/core/src/providers/pinpoint/apis/record.ts b/packages/core/src/providers/pinpoint/apis/record.ts index caaca4e9ccb..10784514254 100644 --- a/packages/core/src/providers/pinpoint/apis/record.ts +++ b/packages/core/src/providers/pinpoint/apis/record.ts @@ -30,6 +30,10 @@ export const record = async ({ identityId, region, userAgentValue, + bufferSize, + flushInterval, + flushSize, + resendLimit, }: PinpointRecordInput): Promise => { let eventSession = session; const currentTime = new Date(); @@ -39,13 +43,13 @@ export const record = async ({ // Prepare event buffer if required const buffer = getEventBuffer({ appId, - bufferSize: BUFFER_SIZE, + region, credentials, - flushInterval: FLUSH_INTERVAL, - flushSize: FLUSH_SIZE, + bufferSize: bufferSize ?? BUFFER_SIZE, + flushInterval: flushInterval ?? FLUSH_INTERVAL, + flushSize: flushSize ?? FLUSH_SIZE, + resendLimit: resendLimit ?? RESEND_LIMIT, identityId, - region, - resendLimit: RESEND_LIMIT, userAgentValue, }); @@ -88,6 +92,6 @@ export const record = async ({ event, session: eventSession!, timestamp: timestampISOString, - resendLimit: RESEND_LIMIT, + resendLimit: resendLimit ?? RESEND_LIMIT, }); }; diff --git a/packages/core/src/providers/pinpoint/types/buffer.ts b/packages/core/src/providers/pinpoint/types/buffer.ts index 6652d4db3bb..28fd0582c44 100644 --- a/packages/core/src/providers/pinpoint/types/buffer.ts +++ b/packages/core/src/providers/pinpoint/types/buffer.ts @@ -5,14 +5,17 @@ import { AuthSession } from '../../../singleton/Auth/types'; import { PinpointAnalyticsEvent, PinpointSession } from './pinpoint'; export type EventBufferConfig = { - appId: string; bufferSize: number; - credentials: Required['credentials']; - identityId: AuthSession['identityId']; flushInterval: number; flushSize: number; - region: string; resendLimit: number; +}; + +export type PinpointEventBufferConfig = EventBufferConfig & { + appId: string; + region: string; + credentials: Required['credentials']; + identityId: AuthSession['identityId']; userAgentValue?: string; }; diff --git a/packages/core/src/providers/pinpoint/types/index.ts b/packages/core/src/providers/pinpoint/types/index.ts index 36f1992aecd..e8c2749ee66 100644 --- a/packages/core/src/providers/pinpoint/types/index.ts +++ b/packages/core/src/providers/pinpoint/types/index.ts @@ -2,4 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 export { UpdateEndpointException } from './errors'; -export * from './pinpoint'; +export { + PinpointUpdateEndpointInput, + PinpointRecordInput, + SupportedCategory, + PinpointProviderConfig, + PinpointSession, + PinpointServiceOptions, + PinpointAnalyticsEvent, +} from './pinpoint'; diff --git a/packages/core/src/providers/pinpoint/types/pinpoint.ts b/packages/core/src/providers/pinpoint/types/pinpoint.ts index 16210807554..91d97aaf273 100644 --- a/packages/core/src/providers/pinpoint/types/pinpoint.ts +++ b/packages/core/src/providers/pinpoint/types/pinpoint.ts @@ -3,6 +3,7 @@ import { AuthSession } from '../../../singleton/Auth/types'; import { UserProfile } from '../../../types'; +import { EventBufferConfig } from './buffer'; export type SupportedCategory = | 'Analytics' @@ -13,7 +14,7 @@ export type SupportedCategory = type SupportedChannelType = 'APNS' | 'APNS_SANDBOX' | 'GCM' | 'IN_APP'; export type PinpointProviderConfig = { - Pinpoint: { + Pinpoint: Partial & { appId: string; region: string; }; @@ -55,6 +56,7 @@ export type PinpointUpdateEndpointInput = PinpointCommonParameters & userProfile?: UserProfile; }; -export type PinpointRecordInput = PinpointCommonParameters & { - event: PinpointAnalyticsEvent; -}; +export type PinpointRecordInput = Partial & + PinpointCommonParameters & { + event: PinpointAnalyticsEvent; + }; diff --git a/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts b/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts index 616e0ca2767..55e7ce02be7 100644 --- a/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts +++ b/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts @@ -9,7 +9,7 @@ import { PutEventsOutput, } from '../../../awsClients/pinpoint'; import { - EventBufferConfig, + PinpointEventBufferConfig, BufferedEvent, BufferedEventMap, EventBuffer, @@ -22,13 +22,13 @@ const RETRYABLE_CODES = [429, 500]; const ACCEPTED_CODES = [202]; export class PinpointEventBuffer { - private _config: EventBufferConfig; + private _config: PinpointEventBufferConfig; private _interval: ReturnType | undefined = undefined; private _buffer: EventBuffer; private _pause = false; private _flush = false; - constructor(config: EventBufferConfig) { + constructor(config: PinpointEventBufferConfig) { this._buffer = []; this._config = config; diff --git a/packages/core/src/providers/pinpoint/utils/getEventBuffer.ts b/packages/core/src/providers/pinpoint/utils/getEventBuffer.ts index c2778359361..0f737391915 100644 --- a/packages/core/src/providers/pinpoint/utils/getEventBuffer.ts +++ b/packages/core/src/providers/pinpoint/utils/getEventBuffer.ts @@ -3,32 +3,40 @@ import { EventBufferConfig } from '../types/buffer'; import { PinpointEventBuffer } from './PinpointEventBuffer'; -import { BUFFER_SIZE, FLUSH_INTERVAL, FLUSH_SIZE, RESEND_LIMIT } from './constants'; +import { AuthSession } from '../../../singleton/Auth/types'; // Map of buffers by region -> appId const eventBufferMap: Record> = {}; +export type GetEventBufferInput = EventBufferConfig & { + appId: string; + region: string; + credentials: Required['credentials']; + identityId?: AuthSession['identityId']; + userAgentValue?: string; +}; + /** * Returns a PinpointEventBuffer instance for the specified region & app ID, creating one if it does not yet exist. - * + * * @internal */ export const getEventBuffer = ({ appId, - bufferSize = BUFFER_SIZE, + region, credentials, - flushInterval = FLUSH_INTERVAL, - flushSize = FLUSH_SIZE, + bufferSize, + flushInterval, + flushSize, + resendLimit, identityId, - region, - resendLimit = RESEND_LIMIT, - userAgentValue -}: EventBufferConfig): PinpointEventBuffer => { + userAgentValue, +}: GetEventBufferInput): PinpointEventBuffer => { if (eventBufferMap[region]?.[appId]) { const buffer = eventBufferMap[region][appId]; /* - If the identity has changed flush out the buffer and create a new instance. The old instance will be garbage + If the identity has changed flush out the buffer and create a new instance. The old instance will be garbage collected. */ if (buffer.identityHasChanged(identityId)) { @@ -47,7 +55,7 @@ export const getEventBuffer = ({ identityId, region, resendLimit, - userAgentValue + userAgentValue, }); if (!eventBufferMap[region]) { From 0138c28239915e58457aae6c202e9cbfb6861d3d Mon Sep 17 00:00:00 2001 From: Chris F <5827964+cshfang@users.noreply.github.com> Date: Wed, 8 Nov 2023 13:11:12 -0800 Subject: [PATCH 39/45] Clean up references to ConsoleLogger (#12499) Co-authored-by: Jim Blanchard --- packages/core/__tests__/utils.test.ts | 4 +- .../core/src/Cache/StorageCache.native.ts | 4 +- packages/core/src/Cache/StorageCache.ts | 4 +- packages/core/src/Cache/StorageCacheCommon.ts | 4 +- packages/core/src/Hub/index.ts | 4 +- packages/core/src/I18n/I18n.ts | 5 +-- packages/core/src/I18n/index.ts | 4 +- packages/core/src/Logger/ConsoleLogger.ts | 37 +++++++------------ packages/core/src/Logger/index.ts | 2 +- packages/core/src/Logger/logger-interface.ts | 12 ------ .../src/{types/logging.ts => Logger/types.ts} | 16 ++++++++ .../src/Reachability/Reachability.native.ts | 4 +- .../core/src/ServiceWorker/ServiceWorker.ts | 4 +- packages/core/src/parseAWSExports.ts | 4 +- .../pinpoint/utils/PinpointEventBuffer.ts | 4 +- packages/core/src/types/index.ts | 1 - .../getClientInfo/getClientInfo.android.ts | 4 +- .../utils/getClientInfo/getClientInfo.ios.ts | 4 +- .../src/utils/getClientInfo/getClientInfo.ts | 4 +- packages/core/src/utils/retry/retry.ts | 4 +- packages/datastore/docs/getting-started.md | 2 +- packages/predictions/src/Predictions.ts | 4 +- .../AmazonAIConvertPredictionsProvider.ts | 8 +--- .../AmazonAIIdentifyPredictionsProvider.ts | 8 +--- packages/pubsub/src/Providers/MqttOverWS.ts | 4 +- packages/pubsub/src/Providers/PubSub.ts | 4 +- 26 files changed, 72 insertions(+), 87 deletions(-) delete mode 100644 packages/core/src/Logger/logger-interface.ts rename packages/core/src/{types/logging.ts => Logger/types.ts} (65%) diff --git a/packages/core/__tests__/utils.test.ts b/packages/core/__tests__/utils.test.ts index a57207823ee..128e5eebbf5 100644 --- a/packages/core/__tests__/utils.test.ts +++ b/packages/core/__tests__/utils.test.ts @@ -8,10 +8,10 @@ import { } from '../src/utils'; import { Reachability as ReachabilityNative } from '../src/Reachability/Reachability.native'; import { Reachability } from '../src/Reachability/Reachability'; -import { ConsoleLogger as Logger } from '../src/Logger'; +import { ConsoleLogger } from '../src/Logger'; import { DateUtils } from '../src/Signer/DateUtils'; -Logger.LOG_LEVEL = 'DEBUG'; +ConsoleLogger.LOG_LEVEL = 'DEBUG'; describe('Util', () => { beforeEach(() => {}); diff --git a/packages/core/src/Cache/StorageCache.native.ts b/packages/core/src/Cache/StorageCache.native.ts index c8d5e57bd50..fa703d185c3 100644 --- a/packages/core/src/Cache/StorageCache.native.ts +++ b/packages/core/src/Cache/StorageCache.native.ts @@ -2,13 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAsyncStorage } from '@aws-amplify/react-native'; -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { defaultConfig } from './constants'; import { StorageCacheCommon } from './StorageCacheCommon'; import { Cache, CacheConfig } from './types'; import { getCurrentSizeKey, getCurrentTime } from './utils'; -const logger = new Logger('StorageCache'); +const logger = new ConsoleLogger('StorageCache'); const AsyncStorage = loadAsyncStorage(); /* diff --git a/packages/core/src/Cache/StorageCache.ts b/packages/core/src/Cache/StorageCache.ts index 406ca7bc76b..b80c87715f8 100644 --- a/packages/core/src/Cache/StorageCache.ts +++ b/packages/core/src/Cache/StorageCache.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { KeyValueStorage } from '../storage/KeyValueStorage'; import { getLocalStorageWithFallback } from '../storage/utils'; import { defaultConfig } from './constants'; @@ -9,7 +9,7 @@ import { StorageCacheCommon } from './StorageCacheCommon'; import { Cache, CacheConfig } from './types'; import { getCurrentSizeKey, getCurrentTime } from './utils'; -const logger = new Logger('Cache'); +const logger = new ConsoleLogger('StorageCache'); /** * Customized storage based on the SessionStorage or LocalStorage with LRU implemented diff --git a/packages/core/src/Cache/StorageCacheCommon.ts b/packages/core/src/Cache/StorageCacheCommon.ts index 126a0fb7462..860ee87d666 100644 --- a/packages/core/src/Cache/StorageCacheCommon.ts +++ b/packages/core/src/Cache/StorageCacheCommon.ts @@ -1,14 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { KeyValueStorageInterface } from '../types'; import { currentSizeKey, defaultConfig } from './constants'; import { CacheConfig, CacheItem, CacheItemOptions } from './types'; import { getCurrentSizeKey, getCurrentTime, getByteLength } from './utils'; import { assert, CacheErrorCode } from './utils/errorHelpers'; -const logger = new Logger('StorageCache'); +const logger = new ConsoleLogger('StorageCache'); /** * Initialization of the cache diff --git a/packages/core/src/Hub/index.ts b/packages/core/src/Hub/index.ts index 6f6cb907140..e1808a345d9 100644 --- a/packages/core/src/Hub/index.ts +++ b/packages/core/src/Hub/index.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { NO_HUBCALLBACK_PROVIDED_EXCEPTION } from '../constants'; import { AmplifyError } from '../errors'; import { @@ -21,7 +21,7 @@ export const AMPLIFY_SYMBOL = ( : '@@amplify_default' ) as Symbol; -const logger = new Logger('Hub'); +const logger = new ConsoleLogger('Hub'); export class HubClass { name: string; diff --git a/packages/core/src/I18n/I18n.ts b/packages/core/src/I18n/I18n.ts index ee35c63d94d..91026ee18ba 100644 --- a/packages/core/src/I18n/I18n.ts +++ b/packages/core/src/I18n/I18n.ts @@ -1,11 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../Logger'; -import { Amplify } from '../singleton'; +import { ConsoleLogger } from '../Logger'; import { I18nConfig } from './types'; -const logger = new Logger('I18n'); +const logger = new ConsoleLogger('I18n'); /** * Language translation utility. diff --git a/packages/core/src/I18n/index.ts b/packages/core/src/I18n/index.ts index 5a1b88ef443..97740114877 100644 --- a/packages/core/src/I18n/index.ts +++ b/packages/core/src/I18n/index.ts @@ -3,11 +3,11 @@ import { I18n as I18nClass } from './I18n'; -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { I18nConfig } from './types'; import { assert, I18nErrorCode } from './errorHelpers'; -const logger = new Logger('I18n'); +const logger = new ConsoleLogger('I18n'); let _config: I18nConfig = { language: null }; let _i18n: I18nClass | null = null; diff --git a/packages/core/src/Logger/ConsoleLogger.ts b/packages/core/src/Logger/ConsoleLogger.ts index adc824c30ed..a55e034173d 100644 --- a/packages/core/src/Logger/ConsoleLogger.ts +++ b/packages/core/src/Logger/ConsoleLogger.ts @@ -1,9 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { LoggingProvider, InputLogEvent } from '../types'; +import { InputLogEvent, Logger, LoggingProvider, LogType } from './types'; import { AWS_CLOUDWATCH_CATEGORY } from '../constants'; -import { Logger } from './logger-interface'; const LOG_LEVELS: Record = { VERBOSE: 1, @@ -13,21 +12,13 @@ const LOG_LEVELS: Record = { ERROR: 5, }; -export enum LOG_TYPE { - DEBUG = 'DEBUG', - ERROR = 'ERROR', - INFO = 'INFO', - WARN = 'WARN', - VERBOSE = 'VERBOSE', -} - /** * Write logs * @class Logger */ export class ConsoleLogger implements Logger { name: string; - level: LOG_TYPE | string; + level: LogType | string; private _pluggables: LoggingProvider[]; private _config?: object; @@ -35,13 +26,13 @@ export class ConsoleLogger implements Logger { * @constructor * @param {string} name - Name of the logger */ - constructor(name: string, level: LOG_TYPE | string = LOG_TYPE.WARN) { + constructor(name: string, level: LogType | string = LogType.WARN) { this.name = name; this.level = level; this._pluggables = []; } - static LOG_LEVEL = null; + static LOG_LEVEL: string | null = null; _padding(n: number) { return n < 10 ? '0' + n : '' + n; @@ -70,10 +61,10 @@ export class ConsoleLogger implements Logger { * Write log * @method * @memeberof Logger - * @param {LOG_TYPE|string} type - log type, default INFO + * @param {LogType|string} type - log type, default INFO * @param {string|object} msg - Logging message or object */ - _log(type: LOG_TYPE | string, ...msg: any) { + _log(type: LogType | string, ...msg: any) { let logger_level_name = this.level; if (ConsoleLogger.LOG_LEVEL) { logger_level_name = ConsoleLogger.LOG_LEVEL; @@ -89,10 +80,10 @@ export class ConsoleLogger implements Logger { } let log = console.log.bind(console); - if (type === LOG_TYPE.ERROR && console.error) { + if (type === LogType.ERROR && console.error) { log = console.error.bind(console); } - if (type === LOG_TYPE.WARN && console.warn) { + if (type === LogType.WARN && console.warn) { log = console.warn.bind(console); } @@ -130,7 +121,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ log(...msg: any) { - this._log(LOG_TYPE.INFO, ...msg); + this._log(LogType.INFO, ...msg); } /** @@ -140,7 +131,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ info(...msg: any) { - this._log(LOG_TYPE.INFO, ...msg); + this._log(LogType.INFO, ...msg); } /** @@ -150,7 +141,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ warn(...msg: any) { - this._log(LOG_TYPE.WARN, ...msg); + this._log(LogType.WARN, ...msg); } /** @@ -160,7 +151,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ error(...msg: any) { - this._log(LOG_TYPE.ERROR, ...msg); + this._log(LogType.ERROR, ...msg); } /** @@ -170,7 +161,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ debug(...msg: any) { - this._log(LOG_TYPE.DEBUG, ...msg); + this._log(LogType.DEBUG, ...msg); } /** @@ -180,7 +171,7 @@ export class ConsoleLogger implements Logger { * @param {string|object} msg - Logging message or object */ verbose(...msg: any) { - this._log(LOG_TYPE.VERBOSE, ...msg); + this._log(LogType.VERBOSE, ...msg); } addPluggable(pluggable: LoggingProvider) { diff --git a/packages/core/src/Logger/index.ts b/packages/core/src/Logger/index.ts index 8761b7bd354..dd924dca47d 100644 --- a/packages/core/src/Logger/index.ts +++ b/packages/core/src/Logger/index.ts @@ -1,4 +1,4 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -export { ConsoleLogger, LOG_TYPE } from './ConsoleLogger'; +export { ConsoleLogger } from './ConsoleLogger'; diff --git a/packages/core/src/Logger/logger-interface.ts b/packages/core/src/Logger/logger-interface.ts deleted file mode 100644 index 02632d441d4..00000000000 --- a/packages/core/src/Logger/logger-interface.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { LoggingProvider } from '../types'; - -export interface Logger { - debug(msg: string): void; - info(msg: string): void; - warn(msg: string): void; - error(msg: string): void; - addPluggable(pluggable: LoggingProvider): void; -} diff --git a/packages/core/src/types/logging.ts b/packages/core/src/Logger/types.ts similarity index 65% rename from packages/core/src/types/logging.ts rename to packages/core/src/Logger/types.ts index 8a0a08c6fcf..6967d1d923b 100644 --- a/packages/core/src/types/logging.ts +++ b/packages/core/src/Logger/types.ts @@ -22,3 +22,19 @@ export interface LoggingProvider { // take logs and push to provider pushLogs(logs: InputLogEvent[]): void; } + +export interface Logger { + debug(msg: string): void; + info(msg: string): void; + warn(msg: string): void; + error(msg: string): void; + addPluggable(pluggable: LoggingProvider): void; +} + +export enum LogType { + DEBUG = 'DEBUG', + ERROR = 'ERROR', + INFO = 'INFO', + WARN = 'WARN', + VERBOSE = 'VERBOSE', +} diff --git a/packages/core/src/Reachability/Reachability.native.ts b/packages/core/src/Reachability/Reachability.native.ts index c459657ab24..dda3bd1770e 100644 --- a/packages/core/src/Reachability/Reachability.native.ts +++ b/packages/core/src/Reachability/Reachability.native.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { Observable } from 'rxjs'; import { loadNetInfo } from '@aws-amplify/react-native'; -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { NetworkStatus } from './types'; -const logger = new Logger('Reachability', 'DEBUG'); +const logger = new ConsoleLogger('Reachability', 'DEBUG'); export class Reachability { networkMonitor( diff --git a/packages/core/src/ServiceWorker/ServiceWorker.ts b/packages/core/src/ServiceWorker/ServiceWorker.ts index d7abfede978..6683b8a4fc1 100644 --- a/packages/core/src/ServiceWorker/ServiceWorker.ts +++ b/packages/core/src/ServiceWorker/ServiceWorker.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../Logger'; +import { ConsoleLogger } from '../Logger'; import { isBrowser } from '../utils'; import { AmplifyError } from '../errors'; import { assert, ServiceWorkerErrorCode } from './errorHelpers'; @@ -35,7 +35,7 @@ export class ServiceWorkerClass { private _subscription?: PushSubscription; // The AWS Amplify logger - private _logger: Logger = new Logger('ServiceWorker'); + private _logger: ConsoleLogger = new ConsoleLogger('ServiceWorker'); constructor() {} diff --git a/packages/core/src/parseAWSExports.ts b/packages/core/src/parseAWSExports.ts index 51719f0410e..96cb0afc870 100644 --- a/packages/core/src/parseAWSExports.ts +++ b/packages/core/src/parseAWSExports.ts @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from './Logger'; +import { ConsoleLogger } from './Logger'; import { OAuthConfig, AuthConfigUserAttributes, @@ -8,7 +8,7 @@ import { } from './singleton/Auth/types'; import { ResourcesConfig } from './singleton/types'; -const logger = new Logger('parseAWSExports'); +const logger = new ConsoleLogger('parseAWSExports'); const authTypeMapping: Record = { API_KEY: 'apiKey', diff --git a/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts b/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts index 55e7ce02be7..f833e01feca 100644 --- a/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts +++ b/packages/core/src/providers/pinpoint/utils/PinpointEventBuffer.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../../../Logger'; +import { ConsoleLogger } from '../../../Logger'; import { EventsBatch, putEvents, @@ -17,7 +17,7 @@ import { import { AuthSession } from '../../../singleton/Auth/types'; import { isAppInForeground } from './isAppInForeground'; -const logger = new Logger('PinpointEventBuffer'); +const logger = new ConsoleLogger('PinpointEventBuffer'); const RETRYABLE_CODES = [429, 500]; const ACCEPTED_CODES = [202]; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 0a250d64321..582907f7acd 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -3,5 +3,4 @@ export * from './core'; export * from './errors'; -export * from './logging'; export * from './storage'; diff --git a/packages/core/src/utils/getClientInfo/getClientInfo.android.ts b/packages/core/src/utils/getClientInfo/getClientInfo.android.ts index cb842903ca8..24626eef935 100644 --- a/packages/core/src/utils/getClientInfo/getClientInfo.android.ts +++ b/packages/core/src/utils/getClientInfo/getClientInfo.android.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore: missing type definition import { Platform, Dimensions } from 'react-native'; -import { ConsoleLogger as Logger } from '../../Logger'; +import { ConsoleLogger } from '../../Logger'; -const logger = new Logger('DeviceInfo'); +const logger = new ConsoleLogger('getClientInfo'); export const getClientInfo = () => { const dim = Dimensions.get('screen'); diff --git a/packages/core/src/utils/getClientInfo/getClientInfo.ios.ts b/packages/core/src/utils/getClientInfo/getClientInfo.ios.ts index de2edb02a2e..215b63e1fec 100644 --- a/packages/core/src/utils/getClientInfo/getClientInfo.ios.ts +++ b/packages/core/src/utils/getClientInfo/getClientInfo.ios.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore: missing type definition import { Platform, Dimensions } from 'react-native'; -import { ConsoleLogger as Logger } from '../../Logger'; +import { ConsoleLogger } from '../../Logger'; -const logger = new Logger('DeviceInfo'); +const logger = new ConsoleLogger('getClientInfo'); export const getClientInfo = () => { const dim = Dimensions.get('screen'); diff --git a/packages/core/src/utils/getClientInfo/getClientInfo.ts b/packages/core/src/utils/getClientInfo/getClientInfo.ts index ca573f397a6..b729e31de17 100644 --- a/packages/core/src/utils/getClientInfo/getClientInfo.ts +++ b/packages/core/src/utils/getClientInfo/getClientInfo.ts @@ -1,8 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '../../Logger'; +import { ConsoleLogger } from '../../Logger'; -const logger = new Logger('ClientDevice_Browser'); +const logger = new ConsoleLogger('getClientInfo'); export function getClientInfo() { if (typeof window === 'undefined') { diff --git a/packages/core/src/utils/retry/retry.ts b/packages/core/src/utils/retry/retry.ts index 250a1464819..dfa27f51c1d 100644 --- a/packages/core/src/utils/retry/retry.ts +++ b/packages/core/src/utils/retry/retry.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { DelayFunction } from '../../types'; -import { ConsoleLogger as Logger } from '../../Logger/ConsoleLogger'; +import { ConsoleLogger } from '../../Logger/ConsoleLogger'; import { isNonRetryableError } from './isNonRetryableError'; -const logger = new Logger('Util'); +const logger = new ConsoleLogger('retryUtil'); /** * @private diff --git a/packages/datastore/docs/getting-started.md b/packages/datastore/docs/getting-started.md index 9e703789395..4334fcb0692 100644 --- a/packages/datastore/docs/getting-started.md +++ b/packages/datastore/docs/getting-started.md @@ -16,7 +16,7 @@ 6. While interacting with your app, examine the IndexedDB tables (Application > IndexedDB within Chrome dev tools): 1. Check out the different stores in IDB that get created for your schema. Note the internal stores prefixed with sync_, and the stores corresponding to your models prefixed with user_. 2. Familiarize yourself with how actions taken in the UI affect the data stored in IDB. This may be easier to do while throttling the network connection. You'll be able to see how outgoing mutations first get persisted into the corresponding store, then added to the mutation queue / outbox (sync_MutationEvent), and then updated in the store with data from AppSync. -7. Turn on DEBUG logging (`Amplify.Logger.LOG_LEVEL = "DEBUG";`) at the root of your project, and inspect the logs in the console while using your app. Additionally, [enable hub events](https://docs.amplify.aws/lib/datastore/datastore-events/q/platform/js#usage) for DataStore. +7. Turn on DEBUG logging (`ConsoleLogger.LOG_LEVEL = "DEBUG";`) at the root of your project, and inspect the logs in the console while using your app. Additionally, [enable hub events](https://docs.amplify.aws/lib/datastore/datastore-events/q/platform/js#usage) for DataStore. 8. The best way to understand DataStore events is to place several debuggers or breakpoints throughout DataStore. - With logging / Hub events enabled, you can see what operations DataStore is performing (i.e. start, sync, etc.) as you step through with the debugger. 9. Testing offline scenerios / concurrent user sessions is a useful way to test the full functionality of DataStore, and to fully understand how the sync process actually works. diff --git a/packages/predictions/src/Predictions.ts b/packages/predictions/src/Predictions.ts index 2df7d658f60..97d699abb14 100644 --- a/packages/predictions/src/Predictions.ts +++ b/packages/predictions/src/Predictions.ts @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger as Logger } from '@aws-amplify/core'; +import { ConsoleLogger } from '@aws-amplify/core'; import { AmazonAIConvertPredictionsProvider, AmazonAIIdentifyPredictionsProvider, @@ -23,7 +23,7 @@ import { TranslateTextOutput, } from './types'; -const logger = new Logger('Predictions'); +const logger = new ConsoleLogger('Predictions'); export class PredictionsClass { private convertProvider = new AmazonAIConvertPredictionsProvider(); diff --git a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts index e2da48c0651..77beadfd21d 100644 --- a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts @@ -1,10 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { - Amplify, - ConsoleLogger as Logger, - fetchAuthSession, -} from '@aws-amplify/core'; +import { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core'; import { AWSCredentials, Category, @@ -40,7 +36,7 @@ import { isValidConvertInput, } from '../types'; -const logger = new Logger('AmazonAIConvertPredictionsProvider'); +const logger = new ConsoleLogger('AmazonAIConvertPredictionsProvider'); const eventBuilder = new EventStreamCodec(toUtf8, fromUtf8); const LANGUAGES_CODE_IN_8KHZ = ['fr-FR', 'en-AU', 'en-GB', 'fr-CA']; diff --git a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts index 057d8915565..006f68a1d7a 100644 --- a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts @@ -1,10 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { - Amplify, - ConsoleLogger as Logger, - fetchAuthSession, -} from '@aws-amplify/core'; +import { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core'; import { Category, PredictionsAction, @@ -66,7 +62,7 @@ import { } from './IdentifyTextUtils'; import { blobToArrayBuffer, makeCamelCase, makeCamelCaseArray } from './Utils'; -const logger = new Logger('AmazonAIIdentifyPredictionsProvider'); +const logger = new ConsoleLogger('AmazonAIIdentifyPredictionsProvider'); export class AmazonAIIdentifyPredictionsProvider { private rekognitionClient?: RekognitionClient; diff --git a/packages/pubsub/src/Providers/MqttOverWS.ts b/packages/pubsub/src/Providers/MqttOverWS.ts index 1d3444036d9..ea943b88bbb 100644 --- a/packages/pubsub/src/Providers/MqttOverWS.ts +++ b/packages/pubsub/src/Providers/MqttOverWS.ts @@ -14,7 +14,7 @@ import { PublishInput, SubscribeInput, } from '../types/PubSub'; -import { Hub, HubPayload, ConsoleLogger as Logger } from '@aws-amplify/core'; +import { Hub, HubPayload, ConsoleLogger } from '@aws-amplify/core'; import { amplifyUuid } from '@aws-amplify/core/internals/utils'; import { ConnectionStateMonitor, @@ -26,7 +26,7 @@ import { } from '../utils/ReconnectionMonitor'; import { AMPLIFY_SYMBOL, CONNECTION_STATE_CHANGE } from './constants'; -const logger = new Logger('MqttOverWS'); +const logger = new ConsoleLogger('MqttOverWS'); export function mqttTopicMatch(filter: string, topic: string) { const filterArray = filter.split('/'); diff --git a/packages/pubsub/src/Providers/PubSub.ts b/packages/pubsub/src/Providers/PubSub.ts index 78a7eec9141..5750d0a1940 100644 --- a/packages/pubsub/src/Providers/PubSub.ts +++ b/packages/pubsub/src/Providers/PubSub.ts @@ -8,8 +8,8 @@ import { PublishInput, SubscribeInput, } from '../types/PubSub'; -import { ConsoleLogger as Logger } from '@aws-amplify/core'; -const logger = new Logger('AbstractPubSubProvider'); +import { ConsoleLogger } from '@aws-amplify/core'; +const logger = new ConsoleLogger('AbstractPubSubProvider'); export abstract class AbstractPubSub implements PubSubBase From bd73367b5461ebba33d1e30ffae7940095683044 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 8 Nov 2023 15:17:48 -0800 Subject: [PATCH 40/45] chore(auth|aws-amplify): fix instance naming (use camel-case) --- .../__tests__/providers/cognito/autoSignIn.test.ts | 4 ++-- .../cognito/confirmSignInHappyCases.test.ts | 4 ++-- .../providers/cognito/fetchAuthSession.test.ts | 8 ++++---- .../providers/cognito/signInErrorCases.test.ts | 4 ++-- .../providers/cognito/signInStateManagement.test.ts | 4 ++-- .../providers/cognito/signInWithCustomAuth.test.ts | 4 ++-- .../cognito/signInWithCustomSRPAuth.test.ts | 4 ++-- .../providers/cognito/signInWithSRP.test.ts | 4 ++-- .../providers/cognito/signInWithUserPassword.test.ts | 4 ++-- .../src/providers/cognito/apis/signInWithRedirect.ts | 4 ++-- packages/auth/src/providers/cognito/index.ts | 2 +- .../src/providers/cognito/tokenProvider/index.ts | 4 ++-- packages/aws-amplify/__tests__/exports.test.ts | 2 +- packages/aws-amplify/__tests__/initSingleton.test.ts | 12 ++++++------ packages/aws-amplify/src/initSingleton.ts | 8 ++++---- 15 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts index 4155a788c28..8765a94aa72 100644 --- a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts +++ b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, signUp, } from '../../../src/providers/cognito'; import { autoSignIn } from '../../../src/providers/cognito/apis/autoSignIn'; @@ -20,7 +20,7 @@ const authConfig = { userPoolId: 'us-west-2_zzzzz', }, }; -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); Amplify.configure({ Auth: authConfig, }); diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts index 48c876584d0..ce6cc7457af 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts @@ -11,7 +11,7 @@ import { import * as signInHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; @@ -34,7 +34,7 @@ describe('confirmSignIn API happy path cases', () => { const password = authAPITestParams.user1.password; beforeEach(async () => { - CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); + cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); handleChallengeNameSpy = jest .spyOn(signInHelpers, 'handleChallengeName') diff --git a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts index 660f075da57..fd32724b43f 100644 --- a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts @@ -2,7 +2,7 @@ import { Amplify } from '@aws-amplify/core'; import { fetchAuthSession } from '@aws-amplify/core'; import { CognitoAWSCredentialsAndIdentityIdProvider, - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, cognitoCredentialsProvider, } from '../../../src/providers/cognito'; import { decodeJWT } from '@aws-amplify/core/internals/utils'; @@ -43,7 +43,7 @@ describe('fetchAuthSession behavior for IdentityPools only', () => { { Auth: { credentialsProvider: cognitoCredentialsProvider, - tokenProvider: CognitoUserPoolsTokenProvider, + tokenProvider: cognitoUserPoolsTokenProvider, }, } ); @@ -78,7 +78,7 @@ describe.only('fetchAuthSession behavior for UserPools only', () => { let tokenProviderSpy; beforeEach(() => { tokenProviderSpy = jest - .spyOn(CognitoUserPoolsTokenProvider, 'getTokens') + .spyOn(cognitoUserPoolsTokenProvider, 'getTokens') .mockImplementation(async () => { return { accessToken: decodeJWT( @@ -104,7 +104,7 @@ describe.only('fetchAuthSession behavior for UserPools only', () => { { Auth: { credentialsProvider: cognitoCredentialsProvider, - tokenProvider: CognitoUserPoolsTokenProvider, + tokenProvider: cognitoUserPoolsTokenProvider, }, } ); diff --git a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts index fa948beb54c..e050dfab6a1 100644 --- a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts @@ -7,7 +7,7 @@ import { authAPITestParams } from './testUtils/authApiTestParams'; import { signIn, getCurrentUser, - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, } from '../../../src/providers/cognito'; import { InitiateAuthException } from '../../../src/providers/cognito/types/errors'; import { Amplify } from 'aws-amplify'; @@ -27,7 +27,7 @@ const authConfig = { Amplify.configure({ Auth: authConfig, }); -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); describe('signIn API error path cases:', () => { test('signIn API should throw a validation AuthError when a user is already signed-in', async () => { diff --git a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts index 48647dacb82..9cb49b83b29 100644 --- a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts @@ -7,7 +7,7 @@ import * as signInHelpers from '../../../src/providers/cognito/utils/signInHelpe import { signInStore } from '../../../src/providers/cognito/utils/signInStore'; import { Amplify } from '@aws-amplify/core'; import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; -import { CognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; +import { cognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); // getCurrentUser is mocked so Hub is able to dispatch a mocked AuthUser @@ -26,7 +26,7 @@ describe('local sign-in state management tests', () => { }; beforeEach(() => { - CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); + cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); }); test('local state management should return state after signIn returns a ChallengeName', async () => { diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts index b12dd7db71b..567a706b82f 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts @@ -8,7 +8,7 @@ import { signInWithCustomAuth } from '../../../src/providers/cognito/apis/signIn import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signInHelpers'; import { InitiateAuthCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; @@ -23,7 +23,7 @@ const authConfig = { Amplify.configure({ Auth: authConfig, }); -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); describe('signIn API happy path cases', () => { let handleCustomAuthFlowWithoutSRPSpy; diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts index e91dce6ddf0..c49983466f9 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts @@ -8,7 +8,7 @@ import { signInWithCustomSRPAuth } from '../../../src/providers/cognito/apis/sig import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { Amplify } from 'aws-amplify'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; @@ -19,7 +19,7 @@ const authConfig = { userPoolId: 'us-west-2_zzzzz', }, }; -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); Amplify.configure({ Auth: authConfig, }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts index f200e53b157..200f1659164 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts @@ -8,7 +8,7 @@ import * as initiateAuthHelpers from '../../../src/providers/cognito/utils/signI import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { Amplify } from 'aws-amplify'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import { AuthError } from '../../../src'; @@ -22,7 +22,7 @@ const authConfig = { }, }; -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); Amplify.configure({ Auth: authConfig, }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts index 0a437425c4a..2fd5e0b6fd1 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts @@ -8,7 +8,7 @@ import { signInWithUserPassword } from '../../../src/providers/cognito/apis/sign import { RespondToAuthChallengeCommandOutput } from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/types'; import { Amplify } from 'aws-amplify'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, tokenOrchestrator, } from '../../../src/providers/cognito/tokenProvider'; import * as clients from '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider'; @@ -20,7 +20,7 @@ const authConfig = { }, }; -CognitoUserPoolsTokenProvider.setAuthConfig(authConfig); +cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); Amplify.configure({ Auth: authConfig, }); diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index a5004e499bc..76f99752cf1 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -15,7 +15,7 @@ import { AmplifyUrl, } from '@aws-amplify/core/internals/utils'; import { cacheCognitoTokens } from '../tokenProvider/cacheTokens'; -import { CognitoUserPoolsTokenProvider } from '../tokenProvider'; +import { cognitoUserPoolsTokenProvider } from '../tokenProvider'; import { cognitoHostedUIIdentityProviderMap } from '../types/models'; import { DefaultOAuthStore } from '../utils/signInWithRedirectStore'; import { AuthError } from '../../../errors/AuthError'; @@ -472,7 +472,7 @@ const invokeAndClearPromise = () => { }; isBrowser() && - CognitoUserPoolsTokenProvider.setWaitForInflightOAuth( + cognitoUserPoolsTokenProvider.setWaitForInflightOAuth( () => new Promise(async (res, _rej) => { if (!(await store.loadOAuthInFlight())) { diff --git a/packages/auth/src/providers/cognito/index.ts b/packages/auth/src/providers/cognito/index.ts index 1043a5ae7ae..9229b376083 100644 --- a/packages/auth/src/providers/cognito/index.ts +++ b/packages/auth/src/providers/cognito/index.ts @@ -75,7 +75,7 @@ export { DefaultIdentityIdStore, } from './credentialsProvider'; export { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, CognitoUserPoolTokenProviderType, TokenOrchestrator, DefaultTokenStore, diff --git a/packages/auth/src/providers/cognito/tokenProvider/index.ts b/packages/auth/src/providers/cognito/tokenProvider/index.ts index 3054ca51596..bc2ac570b53 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/index.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/index.ts @@ -42,11 +42,11 @@ class CognitoUserPoolsTokenProviderClass } } -export const CognitoUserPoolsTokenProvider = +export const cognitoUserPoolsTokenProvider = new CognitoUserPoolsTokenProviderClass(); export const tokenOrchestrator = - CognitoUserPoolsTokenProvider.tokenOrchestrator; + cognitoUserPoolsTokenProvider.tokenOrchestrator; export { CognitoUserPoolTokenProviderType, diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index d35f392da1d..2732f332d47 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -210,7 +210,7 @@ describe('aws-amplify Exports', () => { 'fetchDevices', 'autoSignIn', 'cognitoCredentialsProvider', - 'CognitoUserPoolsTokenProvider', + 'cognitoUserPoolsTokenProvider', 'CognitoAWSCredentialsAndIdentityIdProvider', 'DefaultIdentityIdStore', 'TokenOrchestrator', diff --git a/packages/aws-amplify/__tests__/initSingleton.test.ts b/packages/aws-amplify/__tests__/initSingleton.test.ts index 3bdad8a9d86..56b1261314e 100644 --- a/packages/aws-amplify/__tests__/initSingleton.test.ts +++ b/packages/aws-amplify/__tests__/initSingleton.test.ts @@ -9,7 +9,7 @@ import { defaultStorage, } from '@aws-amplify/core'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, cognitoCredentialsProvider, } from '../src/auth/cognito'; @@ -17,7 +17,7 @@ import { Amplify } from '../src'; jest.mock('@aws-amplify/core'); jest.mock('../src/auth/cognito', () => ({ - CognitoUserPoolsTokenProvider: { + cognitoUserPoolsTokenProvider: { setAuthConfig: jest.fn(), setKeyValueStorage: jest.fn(), }, @@ -25,9 +25,9 @@ jest.mock('../src/auth/cognito', () => ({ })); const mockCognitoUserPoolsTokenProviderSetAuthConfig = - CognitoUserPoolsTokenProvider.setAuthConfig as jest.Mock; + cognitoUserPoolsTokenProvider.setAuthConfig as jest.Mock; const mockCognitoUserPoolsTokenProviderSetKeyValueStorage = - CognitoUserPoolsTokenProvider.setKeyValueStorage as jest.Mock; + cognitoUserPoolsTokenProvider.setKeyValueStorage as jest.Mock; const mockAmplifySingletonConfigure = AmplifySingleton.configure as jest.Mock; const mockAmplifySingletonGetConfig = AmplifySingleton.getConfig as jest.Mock; const MockCookieStorage = CookieStorage as jest.Mock; @@ -137,7 +137,7 @@ describe('initSingleton (DefaultAmplify)', () => { mockResourceConfig, { Auth: { - tokenProvider: CognitoUserPoolsTokenProvider, + tokenProvider: cognitoUserPoolsTokenProvider, credentialsProvider: cognitoCredentialsProvider, }, } @@ -200,7 +200,7 @@ describe('initSingleton (DefaultAmplify)', () => { mockResourceConfig, { Auth: { - tokenProvider: CognitoUserPoolsTokenProvider, + tokenProvider: cognitoUserPoolsTokenProvider, credentialsProvider: cognitoCredentialsProvider, }, ...libraryOptionsWithStorage, diff --git a/packages/aws-amplify/src/initSingleton.ts b/packages/aws-amplify/src/initSingleton.ts index 2ec413012c9..58e92dd053b 100644 --- a/packages/aws-amplify/src/initSingleton.ts +++ b/packages/aws-amplify/src/initSingleton.ts @@ -12,7 +12,7 @@ import { parseAWSExports, } from '@aws-amplify/core/internals/utils'; import { - CognitoUserPoolsTokenProvider, + cognitoUserPoolsTokenProvider, cognitoCredentialsProvider, } from './auth/cognito'; @@ -36,17 +36,17 @@ export const DefaultAmplify = { !libraryOptions?.Auth && !Amplify.libraryOptions.Auth ) { - CognitoUserPoolsTokenProvider.setAuthConfig(resolvedResourceConfig.Auth); + cognitoUserPoolsTokenProvider.setAuthConfig(resolvedResourceConfig.Auth); const libraryOptionsWithDefaultAuthProviders: LibraryOptions = { ...libraryOptions, Auth: { - tokenProvider: CognitoUserPoolsTokenProvider, + tokenProvider: cognitoUserPoolsTokenProvider, credentialsProvider: cognitoCredentialsProvider, }, }; - CognitoUserPoolsTokenProvider.setKeyValueStorage( + cognitoUserPoolsTokenProvider.setKeyValueStorage( libraryOptions?.ssr ? // TODO: allow configure with a public interface new CookieStorage({ From 36de0bb25514c4724b573ff6810ba1b0203b022b Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 8 Nov 2023 21:34:14 -0800 Subject: [PATCH 41/45] fix(auth): refreshToken unawaited async operation caused race condition --- .../tokenProvider/tokenOrchestrator.test.ts | 76 +++++++++++++++++++ .../tokenProvider/TokenOrchestrator.ts | 2 +- 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts diff --git a/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts b/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts new file mode 100644 index 00000000000..a9bdbcaca73 --- /dev/null +++ b/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts @@ -0,0 +1,76 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Hub } from '@aws-amplify/core'; +import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils'; +import { tokenOrchestrator } from '../../../../src/providers/cognito/tokenProvider'; +import { CognitoAuthTokens } from '../../../../src/providers/cognito/tokenProvider/types'; + +jest.mock('@aws-amplify/core/internals/utils'); +jest.mock('@aws-amplify/core', () => ({ + ...jest.requireActual('@aws-amplify/core'), + Hub: { + dispatch: jest.fn(), + }, +})); + +const mockAssertTokenProviderConfig = assertTokenProviderConfig as jest.Mock; + +describe('tokenOrchestrator', () => { + const mockTokenRefresher = jest.fn(); + const mockTokenStore = { + storeTokens: jest.fn(), + getLastAuthUser: jest.fn(), + loadTokens: jest.fn(), + clearTokens: jest.fn(), + setKeyValueStorage: jest.fn(), + getDeviceMetadata: jest.fn(), + clearDeviceMetadata: jest.fn(), + }; + + beforeAll(() => { + tokenOrchestrator.setTokenRefresher(mockTokenRefresher); + tokenOrchestrator.setAuthTokenStore(mockTokenStore); + }); + + describe('refreshTokens method', () => { + it('calls the set tokenRefresher, tokenStore and Hub while refreshing tokens', async () => { + const testUsername = 'username'; + const testInputTokens = { + accessToken: { + payload: {}, + }, + clockDrift: 400000, + username: testUsername, + }; + + const mockTokens: CognitoAuthTokens = { + accessToken: { + payload: {}, + }, + clockDrift: 300, + username: testUsername, + }; + mockTokenRefresher.mockResolvedValueOnce(mockTokens); + mockTokenStore.storeTokens.mockResolvedValue(void 0); + const newTokens = await tokenOrchestrator['refreshTokens']({ + tokens: testInputTokens, + username: testUsername, + }); + + // ensure the underlying async operations to be completed + // async #1 + expect(mockTokenRefresher).toHaveBeenCalledWith( + expect.objectContaining({ + tokens: testInputTokens, + username: testUsername, + }) + ); + // async #2 + expect(mockTokenStore.storeTokens).toHaveBeenCalledWith(mockTokens); + + // ensure the result is correct + expect(newTokens).toEqual(mockTokens); + }); + }); +}); diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts index ac08d7731de..58b3b4dcad5 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts @@ -124,7 +124,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { username, }); - this.setTokens({ tokens: newTokens }); + await this.setTokens({ tokens: newTokens }); Hub.dispatch('auth', { event: 'tokenRefresh' }, 'Auth', AMPLIFY_SYMBOL); return newTokens; From eca4b5a3746ab34a3152b65556a8a0cdca06a202 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Thu, 9 Nov 2023 09:38:01 -0600 Subject: [PATCH 42/45] chore: Update release command. --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 33583c5c8db..a7088479be0 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "unlink-all": "lerna exec --no-bail --parallel -- yarn unlink; exit 0", "publish:preid": "./scripts/preid-env-vars-exist.sh && lerna publish --canary --force-publish --dist-tag=${PREID_PREFIX} --preid=${PREID_PREFIX}${PREID_HASH_SUFFIX} --yes", "publish:main": "lerna publish --canary --force-publish --dist-tag=unstable --preid=unstable${PREID_HASH_SUFFIX} --yes", - "publish:release": "lerna publish --conventional-commits --dist-tag=v6 --message 'chore(release): Publish [ci skip]' --yes", + "publish:release": "lerna publish from-package --dist-tag=v6 --message 'chore(release): Publish [ci skip]' --yes", "publish:v5-stable": "lerna publish --conventional-commits --yes --dist-tag=stable-5 --message 'chore(release): Publish [ci skip]' --no-verify-access", "publish:verdaccio": "lerna publish --canary --force-publish --no-push --dist-tag=unstable --preid=unstable --yes", "ts-coverage": "lerna run ts-coverage", From 296162ce315829b225893968faa7e682a16819b8 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Thu, 9 Nov 2023 09:48:21 -0600 Subject: [PATCH 43/45] Publish - @aws-amplify/adapter-nextjs@1.0.1 - @aws-amplify/analytics@7.0.1 - @aws-amplify/api@6.0.1 - @aws-amplify/api-graphql@4.0.1 - @aws-amplify/api-rest@4.0.1 - @aws-amplify/auth@6.0.1 - aws-amplify@6.0.1 - @aws-amplify/core@6.0.1 - @aws-amplify/datastore@5.0.1 - @aws-amplify/datastore-storage-adapter@2.1.1 - @aws-amplify/geo@3.0.1 - @aws-amplify/interactions@6.0.1 - @aws-amplify/notifications@2.0.1 - @aws-amplify/predictions@6.0.1 - @aws-amplify/pubsub@6.0.1 - @aws-amplify/react-native@1.0.1 - @aws-amplify/react-native-example@0.0.2 - @aws-amplify/rtn-push-notification@1.2.1 - @aws-amplify/rtn-web-browser@1.0.1 - @aws-amplify/storage@6.0.1 - tsc-compliance-test@0.1.1 --- packages/adapter-nextjs/package.json | 8 +- packages/analytics/package.json | 12 +- packages/api-graphql/package.json | 176 +++++++++--------- packages/api-rest/package.json | 6 +- packages/api/package.json | 10 +- packages/auth/package.json | 8 +- packages/aws-amplify/package.json | 20 +- packages/core/package.json | 4 +- .../datastore-storage-adapter/package.json | 10 +- packages/datastore/package.json | 22 ++- packages/geo/package.json | 4 +- packages/interactions/package.json | 8 +- packages/notifications/package.json | 6 +- packages/predictions/package.json | 10 +- packages/pubsub/package.json | 10 +- packages/react-native/example/package.json | 2 +- packages/react-native/package.json | 6 +- packages/rtn-push-notification/package.json | 2 +- packages/rtn-web-browser/package.json | 6 +- packages/storage/package.json | 6 +- scripts/tsc-compliance-test/package.json | 4 +- 21 files changed, 176 insertions(+), 164 deletions(-) diff --git a/packages/adapter-nextjs/package.json b/packages/adapter-nextjs/package.json index 49db1978bd4..3602f548c24 100644 --- a/packages/adapter-nextjs/package.json +++ b/packages/adapter-nextjs/package.json @@ -1,7 +1,7 @@ { "author": "Amazon Web Services", "name": "@aws-amplify/adapter-nextjs", - "version": "1.0.0", + "version": "1.0.1", "description": "The adapter for the supporting of using Amplify APIs in Next.js.", "peerDependencies": { "aws-amplify": "^6.0.0", @@ -16,7 +16,7 @@ "@types/node": "^20.3.1", "@types/react": "^18.2.13", "@types/react-dom": "^18.2.6", - "aws-amplify": "6.0.0", + "aws-amplify": "6.0.1", "jest-fetch-mock": "3.0.3", "next": ">= 13.5.0 < 15.0.0", "rollup": "3.29.4", @@ -89,7 +89,9 @@ }, "tsConfig": { "allowJs": true, - "types": ["@types/jest"] + "types": [ + "@types/jest" + ] } } }, diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 0a6cb1f1221..e09e274b0db 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/analytics", - "version": "7.0.0", + "version": "7.0.1", "description": "Analytics category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -94,18 +94,18 @@ "personalize" ], "dependencies": { - "tslib": "^2.5.0", - "@aws-sdk/client-kinesis": "3.398.0", "@aws-sdk/client-firehose": "3.398.0", + "@aws-sdk/client-kinesis": "3.398.0", "@aws-sdk/client-personalize-events": "3.398.0", - "@smithy/util-utf8": "2.0.0" + "@smithy/util-utf8": "2.0.0", + "tslib": "^2.5.0" }, "peerDependencies": { "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@aws-sdk/types": "3.398.0", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", diff --git a/packages/api-graphql/package.json b/packages/api-graphql/package.json index 4dbdb44c291..5489b1c751f 100644 --- a/packages/api-graphql/package.json +++ b/packages/api-graphql/package.json @@ -1,92 +1,92 @@ { - "name": "@aws-amplify/api-graphql", - "version": "4.0.0", - "description": "Api-graphql category of aws-amplify", - "main": "./dist/cjs/index.js", - "module": "./dist/esm/index.mjs", - "typings": "./dist/esm/index.d.ts", - "react-native": "./src/index.ts", - "sideEffects": [ - "./dist/cjs/GraphQLAPI.js", - "./dist/esm/GraphQLAPI.mjs" - ], - "publishConfig": { - "access": "public" - }, - "scripts": { - "test": "npm run lint && jest -w 1 --coverage", - "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", - "build-with-test": "npm test && npm build", - "build:umd": "webpack && webpack --config ./webpack.config.dev.js", - "build:esm-cjs": "rollup -c rollup.config.mjs", - "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", - "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", - "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", - "clean": "npm run clean:size && rimraf dist lib lib-esm", - "clean:size": "rimraf dual-publish-tmp tmp*", - "format": "echo \"Not implemented\"", - "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", - "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 70.0" - }, - "exports": { - ".": { - "types": "./dist/esm/index.d.ts", - "import": "./dist/esm/index.mjs", - "require": "./dist/cjs/index.js", - "react-native": "./src/index.ts" + "name": "@aws-amplify/api-graphql", + "version": "4.0.1", + "description": "Api-graphql category of aws-amplify", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "typings": "./dist/esm/index.d.ts", + "react-native": "./src/index.ts", + "sideEffects": [ + "./dist/cjs/GraphQLAPI.js", + "./dist/esm/GraphQLAPI.mjs" + ], + "publishConfig": { + "access": "public" }, - "./internals": { - "types": "./dist/esm/internals/index.d.ts", - "import": "./dist/esm/internals/index.mjs", - "require": "./dist/cjs/internals/index.js", - "react-native": "./src/internals/index.ts" + "scripts": { + "test": "npm run lint && jest -w 1 --coverage", + "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", + "build-with-test": "npm test && npm build", + "build:umd": "webpack && webpack --config ./webpack.config.dev.js", + "build:esm-cjs": "rollup -c rollup.config.mjs", + "build:cjs:watch": "rimraf dist/cjs && tsc -m commonjs --outDir dist/cjs --watch", + "build:esm:watch": "rimraf dist/esm && tsc -m esnext --outDir dist/esm --watch", + "build": "npm run clean && npm run build:esm-cjs && npm run build:umd", + "clean": "npm run clean:size && rimraf dist lib lib-esm", + "clean:size": "rimraf dual-publish-tmp tmp*", + "format": "echo \"Not implemented\"", + "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", + "ts-coverage": "typescript-coverage-report -p ./tsconfig.json -t 70.0" }, - "./package.json": "./package.json" - }, - "typesVersions": { - ">=4.2": { - "internals": [ - "./dist/esm/internals/index.d.ts" - ] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/aws-amplify/amplify-js.git" - }, - "author": "Amazon Web Services", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/aws/aws-amplify/issues" - }, - "homepage": "https://aws-amplify.github.io/", - "devDependencies": { - "@rollup/plugin-typescript": "11.1.5", - "rollup": "3.29.4" - }, - "files": [ - "dist/cjs", - "dist/esm", - "src", - "internals" - ], - "dependencies": { - "@aws-amplify/api-rest": "4.0.0", - "@aws-amplify/auth": "6.0.0", - "@aws-amplify/core": "6.0.0", - "@aws-sdk/types": "3.387.0", - "graphql": "15.8.0", - "tslib": "^2.5.0", - "rxjs": "^7.8.1" - }, - "size-limit": [ - { - "name": "API (GraphQL client)", - "path": "./dist/esm/index.mjs", - "import": "{ Amplify, GraphQLAPI }", - "limit": "91.7 kB" - } - ], + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.js", + "react-native": "./src/index.ts" + }, + "./internals": { + "types": "./dist/esm/internals/index.d.ts", + "import": "./dist/esm/internals/index.mjs", + "require": "./dist/cjs/internals/index.js", + "react-native": "./src/internals/index.ts" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + ">=4.2": { + "internals": [ + "./dist/esm/internals/index.d.ts" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/aws-amplify/amplify-js.git" + }, + "author": "Amazon Web Services", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/aws/aws-amplify/issues" + }, + "homepage": "https://aws-amplify.github.io/", + "devDependencies": { + "@rollup/plugin-typescript": "11.1.5", + "rollup": "3.29.4" + }, + "files": [ + "dist/cjs", + "dist/esm", + "src", + "internals" + ], + "dependencies": { + "@aws-amplify/api-rest": "4.0.1", + "@aws-amplify/auth": "6.0.1", + "@aws-amplify/core": "6.0.1", + "@aws-sdk/types": "3.387.0", + "graphql": "15.8.0", + "rxjs": "^7.8.1", + "tslib": "^2.5.0" + }, + "size-limit": [ + { + "name": "API (GraphQL client)", + "path": "./dist/esm/index.mjs", + "import": "{ Amplify, GraphQLAPI }", + "limit": "91.7 kB" + } + ], "jest": { "globals": { "ts-jest": { @@ -104,7 +104,9 @@ "allowJs": true, "noEmitOnError": false, "strictNullChecks": true, - "types": ["@types/jest"] + "types": [ + "@types/jest" + ] } } }, diff --git a/packages/api-rest/package.json b/packages/api-rest/package.json index 7c6f616df74..51f6bc257c4 100644 --- a/packages/api-rest/package.json +++ b/packages/api-rest/package.json @@ -1,7 +1,7 @@ { "name": "@aws-amplify/api-rest", "private": false, - "version": "4.0.0", + "version": "4.0.1", "description": "Api-rest category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -87,8 +87,8 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" diff --git a/packages/api/package.json b/packages/api/package.json index 1e70b663e5c..7914c7086e1 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/api", - "version": "6.0.0", + "version": "6.0.1", "description": "Api category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -81,8 +81,8 @@ "server" ], "dependencies": { - "@aws-amplify/api-graphql": "4.0.0", - "@aws-amplify/api-rest": "4.0.0", + "@aws-amplify/api-graphql": "4.0.1", + "@aws-amplify/api-rest": "4.0.1", "tslib": "^2.5.0" }, "jest": { @@ -102,7 +102,9 @@ "allowJs": true, "noEmitOnError": false, "strictNullChecks": true, - "types": ["@types/jest"] + "types": [ + "@types/jest" + ] } } }, diff --git a/packages/auth/package.json b/packages/auth/package.json index ca67788ef1d..2ed5b7d4676 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/auth", - "version": "6.0.0", + "version": "6.0.1", "description": "Auth category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -89,10 +89,10 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", - "@rollup/plugin-typescript": "11.1.5", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@jest/test-sequencer": "^24.9.0", + "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" }, diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index 23f059e5db4..c8346cc89a8 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -1,6 +1,6 @@ { "name": "aws-amplify", - "version": "6.0.0", + "version": "6.0.1", "description": "AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -250,13 +250,13 @@ "utils" ], "dependencies": { - "@aws-amplify/api": "6.0.0", - "@aws-amplify/analytics": "7.0.0", - "@aws-amplify/auth": "6.0.0", - "@aws-amplify/core": "6.0.0", - "@aws-amplify/storage": "6.0.0", - "@aws-amplify/datastore": "5.0.0", - "@aws-amplify/notifications": "2.0.0", + "@aws-amplify/analytics": "7.0.1", + "@aws-amplify/api": "6.0.1", + "@aws-amplify/auth": "6.0.1", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/datastore": "5.0.1", + "@aws-amplify/notifications": "2.0.1", + "@aws-amplify/storage": "6.0.1", "tslib": "^2.5.0" }, "devDependencies": { @@ -498,7 +498,9 @@ "jsx" ], "testEnvironment": "jsdom", - "testPathIgnorePatterns": ["dual-publish-tmp"], + "testPathIgnorePatterns": [ + "dual-publish-tmp" + ], "testURL": "http://localhost/", "coverageThreshold": { "global": { diff --git a/packages/core/package.json b/packages/core/package.json index 4ae42c16766..7effa6e2a36 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/core", - "version": "6.0.0", + "version": "6.0.1", "description": "Core category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -60,7 +60,7 @@ "uuid": "^9.0.0" }, "devDependencies": { - "@aws-amplify/react-native": "^1.0.0", + "@aws-amplify/react-native": "1.0.1", "@rollup/plugin-typescript": "11.1.5", "@types/js-cookie": "3.0.2", "genversion": "^2.2.0", diff --git a/packages/datastore-storage-adapter/package.json b/packages/datastore-storage-adapter/package.json index 8428795dbcd..2bbdcdb37d3 100644 --- a/packages/datastore-storage-adapter/package.json +++ b/packages/datastore-storage-adapter/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/datastore-storage-adapter", - "version": "2.1.0", + "version": "2.1.1", "description": "SQLite storage adapter for Amplify DataStore ", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -36,14 +36,14 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/datastore": "5.0.0", - "@types/react-native-sqlite-storage": "5.0.1", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/datastore": "5.0.1", "@rollup/plugin-typescript": "11.1.5", - "rollup": "3.29.4", + "@types/react-native-sqlite-storage": "5.0.1", "expo-file-system": "13.1.4", "expo-sqlite": "10.1.0", "react-native-sqlite-storage": "5.0.0", + "rollup": "3.29.4", "sqlite3": "^5.0.2", "typescript": "5.0.2" }, diff --git a/packages/datastore/package.json b/packages/datastore/package.json index d7569422e4e..20951e9589d 100644 --- a/packages/datastore/package.json +++ b/packages/datastore/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/datastore", - "version": "5.0.0", + "version": "5.0.1", "description": "AppSyncLocal support for aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -44,27 +44,27 @@ "src" ], "dependencies": { - "@aws-amplify/api": "6.0.0", - "@aws-amplify/auth": "6.0.0", + "@aws-amplify/api": "6.0.1", + "@aws-amplify/auth": "6.0.1", "buffer": "4.9.2", "idb": "5.0.6", "immer": "9.0.6", - "ulid": "^2.3.0", - "rxjs": "^7.8.1" + "rxjs": "^7.8.1", + "ulid": "^2.3.0" }, "peerDependencies": { "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", - "@types/uuid-validate": "^0.0.1", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@rollup/plugin-typescript": "11.1.5", - "rollup": "3.29.4", + "@types/uuid-validate": "^0.0.1", "dexie": "3.2.2", "dexie-export-import": "1.0.3", "fake-indexeddb": "3.0.0", "graphql": "15.8.0", + "rollup": "3.29.4", "typescript": "5.0.2" }, "size-limit": [ @@ -91,7 +91,9 @@ "allowJs": true, "esModuleInterop": true, "strictNullChecks": false, - "types": ["@types/jest"] + "types": [ + "@types/jest" + ] } } }, diff --git a/packages/geo/package.json b/packages/geo/package.json index cf27cb9f709..ee6dcfb089f 100644 --- a/packages/geo/package.json +++ b/packages/geo/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/geo", - "version": "3.0.0", + "version": "3.0.1", "description": "Geo category for aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -76,7 +76,7 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", + "@aws-amplify/core": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" diff --git a/packages/interactions/package.json b/packages/interactions/package.json index a222d63c844..f338bd07ffe 100644 --- a/packages/interactions/package.json +++ b/packages/interactions/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/interactions", - "version": "6.0.0", + "version": "6.0.1", "description": "Interactions category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -77,11 +77,11 @@ "base-64": "1.0.0", "fflate": "0.7.3", "pako": "2.0.4", - "uuid": "^9.0.0", - "tslib": "^2.5.0" + "tslib": "^2.5.0", + "uuid": "^9.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", + "@aws-amplify/core": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "^5.0.2" diff --git a/packages/notifications/package.json b/packages/notifications/package.json index 229fb10c657..e0bf195dff2 100644 --- a/packages/notifications/package.json +++ b/packages/notifications/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/notifications", - "version": "2.0.0", + "version": "2.0.1", "description": "Notifications category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -98,8 +98,8 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" diff --git a/packages/predictions/package.json b/packages/predictions/package.json index b50b1a6b715..a97981843f5 100644 --- a/packages/predictions/package.json +++ b/packages/predictions/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/predictions", - "version": "6.0.0", + "version": "6.0.1", "description": "Machine learning category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -43,7 +43,7 @@ "src" ], "dependencies": { - "@aws-amplify/storage": "6.0.0", + "@aws-amplify/storage": "6.0.1", "@aws-sdk/client-comprehend": "3.398.0", "@aws-sdk/client-polly": "3.398.0", "@aws-sdk/client-rekognition": "3.398.0", @@ -59,7 +59,7 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", + "@aws-amplify/core": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" @@ -81,7 +81,9 @@ "tsConfig": { "downlevelIteration": true, "allowJs": true, - "types": ["@types/jest"], + "types": [ + "@types/jest" + ], "outDir": "./tsconfig.json", "noEmitOnError": false, "noImplicitAny": false, diff --git a/packages/pubsub/package.json b/packages/pubsub/package.json index d6f518465a7..3ed9e7f4b46 100644 --- a/packages/pubsub/package.json +++ b/packages/pubsub/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/pubsub", - "version": "6.0.0", + "version": "6.0.1", "description": "Pubsub category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -73,18 +73,18 @@ "mqtt" ], "dependencies": { - "@aws-amplify/auth": "6.0.0", + "@aws-amplify/auth": "6.0.1", "buffer": "4.9.2", "graphql": "15.8.0", + "rxjs": "^7.8.1", "tslib": "^2.5.0", - "url": "0.11.0", - "rxjs": "^7.8.1" + "url": "0.11.0" }, "peerDependencies": { "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", + "@aws-amplify/core": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", "typescript": "5.0.2" diff --git a/packages/react-native/example/package.json b/packages/react-native/example/package.json index c469a2de98c..0471a871649 100644 --- a/packages/react-native/example/package.json +++ b/packages/react-native/example/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/react-native-example", - "version": "0.0.1", + "version": "0.0.2", "private": true, "scripts": { "android": "react-native run-android", diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 9bc0af6ae21..9c0d8bd663a 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/react-native", - "version": "1.0.0", + "version": "1.0.1", "description": "React Native core module for aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -33,8 +33,8 @@ "react-native-get-random-values": ">=1.9.0" }, "devDependencies": { - "@aws-amplify/rtn-push-notification": "^1.2.0", - "@aws-amplify/rtn-web-browser": "^1.0.0", + "@aws-amplify/rtn-push-notification": "1.2.1", + "@aws-amplify/rtn-web-browser": "1.0.1", "@react-native-async-storage/async-storage": "^1.17.12", "@react-native-community/netinfo": "4.7.0", "@rollup/plugin-typescript": "11.1.5", diff --git a/packages/rtn-push-notification/package.json b/packages/rtn-push-notification/package.json index fc83003929f..70a9bfb1e4b 100644 --- a/packages/rtn-push-notification/package.json +++ b/packages/rtn-push-notification/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/rtn-push-notification", - "version": "1.2.0", + "version": "1.2.1", "description": "React Native module for aws-amplify push notifications", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", diff --git a/packages/rtn-web-browser/package.json b/packages/rtn-web-browser/package.json index a71beb2542a..74c9bdabdbd 100644 --- a/packages/rtn-web-browser/package.json +++ b/packages/rtn-web-browser/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/rtn-web-browser", - "version": "1.0.0", + "version": "1.0.1", "description": "React Native module for aws-amplify web browser", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -24,10 +24,10 @@ "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 88.21" }, "devDependencies": { - "@types/react-native": "0.70.0", "@rollup/plugin-typescript": "11.1.5", - "rollup": "3.29.4", + "@types/react-native": "0.70.0", "react-native": "0.72.3", + "rollup": "3.29.4", "typescript": "5.1.6" }, "repository": { diff --git a/packages/storage/package.json b/packages/storage/package.json index b80ebb47d52..053b881f974 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -1,6 +1,6 @@ { "name": "@aws-amplify/storage", - "version": "6.0.0", + "version": "6.0.1", "description": "Storage category of aws-amplify", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.mjs", @@ -101,8 +101,8 @@ "@aws-amplify/core": "^6.0.0" }, "devDependencies": { - "@aws-amplify/core": "6.0.0", - "@aws-amplify/react-native": "^1.0.0", + "@aws-amplify/core": "6.0.1", + "@aws-amplify/react-native": "1.0.1", "@rollup/plugin-json": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4", diff --git a/scripts/tsc-compliance-test/package.json b/scripts/tsc-compliance-test/package.json index 967d66d7c96..92cb6dbae76 100644 --- a/scripts/tsc-compliance-test/package.json +++ b/scripts/tsc-compliance-test/package.json @@ -1,11 +1,11 @@ { "name": "tsc-compliance-test", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "private": true, "devDependencies": { "@types/node": "^16.11.7", - "aws-amplify": "6.0.0", + "aws-amplify": "6.0.1", "typescript": "4.2.x" }, "scripts": { From 250bff8654cc6af9e447a4d07acc5390a1d72648 Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Thu, 9 Nov 2023 11:36:54 -0600 Subject: [PATCH 44/45] fix: API GraphQL dependencies on core & auth. --- packages/api-graphql/package.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/api-graphql/package.json b/packages/api-graphql/package.json index 5489b1c751f..3c21d95ca3e 100644 --- a/packages/api-graphql/package.json +++ b/packages/api-graphql/package.json @@ -60,7 +60,11 @@ "url": "https://github.com/aws/aws-amplify/issues" }, "homepage": "https://aws-amplify.github.io/", + "peerDependencies": { + "@aws-amplify/core": "^6.0.0" + }, "devDependencies": { + "@aws-amplify/core": "6.0.1", "@rollup/plugin-typescript": "11.1.5", "rollup": "3.29.4" }, @@ -72,8 +76,6 @@ ], "dependencies": { "@aws-amplify/api-rest": "4.0.1", - "@aws-amplify/auth": "6.0.1", - "@aws-amplify/core": "6.0.1", "@aws-sdk/types": "3.387.0", "graphql": "15.8.0", "rxjs": "^7.8.1", From 0bf1ad77eff30871ae361071bf41ef0999a5549c Mon Sep 17 00:00:00 2001 From: Jim Blanchard Date: Thu, 9 Nov 2023 11:42:18 -0600 Subject: [PATCH 45/45] chore: Remove auth as DataStore dependency. --- packages/datastore/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/datastore/package.json b/packages/datastore/package.json index 20951e9589d..9d5ecc68161 100644 --- a/packages/datastore/package.json +++ b/packages/datastore/package.json @@ -45,7 +45,6 @@ ], "dependencies": { "@aws-amplify/api": "6.0.1", - "@aws-amplify/auth": "6.0.1", "buffer": "4.9.2", "idb": "5.0.6", "immer": "9.0.6",