From 5c206308452023ca44b21162272e13f86ea6d59d Mon Sep 17 00:00:00 2001 From: Praveen Gupta <51211245+pravgupt@users.noreply.github.com> Date: Thu, 17 Oct 2019 10:51:40 -0700 Subject: [PATCH] Modularization es6 (#4007) * Build ES6 Modules along with CJS Modules * Upgrade Typescript to 3.5 * Upgrade Webpack to 4 * Upgrade Jest to 24 [Delivers #168385455] * Removing unused variable from build scripts * Fix signout component being undefined * Fix PR comments * Apply Prettier formatting * Merge branch 'master' of github.com:aws-amplify/amplify-js into modularization-merge * Fix tests that were failing after merge from master * Revert docs and other directories impacted by prettier * Update repository and homepage urls for all packages * Add diagnostic information to build script in event of failures * Revert formatter command as library now used Prettier with pre-commit hook * Adding unit test for pubsub desconnection issue * Fixing websocket disconnect issue on MqttProvider * Update stale.yml * fix: lerna linking for unstable and beta * fix(amazon-cognito-identity-js): linting config (#4097) * partially resolves linting issues in cognito sdk * removes no-cap lint change * using prettier to extend eslint in cognito sdk * removing newline * using airbnb lint config as well as prettier * Fix failing pubsub tests because of jest upgrade * Fix issue SignOut component being undefined * Apply suggestions from code review Co-Authored-By: Manuel Iglesias * Made mock window worker in angular tests more explicit * Fix failing pubsub tests because of jest upgrade * fix(@aws-amplify/core): removed unused variables (#3926) * Added link to docs for local development to CONTRIBUTING (#3990) * disabled autocomplete when resetting password for new password field * added local development resources to contributing * Fixed typo (#4156) * disabled autocomplete when resetting password for new password field * added local development resources to contributing * fixed typo in CONTRIBUTING doc, #3990 * fix(@aws-amplify/api) Adding x-amz-user-agent for AppSync calls * Adding x-amz-user-agent for appsync calls * Fixing unit test * chore(release): Publish [ci skip] - amazon-cognito-identity-js@3.1.0 - @aws-amplify/ui@1.1.0 - @aws-amplify/analytics@1.3.0 - @aws-amplify/api@1.2.0 - @aws-amplify/auth@1.4.0 - aws-amplify-angular@3.1.0 - aws-amplify-react-native@2.2.0 - aws-amplify-react@2.5.0 - aws-amplify-vue@0.3.0 - aws-amplify@1.2.0 - @aws-amplify/cache@1.1.0 - @aws-amplify/core@1.2.0 - @aws-amplify/interactions@1.1.0 - @aws-amplify/predictions@1.1.0 - @aws-amplify/pubsub@1.2.0 - @aws-amplify/pushnotification@1.1.0 - @aws-amplify/storage@1.2.0 - @aws-amplify/xr@0.2.0 * Publish - amazon-cognito-identity-js@3.1.1 - @aws-amplify/ui@1.1.1 - @aws-amplify/analytics@1.3.1 - @aws-amplify/api@1.2.1 - @aws-amplify/auth@1.4.1 - aws-amplify-angular@3.1.1 - aws-amplify-react-native@2.2.1 - aws-amplify-react@2.5.1 - aws-amplify-vue@0.3.1 - aws-amplify@1.2.1 - @aws-amplify/cache@1.1.1 - @aws-amplify/core@1.2.1 - @aws-amplify/interactions@1.1.1 - @aws-amplify/predictions@1.1.1 - @aws-amplify/pubsub@1.2.1 - @aws-amplify/pushnotification@1.1.1 - @aws-amplify/storage@1.2.1 - @aws-amplify/xr@0.2.1 * chore(release): Publish [ci skip] - amazon-cognito-identity-js@3.1.2 - @aws-amplify/ui@1.1.2 - @aws-amplify/analytics@1.3.2 - @aws-amplify/api@1.2.2 - @aws-amplify/auth@1.4.2 - aws-amplify-angular@3.1.2 - aws-amplify-react-native@2.2.2 - aws-amplify-react@2.5.2 - aws-amplify-vue@0.3.2 - aws-amplify@1.2.2 - @aws-amplify/cache@1.1.2 - @aws-amplify/core@1.2.2 - @aws-amplify/interactions@1.1.2 - @aws-amplify/predictions@1.1.2 - @aws-amplify/pubsub@1.2.2 - @aws-amplify/pushnotification@1.1.2 - @aws-amplify/storage@1.2.2 - @aws-amplify/xr@0.2.2 * fix(#4001) (#4131) * fix picker parent style (#4135) * Reduce threads to 1 while running jest tests as Circle CI constantly running out of memory * Remove unnecessary async/awaits in pubsub tests * Add Credentials mock explicitly on two tests that are failing only in circle ci * Move spyon in beforeEach --- .gitignore | 1 + package.json | 30 +- .../amazon-cognito-identity-js/package.json | 4 +- .../AmazonPersonalizeProvider-unit-test.ts | 199 ++--- packages/analytics/build.js | 5 + packages/analytics/index-rn.js | 3 + packages/analytics/index.js | 7 + packages/analytics/package.json | 62 +- .../Providers/AmazonPersonalizeProvider.ts | 2 +- packages/analytics/webpack.config.dev.js | 6 + packages/analytics/webpack.config.js | 51 +- packages/api/__tests__/API-test.ts | 1 - .../api/__tests__/RestClient-unit-test.ts | 776 ++++++++--------- packages/api/build.js | 5 + packages/api/index-rn.js | 3 + packages/api/index.js | 7 + packages/api/package.json | 62 +- packages/api/tsconfig.json | 29 - packages/api/webpack.config.dev.js | 6 + packages/api/webpack.config.js | 53 +- packages/auth/__tests__/cred-unit-test-rn.ts | 326 ++++---- packages/auth/__tests__/totp-unit-test.ts | 791 ++++++++++-------- packages/auth/build.js | 5 + packages/auth/index-rn.js | 3 + packages/auth/index.js | 7 + packages/auth/package.json | 64 +- packages/auth/tsconfig.json | 29 - packages/auth/webpack.config.dev.js | 6 + packages/auth/webpack.config.js | 48 +- packages/aws-amplify-angular/jest.config.js | 2 +- packages/aws-amplify-angular/package.json | 6 +- ...quire-new-password.component.ionic.spec.ts | 8 +- .../storage/s3-album.component.spec.ts | 10 - .../test_setup/setup-jest.ts | 21 +- .../aws-amplify-react-native/package.json | 4 +- .../Auth/Provider/withAuth0-test.tsx | 16 +- .../Auth/Provider/withOAuth-test.tsx | 8 +- .../Widget/__snapshots__/Picker-test.tsx.snap | 8 +- packages/aws-amplify-react/build.js | 5 + packages/aws-amplify-react/index.js | 7 + packages/aws-amplify-react/package.json | 39 +- .../aws-amplify-react/src/Auth/Greetings.tsx | 11 +- .../test_Setup/enzymeSetup.ts | 6 +- .../aws-amplify-react/webpack.config.dev.js | 6 + packages/aws-amplify-react/webpack.config.js | 52 ++ packages/aws-amplify-vue/package.json | 2 +- packages/aws-amplify/build.js | 5 + packages/aws-amplify/index-rn.js | 3 + packages/aws-amplify/index.js | 7 + packages/aws-amplify/package.json | 40 +- packages/aws-amplify/tsconfig.json | 26 - packages/aws-amplify/webpack.config.dev.js | 6 + packages/aws-amplify/webpack.config.js | 59 +- packages/cache/build.js | 5 + packages/cache/index-rn.js | 3 + packages/cache/index.js | 7 + packages/cache/package.json | 66 +- packages/cache/tsconfig.json | 29 - packages/cache/webpack.config.dev.js | 6 + packages/cache/webpack.config.js | 45 +- packages/core/__tests__/Credentials-test.ts | 175 ++-- packages/core/__tests__/ServiceWorker-test.ts | 8 +- packages/core/build.js | 5 + packages/core/index-rn.js | 3 + packages/core/index.js | 7 + packages/core/package.json | 57 +- packages/core/src/ClientDevice/browser.ts | 6 +- packages/core/src/ClientDevice/ios.ts | 4 +- .../core/src/ServiceWorker/ServiceWorker.ts | 2 +- packages/core/tsconfig.json | 30 - packages/core/typings.d.ts | 3 + packages/core/webpack.config.dev.js | 6 + packages/core/webpack.config.js | 45 +- packages/interactions/build.js | 5 + packages/interactions/index-rn.js | 3 + packages/interactions/index.js | 7 + packages/interactions/package.json | 56 +- packages/interactions/tsconfig.json | 29 - packages/interactions/webpack.config.dev.js | 6 + packages/interactions/webpack.config.js | 45 +- packages/predictions/build.js | 5 + packages/predictions/index-rn.js | 3 + packages/predictions/index.js | 7 + packages/predictions/package.json | 70 +- packages/predictions/tsconfig.json | 29 - packages/predictions/webpack.config.dev.js | 6 + packages/predictions/webpack.config.js | 47 +- packages/pubsub/__tests__/PubSub-unit-test.ts | 25 +- packages/pubsub/build.js | 5 + packages/pubsub/index-rn.js | 3 + packages/pubsub/index.js | 7 + packages/pubsub/package.json | 61 +- packages/pubsub/tsconfig.json | 29 - packages/pubsub/webpack.config.dev.js | 6 + packages/pubsub/webpack.config.js | 45 +- .../__tests__/PushNotification-unit-test.ts | 3 - packages/pushnotification/package.json | 6 +- packages/storage/build.js | 5 + packages/storage/index-rn.js | 3 + packages/storage/index.js | 7 + packages/storage/package.json | 61 +- packages/storage/tsconfig.json | 29 - packages/storage/webpack.config.dev.js | 6 + packages/storage/webpack.config.js | 45 +- packages/xr/build.js | 5 + packages/xr/index-rn.js | 3 + packages/xr/index.js | 7 + packages/xr/package.json | 62 +- packages/xr/tsconfig.json | 29 - packages/xr/webpack.config.dev.js | 6 + packages/xr/webpack.config.js | 45 +- scripts/build.js | 174 ++++ scripts/rollup-externals.js | 93 ++ scripts/utility.js | 49 ++ 114 files changed, 2429 insertions(+), 2168 deletions(-) create mode 100644 packages/analytics/build.js create mode 100644 packages/analytics/index-rn.js create mode 100644 packages/analytics/index.js create mode 100644 packages/analytics/webpack.config.dev.js create mode 100644 packages/api/build.js create mode 100644 packages/api/index-rn.js create mode 100644 packages/api/index.js delete mode 100755 packages/api/tsconfig.json create mode 100644 packages/api/webpack.config.dev.js create mode 100644 packages/auth/build.js create mode 100644 packages/auth/index-rn.js create mode 100644 packages/auth/index.js delete mode 100755 packages/auth/tsconfig.json create mode 100644 packages/auth/webpack.config.dev.js create mode 100644 packages/aws-amplify-react/build.js create mode 100644 packages/aws-amplify-react/index.js create mode 100644 packages/aws-amplify-react/webpack.config.dev.js create mode 100644 packages/aws-amplify-react/webpack.config.js create mode 100644 packages/aws-amplify/build.js create mode 100644 packages/aws-amplify/index-rn.js create mode 100644 packages/aws-amplify/index.js delete mode 100755 packages/aws-amplify/tsconfig.json create mode 100644 packages/aws-amplify/webpack.config.dev.js create mode 100644 packages/cache/build.js create mode 100644 packages/cache/index-rn.js create mode 100644 packages/cache/index.js delete mode 100755 packages/cache/tsconfig.json create mode 100644 packages/cache/webpack.config.dev.js create mode 100644 packages/core/build.js create mode 100644 packages/core/index-rn.js create mode 100644 packages/core/index.js delete mode 100755 packages/core/tsconfig.json create mode 100644 packages/core/typings.d.ts create mode 100644 packages/core/webpack.config.dev.js create mode 100644 packages/interactions/build.js create mode 100644 packages/interactions/index-rn.js create mode 100644 packages/interactions/index.js delete mode 100755 packages/interactions/tsconfig.json create mode 100644 packages/interactions/webpack.config.dev.js create mode 100644 packages/predictions/build.js create mode 100644 packages/predictions/index-rn.js create mode 100644 packages/predictions/index.js delete mode 100755 packages/predictions/tsconfig.json create mode 100644 packages/predictions/webpack.config.dev.js create mode 100644 packages/pubsub/build.js create mode 100644 packages/pubsub/index-rn.js create mode 100644 packages/pubsub/index.js delete mode 100755 packages/pubsub/tsconfig.json create mode 100644 packages/pubsub/webpack.config.dev.js delete mode 100644 packages/pushnotification/__tests__/PushNotification-unit-test.ts create mode 100644 packages/storage/build.js create mode 100644 packages/storage/index-rn.js create mode 100644 packages/storage/index.js delete mode 100755 packages/storage/tsconfig.json create mode 100644 packages/storage/webpack.config.dev.js create mode 100644 packages/xr/build.js create mode 100644 packages/xr/index-rn.js create mode 100644 packages/xr/index.js delete mode 100644 packages/xr/tsconfig.json create mode 100644 packages/xr/webpack.config.dev.js create mode 100644 scripts/build.js create mode 100644 scripts/rollup-externals.js create mode 100644 scripts/utility.js diff --git a/.gitignore b/.gitignore index e4142a397a5..5579be7ba33 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ lerna-debug.log node_modules/** packages/*/node_modules/** packages/**/lib/ +packages/**/lib-esm/ packages/**/dist/ packages/**/es/ .DS_Store diff --git a/package.json b/package.json index 9b087941fa6..76b9c66743e 100644 --- a/package.json +++ b/package.json @@ -17,8 +17,8 @@ "lint": "lerna run lint", "link-all": "yarn unlink-all && lerna exec --parallel yarn link", "unlink-all": "lerna exec --parallel --bail=false yarn unlink", - "publish:master": "lerna publish --canary --force-publish \"*\" --yes --dist-tag=unstable --preid=unstable --exact", - "publish:beta": "lerna publish --canary --force-publish \"*\" --yes --dist-tag=beta --preid=beta --exact", + "publish:master": "lerna publish --canary --force-publish \"*\" --yes --dist-tag=unstable --preid=unstable --exact", + "publish:beta": "lerna publish --canary --force-publish \"*\" --yes --dist-tag=beta --preid=beta --exact", "publish:release": "lerna publish --conventional-commits --yes --message 'chore(release): Publish [ci skip]'" }, "husky": { @@ -40,30 +40,40 @@ }, "homepage": "https://aws-amplify.github.io/", "devDependencies": { - "@types/jest": "^20.0.7", + "@types/jest": "^24.0.18", "@types/node": "^8.9.5", + "@babel/cli": "^7.0.0", + "@babel/core": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/preset-react": "^7.0.0", + "babel-loader": "^8.0.0", "codecov": "^1.0.1", "compression-webpack-plugin": "^1.1.3", "cypress": "^3.2.0", "husky": "^3.0.5", - "jest": "^22.4.3", + "jest": "^24.x.x", "json-loader": "^0.5.7", "lerna": "^3.13.1", "pretty-quick": "^1.11.1", "rimraf": "^2.6.2", + "rollup": "^0.67.4", + "rollup-plugin-commonjs": "^9.2.0", + "rollup-plugin-json": "^3.1.0", + "rollup-plugin-node-resolve": "^4.0.0", + "rollup-plugin-sourcemaps": "^0.4.2", + "rollup-plugin-typescript": "^1.0.0", "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", + "ts-jest": "^24.x.x", "tslint": "^5.7.0", "tslint-config-airbnb": "^5.8.0", "typedoc": "^0.11.0", - "typescript": "^2.9.2", + "typescript": "^3.5.3", "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" + "webpack": "^4.32.0", + "webpack-bundle-analyzer": "^3.3.2", + "webpack-cli": "^3.1.0" }, "jest": { - "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "/node_modules/ts-jest/preprocessor.js" - }, "resetMocks": true, "verbose": true } diff --git a/packages/amazon-cognito-identity-js/package.json b/packages/amazon-cognito-identity-js/package.json index a43cdefca9c..20dce8495d4 100644 --- a/packages/amazon-cognito-identity-js/package.json +++ b/packages/amazon-cognito-identity-js/package.json @@ -24,7 +24,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/aws/aws-amplify.git" + "url": "https://github.com/aws-amplify/amplify-js.git" }, "license": "SEE LICENSE IN LICENSE.txt", "licenses": [ @@ -50,7 +50,7 @@ "doc": "jsdoc src -d docs", "lint": "eslint src", "lint2": "eslint enhance-rn.js", - "test": "jest --passWithNoTests", + "test": "jest -w 1 --passWithNoTests", "format": "echo \"Not implemented\"" }, "main": "lib/index.js", diff --git a/packages/analytics/__tests__/Providers/AmazonPersonalizeProvider-unit-test.ts b/packages/analytics/__tests__/Providers/AmazonPersonalizeProvider-unit-test.ts index 6ec3f2f358c..64ecd134cb0 100644 --- a/packages/analytics/__tests__/Providers/AmazonPersonalizeProvider-unit-test.ts +++ b/packages/analytics/__tests__/Providers/AmazonPersonalizeProvider-unit-test.ts @@ -11,114 +11,121 @@ * and limitations under the License. */ jest.mock('aws-sdk/clients/personalizeevents', () => { - const PersonalizeEvents = () => { - var personalizeEvents = null; - return personalizeEvents; - } + const PersonalizeEvents = () => { + var personalizeEvents = null; + return personalizeEvents; + }; - PersonalizeEvents.prototype.putEvents = (params, callback) => { - callback(null, 'data'); - } + PersonalizeEvents.prototype.putEvents = (params, callback) => { + callback(null, 'data'); + }; - return PersonalizeEvents; + return PersonalizeEvents; }); import { Credentials } from '@aws-amplify/core'; -import AmazonPersonalizeProvider from "../../src/Providers/AmazonPersonalizeProvider"; +import AmazonPersonalizeProvider from '../../src/Providers/AmazonPersonalizeProvider'; jest.useFakeTimers(); const clientInfo = { - appVersion: '1.0', - make: 'make', - model: 'model', - version: '1.0.0', - platform: 'platform' -} + appVersion: '1.0', + make: 'make', + model: 'model', + version: '1.0.0', + platform: 'platform', +}; const credentials = { - accessKeyId: 'accessKeyId', - sessionToken: 'sessionToken', - secretAccessKey: 'secretAccessKey', - identityId: 'identityId', - authenticated: true -} + accessKeyId: 'accessKeyId', + sessionToken: 'sessionToken', + secretAccessKey: 'secretAccessKey', + identityId: 'identityId', + authenticated: true, +}; -const TRACKING_ID = "trackingId"; +const TRACKING_ID = 'trackingId'; -jest.useFakeTimers() +jest.useFakeTimers(); describe('Personalize provider test', () => { - describe('getProviderName test', () => { - test('happy case', () => { - const analytics = new AmazonPersonalizeProvider(); - - expect(analytics.getProviderName()).toBe('AmazonPersonalize'); - }); - }); - - describe('configure test', () => { - test('happy case', () => { - const analytics = new AmazonPersonalizeProvider(); - analytics.configure({"trackingId": TRACKING_ID}); - expect(analytics.configure({region: 'region1'})).toEqual( - {"flushInterval": 5000, "flushSize": 5, "region": "region1", "trackingId": "trackingId"}); - }); - }); - - describe('record test', () => { - test('record without credentials', async () => { - const analytics = new AmazonPersonalizeProvider(); - analytics.configure({"trackingId": TRACKING_ID}); - const spyon = jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { - return Promise.reject('err'); - }); - - expect(await analytics.record('params')).toBe(false); - spyon.mockClear(); - }); - - test('record happy case with identify event', async () => { - const analytics = new AmazonPersonalizeProvider(); - analytics.configure({"trackingId": TRACKING_ID}); - const spyon = jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { - return Promise.resolve(credentials); - }); - - - await analytics.record({ - event: { - eventType: "Identify", - properties: {"userId": "user1"}, - }, - config: {} - }); - - jest.advanceTimersByTime(6000); - - spyon.mockClear(); - }); - - test('record happy case with Click event', async () => { - const analytics = new AmazonPersonalizeProvider(); - analytics.configure({"trackingId": TRACKING_ID}); - const spyon = jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { - return Promise.resolve(credentials); - }); - - - await analytics.record({ - event: { - eventType: "Click", - properties: {"itemId": "item1", "eventValue": "value1"}, - }, - config: {} - }); - - jest.advanceTimersByTime(6000); - - spyon.mockClear(); - }); - - }); -}; + describe('getProviderName test', () => { + test('happy case', () => { + const analytics = new AmazonPersonalizeProvider(); + + expect(analytics.getProviderName()).toBe('AmazonPersonalize'); + }); + }); + + describe('configure test', () => { + test('happy case', () => { + const analytics = new AmazonPersonalizeProvider(); + analytics.configure({ trackingId: TRACKING_ID }); + expect(analytics.configure({ region: 'region1' })).toEqual({ + flushInterval: 5000, + flushSize: 5, + region: 'region1', + trackingId: 'trackingId', + }); + }); + }); + + describe('record test', () => { + test('record without credentials', async () => { + const analytics = new AmazonPersonalizeProvider(); + analytics.configure({ trackingId: TRACKING_ID }); + const spyon = jest + .spyOn(Credentials, 'get') + .mockImplementationOnce(() => { + return Promise.reject('err'); + }); + + expect(await analytics.record('params')).toBe(false); + spyon.mockClear(); + }); + + test('record happy case with identify event', async () => { + const analytics = new AmazonPersonalizeProvider(); + analytics.configure({ trackingId: TRACKING_ID }); + const spyon = jest + .spyOn(Credentials, 'get') + .mockImplementationOnce(() => { + return Promise.resolve(credentials); + }); + + await analytics.record({ + event: { + eventType: 'Identify', + properties: { userId: 'user1' }, + }, + config: {}, + }); + + jest.advanceTimersByTime(6000); + + spyon.mockClear(); + }); + + test('record happy case with Click event', async () => { + const analytics = new AmazonPersonalizeProvider(); + analytics.configure({ trackingId: TRACKING_ID }); + const spyon = jest + .spyOn(Credentials, 'get') + .mockImplementationOnce(() => { + return Promise.resolve(credentials); + }); + + await analytics.record({ + event: { + eventType: 'Click', + properties: { itemId: 'item1', eventValue: 'value1' }, + }, + config: {}, + }); + + jest.advanceTimersByTime(6000); + + spyon.mockClear(); + }); + }); +}); diff --git a/packages/analytics/build.js b/packages/analytics/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/analytics/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/analytics/index-rn.js b/packages/analytics/index-rn.js new file mode 100644 index 00000000000..b918804d60f --- /dev/null +++ b/packages/analytics/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib-esm/index.js'); diff --git a/packages/analytics/index.js b/packages/analytics/index.js new file mode 100644 index 00000000000..60bba2fc044 --- /dev/null +++ b/packages/analytics/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-analytics.min.js'); +} else { + module.exports = require('./dist/aws-amplify-analytics.js'); +} diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 375313273ce..0502db838dd 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -2,64 +2,60 @@ "name": "@aws-amplify/analytics", "version": "1.3.2", "description": "Analytics category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "test:watch": "tslint 'src/**/*.ts' && jest --watch", + "test": "tslint 'src/**/*.ts' && jest -w 1 --coverage", + "test:watch": "tslint 'src/**/*.ts' && jest -w 1 --watch", "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "build:watch": "npm run clean && tsc --watch", - "clean": "rimraf lib lib-esm dist", + "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", + "build:esm": "node ./build es6", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "react-native": { - "./lib/trackers": "./lib/trackers/reactnative.js" + "./index": "./lib-esm/index.js", + "./lib-esm/trackers": "./lib-esm/trackers/reactnative.js" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/cache": "^1.1.2", "@aws-amplify/core": "^1.2.2", "uuid": "^3.2.1" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/analytics/src/Providers/AmazonPersonalizeProvider.ts b/packages/analytics/src/Providers/AmazonPersonalizeProvider.ts index 3a9e84dd62f..9ff57c0a6d0 100644 --- a/packages/analytics/src/Providers/AmazonPersonalizeProvider.ts +++ b/packages/analytics/src/Providers/AmazonPersonalizeProvider.ts @@ -49,7 +49,7 @@ export default class AmazonPersonalizeProvider implements AnalyticsProvider { this._config = config ? config : {}; this._config.flushSize = this._config.flushSize > 0 && - this._config.flushSize <= FLUSH_SIZE_THRESHHOLD + this._config.flushSize <= FLUSH_SIZE_THRESHHOLD ? this._config.flushSize : FLUSH_SIZE; this._config.flushInterval = this._config.flushInterval || FLUSH_INTERVAL; diff --git a/packages/analytics/webpack.config.dev.js b/packages/analytics/webpack.config.dev.js new file mode 100644 index 00000000000..7b7ffbdd168 --- /dev/null +++ b/packages/analytics/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-analytics': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/analytics/webpack.config.js b/packages/analytics/webpack.config.js index 6e8f745213a..3aeff42d67f 100644 --- a/packages/analytics/webpack.config.js +++ b/packages/analytics/webpack.config.js @@ -1,11 +1,14 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-analytics': './src/index.ts', - 'aws-amplify-analytics.min': './src/index.ts', + 'aws-amplify-analytics.min': './lib-esm/index.js', }, + externals: [ + 'react-native', + '@aws-amplify/cache', + '@aws-amplify/core', + 'aws-sdk/clients/pinpoint', + 'aws-sdk/clients/kinesis', + ], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +21,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/api/__tests__/API-test.ts b/packages/api/__tests__/API-test.ts index 793f0585076..a0f26c21f4d 100644 --- a/packages/api/__tests__/API-test.ts +++ b/packages/api/__tests__/API-test.ts @@ -8,7 +8,6 @@ import { GRAPHQL_AUTH_MODE } from '../src/types'; import { RestClient } from '../src/RestClient'; import { print } from 'graphql/language/printer'; import { parse } from 'graphql/language/parser'; -import { Signer, Credentials } from '@aws-amplify/core'; import { INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER } from '@aws-amplify/core/lib/constants'; import PubSub from '@aws-amplify/pubsub'; import Cache from '@aws-amplify/cache'; diff --git a/packages/api/__tests__/RestClient-unit-test.ts b/packages/api/__tests__/RestClient-unit-test.ts index e5b02113e15..c49a9e2b393 100644 --- a/packages/api/__tests__/RestClient-unit-test.ts +++ b/packages/api/__tests__/RestClient-unit-test.ts @@ -1,390 +1,406 @@ jest.mock('@aws-amplify/core/lib/Signer', () => { - return { - default: { - sign: (request: any, access_info: any, service_info?: any) => { - return request; - } - } - } + return { + default: { + sign: (request: any, access_info: any, service_info?: any) => { + return request; + }, + }, + }; }); jest.mock('axios', () => { - return { - default: (signed_params) => { - return new Promise((res, rej) => { - const withCredentialsSuffix = signed_params && signed_params.withCredentials - ? '-withCredentials' - : ''; - if (signed_params && signed_params.headers && signed_params.headers.reject) { - rej({ - data: 'error' + withCredentialsSuffix; - }); - } - else if (signed_params && signed_params.responseType === 'blob') { - res({ - data: 'blob' + withCredentialsSuffix; - }); - } - else { - res({ - data: 'data' + withCredentialsSuffix; - }); - } - }); - } - }; + return { + default: signed_params => { + return new Promise((res, rej) => { + const withCredentialsSuffix = + signed_params && signed_params.withCredentials + ? '-withCredentials' + : ''; + if ( + signed_params && + signed_params.headers && + signed_params.headers.reject + ) { + rej({ + data: 'error' + withCredentialsSuffix, + }); + } else if (signed_params && signed_params.responseType === 'blob') { + res({ + data: 'blob' + withCredentialsSuffix, + }); + } else { + res({ + data: 'data' + withCredentialsSuffix, + }); + } + }); + }, + }; }); import { RestClient } from '../src/RestClient'; describe('RestClient test', () => { - describe('ajax', () => { - test('fetch with signed request', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', {})).toEqual('data'); - }); - - test('fetch with signed failing request', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(1); - - try { - await restClient.ajax('url', 'method', { headers: { reject: true } }); - } catch (error) { - expect(error).toEqual({ data: 'error' }); - } - }); - - test('fetch with signed request', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', {})).toEqual('data'); - }); - - test('ajax with no credentials', async () => { - const apiOptions = { - headers: {}, - endpoints: {} - }; - - const restClient = new RestClient(apiOptions); - - try { - await restClient.ajax('url', 'method', {}); - } catch (e) { - expect(e).toBe('credentials not set for API rest client '); - } - }); - - test('ajax with extraParams', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', { body: 'body' })).toEqual('data'); - }); - - test('ajax with custom responseType', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', { body: 'body', responseType: 'blob' })).toEqual('blob'); - }); - - test('ajax with Authorization header', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', { headers: { Authorization: 'authorization' } })).toEqual('data'); - }); - - test('ajax with withCredentials set to true', async () => { - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(await restClient.ajax('url', 'method', { withCredentials: true })).toEqual('data-withCredentials'); - }); - }); - - describe('get test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(5); - await restClient.get('url', {}); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('GET'); - - await restClient.get('url', {withCredentials: true}); - - expect(spyon.mock.calls[1][0]).toBe('url'); - expect(spyon.mock.calls[1][1]).toBe('GET'); - expect(spyon.mock.calls[1][2]).toEqual({withCredentials: true}); - - spyon.mockClear(); - }); - }); - - describe('put test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(3); - await restClient.put('url', 'data'); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('PUT'); - expect(spyon.mock.calls[0][2]).toBe('data'); - spyon.mockClear(); - }); - }); - - describe('patch test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(3); - await restClient.patch('url', 'data'); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('PATCH'); - expect(spyon.mock.calls[0][2]).toBe('data'); - spyon.mockClear(); - }); - }); - - describe('post test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(3); - await restClient.post('url', 'data'); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('POST'); - expect(spyon.mock.calls[0][2]).toBe('data'); - spyon.mockClear(); - }); - }); - - describe('del test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(2); - await restClient.del('url', {}); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('DELETE'); - spyon.mockClear(); - }); - }); - - describe('head test', () => { - test('happy case', async () => { - const spyon = jest.spyOn(RestClient.prototype, 'ajax'); - - const apiOptions = { - headers: {}, - endpoints: {}, - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect.assertions(2); - await restClient.head('url', {}); - - expect(spyon.mock.calls[0][0]).toBe('url'); - expect(spyon.mock.calls[0][1]).toBe('HEAD'); - spyon.mockClear(); - }); - }); - - describe('endpoint test', () => { - test('happy case', () => { - const apiOptions = { - headers: {}, - endpoints: [ - { - name: 'myApi', - endpoint: 'endpoint of myApi' - }, - { - name: 'otherApi', - endpoint: 'endpoint of otherApi' - } - ], - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - }, - region: 'myregion' - }; - - const restClient = new RestClient(apiOptions); - - expect(restClient.endpoint('myApi')).toBe('endpoint of myApi'); - }); - - test('custom endpoint', () => { - const apiOptions = { - headers: {}, - endpoints: [ - { - name: 'myApi', - endpoint: 'endpoint of myApi' - }, - { - name: 'otherApi', - endpoint: 'endpoint of otherApi', - region: 'myregion', - service: 'myservice' - } - ], - credentials: { - accessKeyId: 'accessKeyId', - secretAccessKey: 'secretAccessKey', - sessionToken: 'sessionToken' - } - }; - - const restClient = new RestClient(apiOptions); - - expect(restClient.endpoint('otherApi')).toBe('endpoint of otherApi'); - }); - }); + describe('ajax', () => { + test('fetch with signed request', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect(await restClient.ajax('url', 'method', {})).toEqual('data'); + }); + + test('fetch with signed failing request', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(1); + + try { + await restClient.ajax('url', 'method', { headers: { reject: "true" } }); + } catch (error) { + expect(error).toEqual({ data: 'error' }); + } + }); + + test('fetch with signed request', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect(await restClient.ajax('url', 'method', {})).toEqual('data'); + }); + + test('ajax with no credentials', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + }; + + const restClient = new RestClient(apiOptions); + + try { + await restClient.ajax('url', 'method', {}); + } catch (e) { + expect(e).toBe('credentials not set for API rest client '); + } + }); + + test('ajax with extraParams', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect(await restClient.ajax('url', 'method', { body: 'body' })).toEqual( + 'data' + ); + }); + + test('ajax with custom responseType', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect( + await restClient.ajax('url', 'method', { + body: 'body', + responseType: 'blob', + }) + ).toEqual('blob'); + }); + + test('ajax with Authorization header', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect( + await restClient.ajax('url', 'method', { + headers: { Authorization: 'authorization' }, + }) + ).toEqual('data'); + }); + + test('ajax with withCredentials set to true', async () => { + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect( + await restClient.ajax('url', 'method', { withCredentials: true }) + ).toEqual('data-withCredentials'); + }); + }); + + describe('get test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(5); + await restClient.get('url', {}); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('GET'); + + await restClient.get('url', { withCredentials: true }); + + expect(spyon.mock.calls[1][0]).toBe('url'); + expect(spyon.mock.calls[1][1]).toBe('GET'); + expect(spyon.mock.calls[1][2]).toEqual({ withCredentials: true }); + + spyon.mockClear(); + }); + }); + + describe('put test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(3); + await restClient.put('url', 'data'); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('PUT'); + expect(spyon.mock.calls[0][2]).toBe('data'); + spyon.mockClear(); + }); + }); + + describe('patch test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(3); + await restClient.patch('url', 'data'); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('PATCH'); + expect(spyon.mock.calls[0][2]).toBe('data'); + spyon.mockClear(); + }); + }); + + describe('post test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(3); + await restClient.post('url', 'data'); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('POST'); + expect(spyon.mock.calls[0][2]).toBe('data'); + spyon.mockClear(); + }); + }); + + describe('del test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(2); + await restClient.del('url', {}); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('DELETE'); + spyon.mockClear(); + }); + }); + + describe('head test', () => { + test('happy case', async () => { + const spyon = jest.spyOn(RestClient.prototype, 'ajax'); + + const apiOptions = { + headers: {}, + endpoints: {}, + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect.assertions(2); + await restClient.head('url', {}); + + expect(spyon.mock.calls[0][0]).toBe('url'); + expect(spyon.mock.calls[0][1]).toBe('HEAD'); + spyon.mockClear(); + }); + }); + + describe('endpoint test', () => { + test('happy case', () => { + const apiOptions = { + headers: {}, + endpoints: [ + { + name: 'myApi', + endpoint: 'endpoint of myApi', + }, + { + name: 'otherApi', + endpoint: 'endpoint of otherApi', + }, + ], + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + region: 'myregion', + }; + + const restClient = new RestClient(apiOptions); + + expect(restClient.endpoint('myApi')).toBe('endpoint of myApi'); + }); + + test('custom endpoint', () => { + const apiOptions = { + headers: {}, + endpoints: [ + { + name: 'myApi', + endpoint: 'endpoint of myApi', + }, + { + name: 'otherApi', + endpoint: 'endpoint of otherApi', + region: 'myregion', + service: 'myservice', + }, + ], + credentials: { + accessKeyId: 'accessKeyId', + secretAccessKey: 'secretAccessKey', + sessionToken: 'sessionToken', + }, + }; + + const restClient = new RestClient(apiOptions); + + expect(restClient.endpoint('otherApi')).toBe('endpoint of otherApi'); + }); + }); }); diff --git a/packages/api/build.js b/packages/api/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/api/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/api/index-rn.js b/packages/api/index-rn.js new file mode 100644 index 00000000000..b918804d60f --- /dev/null +++ b/packages/api/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib-esm/index.js'); diff --git a/packages/api/index.js b/packages/api/index.js new file mode 100644 index 00000000000..06065a000c4 --- /dev/null +++ b/packages/api/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-api.min.js'); +} else { + module.exports = require('./dist/aws-amplify-api.js'); +} diff --git a/packages/api/package.json b/packages/api/package.json index f491cc77d5f..e92318c03ac 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -2,64 +2,66 @@ "name": "@aws-amplify/api", "version": "1.2.2", "description": "Api category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "clean": "rimraf lib lib-esm dist", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", + "homepage": "https://aws-amplify.github.io/", "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "@types/zen-observable": "^0.5.3", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" + "prettier": "^1.7.4" }, "dependencies": { "@aws-amplify/auth": "^1.4.2", "@aws-amplify/cache": "^1.1.2", "@aws-amplify/core": "^1.2.2", + "@types/zen-observable": "^0.5.3", "axios": "^0.19.0", "graphql": "0.13.0", "uuid": "^3.2.1", "zen-observable": "^0.8.6" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/api/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/api/webpack.config.dev.js b/packages/api/webpack.config.dev.js new file mode 100644 index 00000000000..7d6c40c7a79 --- /dev/null +++ b/packages/api/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-api': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/api/webpack.config.js b/packages/api/webpack.config.js index a1c8bd7ee3a..7c31dc9885a 100644 --- a/packages/api/webpack.config.js +++ b/packages/api/webpack.config.js @@ -1,11 +1,16 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-api': './src/index.ts', - 'aws-amplify-api.min': './src/index.ts', + 'aws-amplify-api.min': './lib-esm/index.js', }, + externals: [ + 'graphql', + 'graphql/language/ast', + 'graphql/language/parser', + 'graphql/language/printer', + '@aws-amplify/cache', + '@aws-amplify/core', + '@aws-amplify/auth', + ], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +23,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/auth/__tests__/cred-unit-test-rn.ts b/packages/auth/__tests__/cred-unit-test-rn.ts index a0cd08242fb..48e51d59210 100644 --- a/packages/auth/__tests__/cred-unit-test-rn.ts +++ b/packages/auth/__tests__/cred-unit-test-rn.ts @@ -1,186 +1,208 @@ jest.mock('amazon-cognito-identity-js/lib/CognitoUserSession', () => { - const CognitoUserSession = () => {} - - CognitoUserSession.prototype.CognitoUserSession = (options) => { - CognitoUserSession.prototype.options = options; - return CognitoUserSession; - } - - CognitoUserSession.prototype.getIdToken = () => { - return { - getJwtToken: () => { - return null; - } - } - } - - return CognitoUserSession; + const CognitoUserSession = () => {}; + + CognitoUserSession.prototype.CognitoUserSession = options => { + CognitoUserSession.prototype.options = options; + return CognitoUserSession; + }; + + CognitoUserSession.prototype.getIdToken = () => { + return { + getJwtToken: () => { + return null; + }, + }; + }; + + return CognitoUserSession; }); jest.mock('amazon-cognito-identity-js/lib/CognitoIdToken', () => { - const CognitoIdToken = () => {} + const CognitoIdToken = () => {}; - CognitoIdToken.prototype.CognitoIdToken = (value) => { - CognitoIdToken.prototype.idToken = value; - return CognitoIdToken; - } + CognitoIdToken.prototype.CognitoIdToken = value => { + CognitoIdToken.prototype.idToken = value; + return CognitoIdToken; + }; - CognitoIdToken.prototype.getJwtToken = () => { - return 'jwtToken'; - } + CognitoIdToken.prototype.getJwtToken = () => { + return 'jwtToken'; + }; - - return CognitoIdToken; + return CognitoIdToken; }); jest.mock('amazon-cognito-identity-js/lib/CognitoUserPool', () => { - const CognitoUserPool = () => {}; - - CognitoUserPool.prototype.CognitoUserPool = (options) => { - CognitoUserPool.prototype.options = options; - return CognitoUserPool; - } - - CognitoUserPool.prototype.getCurrentUser = () => { - return "currentUser"; - } - - CognitoUserPool.prototype.signUp = (username, password, signUpAttributeList, validationData, callback) => { - callback(null, 'signUpResult'); - } - CognitoUserPool.prototype.storage = { - sync: (callback) => { - callback(null, 'data'); - } - } - - return CognitoUserPool; + const CognitoUserPool = () => {}; + + CognitoUserPool.prototype.CognitoUserPool = options => { + CognitoUserPool.prototype.options = options; + return CognitoUserPool; + }; + + CognitoUserPool.prototype.getCurrentUser = () => { + return 'currentUser'; + }; + + CognitoUserPool.prototype.signUp = ( + username, + password, + signUpAttributeList, + validationData, + callback + ) => { + callback(null, 'signUpResult'); + }; + CognitoUserPool.prototype.storage = { + sync: callback => { + callback(null, 'data'); + }, + }; + + return CognitoUserPool; }); jest.mock('amazon-cognito-identity-js/lib/CognitoUser', () => { - const CognitoUser = () => {} - - CognitoUser.prototype.CognitoUser = (options) => { - CognitoUser.prototype.options = options; - return CognitoUser; - } - - CognitoUser.prototype.getSession = (callback) => { - // throw 3; - callback(null, "session"); - } - - CognitoUser.prototype.getUserAttributes = (callback) => { - callback(null, "attributes"); - } - - CognitoUser.prototype.getAttributeVerificationCode = (attr, callback) => { - callback.onSuccess("success"); - } - - CognitoUser.prototype.verifyAttribute = (attr, code, callback) => { - callback.onSuccess("success"); - } - - CognitoUser.prototype.authenticateUser = (authenticationDetails, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.sendMFACode = (code, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.resendConfirmationCode = (callback) => { - callback(null, 'result'); - } - - CognitoUser.prototype.forgotPassword = (callback) => { - callback.onSuccess(); - } - - CognitoUser.prototype.confirmPassword = (code, password, callback) => { - callback.onSuccess(); - } - - CognitoUser.prototype.signOut = () => { - - } - - CognitoUser.prototype.confirmRegistration = (confirmationCode, forceAliasCreation, callback) => { - callback(null, 'Success'); - } - - CognitoUser.prototype.completeNewPasswordChallenge = (password, requiredAttributes, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.updateAttributes = (attributeList, callback) { - callback(null, 'SUCCESS'); - } - - return CognitoUser; + const CognitoUser = () => {}; + + CognitoUser.prototype.CognitoUser = options => { + CognitoUser.prototype.options = options; + return CognitoUser; + }; + + CognitoUser.prototype.getSession = callback => { + // throw 3; + callback(null, 'session'); + }; + + CognitoUser.prototype.getUserAttributes = callback => { + callback(null, 'attributes'); + }; + + CognitoUser.prototype.getAttributeVerificationCode = (attr, callback) => { + callback.onSuccess('success'); + }; + + CognitoUser.prototype.verifyAttribute = (attr, code, callback) => { + callback.onSuccess('success'); + }; + + CognitoUser.prototype.authenticateUser = ( + authenticationDetails, + callback + ) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.sendMFACode = (code, callback) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.resendConfirmationCode = callback => { + callback(null, 'result'); + }; + + CognitoUser.prototype.forgotPassword = callback => { + callback.onSuccess(); + }; + + CognitoUser.prototype.confirmPassword = (code, password, callback) => { + callback.onSuccess(); + }; + + CognitoUser.prototype.signOut = () => {}; + + CognitoUser.prototype.confirmRegistration = ( + confirmationCode, + forceAliasCreation, + callback + ) => { + callback(null, 'Success'); + }; + + CognitoUser.prototype.completeNewPasswordChallenge = ( + password, + requiredAttributes, + callback + ) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.updateAttributes = (attributeList, callback) => { + callback(null, 'SUCCESS'); + }; + + return CognitoUser; }); jest.mock('@aws-amplify/core', () => { - return { - Platform: { - isReactNative: true - } - } + return { + Platform: { + isReactNative: true, + }, + }; }); import { AuthOptions, SignUpParams } from '../src/types'; import Auth from '../src'; import Cache from '@aws-amplify/cache'; -import { CognitoUserPool, CognitoUser, CognitoUserSession, CognitoIdToken, CognitoAccessToken } from 'amazon-cognito-identity-js'; +import { + CognitoUserPool, + CognitoUser, + CognitoUserSession, + CognitoIdToken, + CognitoAccessToken, +} from 'amazon-cognito-identity-js'; import { CognitoIdentityCredentials } from 'aws-sdk'; import { Credentials } from '@aws-amplify/core'; -const authOptions : AuthOptions = { - userPoolId: "awsUserPoolsId", - userPoolWebClientId: "awsUserPoolsWebClientId", - region: "region", - identityPoolId: "awsCognitoIdentityPoolId", - mandatorySignIn: false -} - -const authOptionsWithNoUserPoolId : AuthOptions = { - userPoolId: null, - userPoolWebClientId: "awsUserPoolsWebClientId", - region: "region", - identityPoolId: "awsCognitoIdentityPoolId", - mandatorySignIn: false -} +const authOptions: AuthOptions = { + userPoolId: 'awsUserPoolsId', + userPoolWebClientId: 'awsUserPoolsWebClientId', + region: 'region', + identityPoolId: 'awsCognitoIdentityPoolId', + mandatorySignIn: false, +}; + +const authOptionsWithNoUserPoolId: AuthOptions = { + userPoolId: null, + userPoolWebClientId: 'awsUserPoolsWebClientId', + region: 'region', + identityPoolId: 'awsCognitoIdentityPoolId', + mandatorySignIn: false, +}; const userPool = new CognitoUserPool({ - UserPoolId: authOptions.userPoolId, - ClientId: authOptions.userPoolWebClientId + UserPoolId: authOptions.userPoolId, + ClientId: authOptions.userPoolWebClientId, }); -const idToken = new CognitoIdToken({IdToken: 'idToken'}); -const accessToken = new CognitoAccessToken({AccessToken: 'accessToken'}); +const idToken = new CognitoIdToken({ IdToken: 'idToken' }); +const accessToken = new CognitoAccessToken({ AccessToken: 'accessToken' }); const session = new CognitoUserSession({ - IdToken: idToken, - AccessToken: accessToken + IdToken: idToken, + AccessToken: accessToken, }); -const cognitoCredentialSpyon = jest.spyOn(CognitoIdentityCredentials.prototype, 'get').mockImplementation((callback) => { - callback(null); -}) +const cognitoCredentialSpyon = jest + .spyOn(CognitoIdentityCredentials.prototype, 'get') + .mockImplementation(callback => { + callback(null); + }); describe('for react native', () => { - describe('currentUserCredentials test', () => { - test('with federated info', async () => { - // const auth = new Auth(authOptions); - - // const spyon = jest.spyOn(Credentials, 'currentUserCredentials'); - - // await auth.currentUserCredentials(); - // expect(spyon).toBeCalled(); - - // spyon.mockClear(); - expect(1).toBe(1); - }); - }); -}) \ No newline at end of file + describe('currentUserCredentials test', () => { + test('with federated info', async () => { + // const auth = new Auth(authOptions); + + // const spyon = jest.spyOn(Credentials, 'currentUserCredentials'); + + // await auth.currentUserCredentials(); + // expect(spyon).toBeCalled(); + + // spyon.mockClear(); + expect(1).toBe(1); + }); + }); +}); diff --git a/packages/auth/__tests__/totp-unit-test.ts b/packages/auth/__tests__/totp-unit-test.ts index 7a7f7269d02..1fc13e8c772 100644 --- a/packages/auth/__tests__/totp-unit-test.ts +++ b/packages/auth/__tests__/totp-unit-test.ts @@ -1,406 +1,455 @@ jest.mock('amazon-cognito-identity-js/lib/CognitoUserSession', () => { - const CognitoUserSession = () => {} - - CognitoUserSession.prototype.CognitoUserSession = (options) => { - CognitoUserSession.prototype.options = options; - return CognitoUserSession; - } - - CognitoUserSession.prototype.getIdToken = () => { - return { - getJwtToken: () => { - return null; - } - } - } - - return CognitoUserSession; + const CognitoUserSession = () => {}; + + CognitoUserSession.prototype.CognitoUserSession = options => { + CognitoUserSession.prototype.options = options; + return CognitoUserSession; + }; + + CognitoUserSession.prototype.getIdToken = () => { + return { + getJwtToken: () => { + return null; + }, + }; + }; + + return CognitoUserSession; }); jest.mock('amazon-cognito-identity-js/lib/CognitoIdToken', () => { - const CognitoIdToken = () => {} + const CognitoIdToken = () => {}; - CognitoIdToken.prototype.CognitoIdToken = (value) => { - CognitoIdToken.prototype.idToken = value; - return CognitoIdToken; - } + CognitoIdToken.prototype.CognitoIdToken = value => { + CognitoIdToken.prototype.idToken = value; + return CognitoIdToken; + }; - CognitoIdToken.prototype.getJwtToken = () => { - return 'jwtToken'; - } + CognitoIdToken.prototype.getJwtToken = () => { + return 'jwtToken'; + }; - - return CognitoIdToken; + return CognitoIdToken; }); jest.mock('amazon-cognito-identity-js/lib/CognitoUserPool', () => { - const CognitoUserPool = () => {}; - - CognitoUserPool.prototype.CognitoUserPool = (options) => { - CognitoUserPool.prototype.options = options; - return CognitoUserPool; - } - - CognitoUserPool.prototype.getCurrentUser = () => { - return "currentUser"; - } - - CognitoUserPool.prototype.signUp = (username, password, signUpAttributeList, validationData, callback) => { - callback(null, 'signUpResult'); - } - - return CognitoUserPool; + const CognitoUserPool = () => {}; + + CognitoUserPool.prototype.CognitoUserPool = options => { + CognitoUserPool.prototype.options = options; + return CognitoUserPool; + }; + + CognitoUserPool.prototype.getCurrentUser = () => { + return 'currentUser'; + }; + + CognitoUserPool.prototype.signUp = ( + username, + password, + signUpAttributeList, + validationData, + callback + ) => { + callback(null, 'signUpResult'); + }; + + return CognitoUserPool; }); jest.mock('amazon-cognito-identity-js/lib/CognitoUser', () => { - const CognitoUser = () => {} - - CognitoUser.prototype.CognitoUser = (options) => { - CognitoUser.prototype.options = options; - return CognitoUser; - } - - CognitoUser.prototype.getSession = (callback) => { - // throw 3; - callback(null, "session"); - } - - CognitoUser.prototype.getUserAttributes = (callback) => { - callback(null, "attributes"); - } - - CognitoUser.prototype.getAttributeVerificationCode = (attr, callback) => { - callback.onSuccess("success"); - } - - CognitoUser.prototype.verifyAttribute = (attr, code, callback) => { - callback.onSuccess("success"); - } - - CognitoUser.prototype.authenticateUser = (authenticationDetails, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.sendMFACode = (code, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.resendConfirmationCode = (callback) => { - callback(null, 'result'); - } - - CognitoUser.prototype.changePassword = (oldPassword, newPassword, callback) => { - callback(null, 'SUCCESS'); - } - - CognitoUser.prototype.forgotPassword = (callback) => { - callback.onSuccess(); - } - - CognitoUser.prototype.confirmPassword = (code, password, callback) => { - callback.onSuccess(); - } - - CognitoUser.prototype.signOut = () => { - - } - - CognitoUser.prototype.confirmRegistration = (confirmationCode, forceAliasCreation, callback) => { - callback(null, 'Success'); - } - - CognitoUser.prototype.completeNewPasswordChallenge = (password, requiredAttributes, callback) => { - callback.onSuccess('session'); - } - - CognitoUser.prototype.updateAttributes = (attributeList, callback) { - callback(null, 'SUCCESS'); - } - - CognitoUser.prototype.getMFAOptions = (callback) => { - callback(null, 'mfaOptions'); - } - - CognitoUser.prototype.disableMFA = (callback) => { - callback(null, 'Success'); - } - - CognitoUser.prototype.enableMFA = (callback) => { - callback(null, 'Success'); - } - - CognitoUser.prototype.associateSoftwareToken = (callback) => { - callback.associateSecretCode('secretCode'); - //callback.onFailure() - } - - CognitoUser.prototype.verifySoftwareToken = (challengeAnswer, device, callback) => { - callback.onSuccess('Success'); - }; - - CognitoUser.prototype.setUserMfaPreference = (smsMfaSettings, totpMfaSettings, callback) => { - callback(null, 'Success'); - } - - CognitoUser.prototype.getUserData = (callback) => { - callback(null, { - PreferredMfaSetting: 'SMS_MFA' - }); - } - - return CognitoUser; + const CognitoUser = () => {}; + + CognitoUser.prototype.CognitoUser = options => { + CognitoUser.prototype.options = options; + return CognitoUser; + }; + + CognitoUser.prototype.getSession = callback => { + // throw 3; + callback(null, 'session'); + }; + + CognitoUser.prototype.getUserAttributes = callback => { + callback(null, 'attributes'); + }; + + CognitoUser.prototype.getAttributeVerificationCode = (attr, callback) => { + callback.onSuccess('success'); + }; + + CognitoUser.prototype.verifyAttribute = (attr, code, callback) => { + callback.onSuccess('success'); + }; + + CognitoUser.prototype.authenticateUser = ( + authenticationDetails, + callback + ) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.sendMFACode = (code, callback) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.resendConfirmationCode = callback => { + callback(null, 'result'); + }; + + CognitoUser.prototype.changePassword = ( + oldPassword, + newPassword, + callback + ) => { + callback(null, 'SUCCESS'); + }; + + CognitoUser.prototype.forgotPassword = callback => { + callback.onSuccess(); + }; + + CognitoUser.prototype.confirmPassword = (code, password, callback) => { + callback.onSuccess(); + }; + + CognitoUser.prototype.signOut = () => {}; + + CognitoUser.prototype.confirmRegistration = ( + confirmationCode, + forceAliasCreation, + callback + ) => { + callback(null, 'Success'); + }; + + CognitoUser.prototype.completeNewPasswordChallenge = ( + password, + requiredAttributes, + callback + ) => { + callback.onSuccess('session'); + }; + + CognitoUser.prototype.updateAttributes = (attributeList, callback) => { + callback(null, 'SUCCESS'); + }; + + CognitoUser.prototype.getMFAOptions = callback => { + callback(null, 'mfaOptions'); + }; + + CognitoUser.prototype.disableMFA = callback => { + callback(null, 'Success'); + }; + + CognitoUser.prototype.enableMFA = callback => { + callback(null, 'Success'); + }; + + CognitoUser.prototype.associateSoftwareToken = callback => { + callback.associateSecretCode('secretCode'); + //callback.onFailure() + }; + + CognitoUser.prototype.verifySoftwareToken = ( + challengeAnswer, + device, + callback + ) => { + callback.onSuccess('Success'); + }; + + CognitoUser.prototype.setUserMfaPreference = ( + smsMfaSettings, + totpMfaSettings, + callback + ) => { + callback(null, 'Success'); + }; + + CognitoUser.prototype.getUserData = callback => { + callback(null, { + PreferredMfaSetting: 'SMS_MFA', + }); + }; + + return CognitoUser; }); - - import { AuthOptions, SignUpParams } from '../src/types'; import Auth from '../src/Auth'; import Cache from '@aws-amplify/cache'; -import { CognitoUserPool, CognitoUser, CognitoUserSession, CognitoIdToken, CognitoAccessToken } from 'amazon-cognito-identity-js'; +import { + CognitoUserPool, + CognitoUser, + CognitoUserSession, + CognitoIdToken, + CognitoAccessToken, +} from 'amazon-cognito-identity-js'; import { CognitoIdentityCredentials } from 'aws-sdk'; - const authOptions = { - Auth: { - userPoolId: "awsUserPoolsId", - userPoolWebClientId: "awsUserPoolsWebClientId", - region: "region", - identityPoolId: "awsCognitoIdentityPoolId" - } -} + Auth: { + userPoolId: 'awsUserPoolsId', + userPoolWebClientId: 'awsUserPoolsWebClientId', + region: 'region', + identityPoolId: 'awsCognitoIdentityPoolId', + }, +}; const authOptionsWithNoUserPoolId = { - Auth: { - userPoolId: null, - userPoolWebClientId: "awsUserPoolsWebClientId", - region: "region", - identityPoolId: "awsCognitoIdentityPoolId" - } -} + Auth: { + userPoolId: null, + userPoolWebClientId: 'awsUserPoolsWebClientId', + region: 'region', + identityPoolId: 'awsCognitoIdentityPoolId', + }, +}; const userPool = new CognitoUserPool({ - UserPoolId: authOptions.Auth.userPoolId, - ClientId: authOptions.Auth.userPoolWebClientId + UserPoolId: authOptions.Auth.userPoolId, + ClientId: authOptions.Auth.userPoolWebClientId, }); -const idToken = new CognitoIdToken({IdToken: 'idToken'}); -const accessToken = new CognitoAccessToken({AccessToken: 'accessToken'}); +const idToken = new CognitoIdToken({ IdToken: 'idToken' }); +const accessToken = new CognitoAccessToken({ AccessToken: 'accessToken' }); const session = new CognitoUserSession({ - IdToken: idToken, - AccessToken: accessToken + IdToken: idToken, + AccessToken: accessToken, }); const user = new CognitoUser({ - Username: "username", - Pool: userPool + Username: 'username', + Pool: userPool, }); describe('auth unit test', () => { - describe('getMFAOptions test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "getMFAOptions"); - expect(await auth.getMFAOptions(user)).toBe('mfaOptions'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - }); - - test('err case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "getMFAOptions").mockImplementationOnce((callback) => { - callback('err', null); - }); - try { - await auth.getMFAOptions(user); - } catch (e) { - expect(e).toBe('err'); - } - expect(spyon).toBeCalled(); - spyon.mockClear(); - }); - }); - - describe('disableMFA test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "disableMFA"); - expect(await auth.disableSMS(user)).toBe('Success'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - }); - - test('err case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "disableMFA").mockImplementationOnce((callback) => { - callback('err', null); - }); - try { - await auth.disableSMS(user); - } catch (e) { - expect(e).toBe('err'); - } - expect(spyon).toBeCalled(); - spyon.mockClear(); - }); - }); - - describe('enableMFA test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "enableMFA"); - expect(await auth.enableSMS(user)).toBe('Success'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - }); - - test('err case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "enableMFA").mockImplementationOnce((callback) => { - callback('err', null); - }); - try { - await auth.enableSMS(user); - } catch (e) { - expect(e).toBe('err'); - } - expect(spyon).toBeCalled(); - spyon.mockClear(); - }); - }); - - describe('setupTOTP test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "associateSoftwareToken"); - expect(await auth.setupTOTP(user)).toBe('secretCode'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - }); - - test('err case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "associateSoftwareToken").mockImplementationOnce((callback) => { - callback.onFailure('err'); - }); - try { - await auth.setupTOTP(user); - } catch (e) { - expect(e).toBe('err'); - } - expect(spyon).toBeCalled(); - spyon.mockClear(); - }); - }); - - describe('verifyTotpToken test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "verifySoftwareToken"); - expect(await auth.verifyTotpToken(user, 'challengeAnswer')).toBe('Success'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - }); - - test('err case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "verifySoftwareToken").mockImplementationOnce((challengeAnswer, device, callback) => { - callback.onFailure('err'); - }); - try { - await auth.verifyTotpToken(user, 'challengeAnswer'); - } catch (e) { - expect(e).toBe('err'); - } - expect(spyon).toBeCalled(); - spyon.mockClear(); - }); - }); - - describe('setPreferredMFA test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "setUserMfaPreference"); - const spyon2 = jest.spyOn(Auth.prototype, 'getPreferredMFA').mockImplementationOnce(() => { - return Promise.resolve('SMS_MFA') - }); - expect(await auth.setPreferredMFA(user, 'TOTP')).toBe('Success'); - expect(spyon).toBeCalled(); - - spyon.mockClear(); - spyon2.mockClear(); - }); - - 'User has not verified software token mfa' - - test('totp not setup but TOTP chosed', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, "setUserMfaPreference").mockImplementationOnce((smsMfaSettings, totpMfaSettings, callback) => { - const err = { - message: 'User has not verified software token mfa' - } - callback(err, null); - }); - const spyon2 = jest.spyOn(Auth.prototype, 'getPreferredMFA').mockImplementationOnce(() => { - return Promise.resolve('SMS_MFA') - }); - - try { - await auth.setPreferredMFA(user, 'TOTP'); - } catch (e) { - expect(e).not.toBeNull(); - } - expect(spyon).toBeCalled(); - - spyon.mockClear(); - spyon2.mockClear(); - }); - - test('incorrect mfa type', async () => { - const auth = new Auth(authOptions); - try { - await auth.setPreferredMFA(user, 'incorrect mfa type'); - } catch (e) { - expect(e).not.toBeNull(); - } - }); - }); - - describe('getPreferredMFA test', () => { - test('happy case', async () => { - const auth = new Auth(authOptions); - - expect(await auth.getPreferredMFA(user)).toBe('SMS_MFA'); - }); - - test('error case', async () => { - const auth = new Auth(authOptions); - - const spyon = jest.spyOn(CognitoUser.prototype, 'getUserData').mockImplementationOnce(callback => { - callback('err', null); - }) - try { - await auth.getPreferredMFA(user); - } catch (e) { - expect(e).toBe('err'); - } - }); - }); -}); \ No newline at end of file + describe('getMFAOptions test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'getMFAOptions'); + expect(await auth.getMFAOptions(user)).toBe('mfaOptions'); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + }); + + test('err case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'getMFAOptions') + .mockImplementationOnce(callback => { + callback('err', null); + }); + try { + await auth.getMFAOptions(user); + } catch (e) { + expect(e).toBe('err'); + } + expect(spyon).toBeCalled(); + spyon.mockClear(); + }); + }); + + describe('disableMFA test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'disableMFA'); + expect(await auth.disableSMS(user)).toBe('Success'); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + }); + + test('err case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'disableMFA') + .mockImplementationOnce(callback => { + callback('err', null); + }); + try { + await auth.disableSMS(user); + } catch (e) { + expect(e).toBe('err'); + } + expect(spyon).toBeCalled(); + spyon.mockClear(); + }); + }); + + describe('enableMFA test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'enableMFA'); + expect(await auth.enableSMS(user)).toBe('Success'); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + }); + + test('err case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'enableMFA') + .mockImplementationOnce(callback => { + callback('err', null); + }); + try { + await auth.enableSMS(user); + } catch (e) { + expect(e).toBe('err'); + } + expect(spyon).toBeCalled(); + spyon.mockClear(); + }); + }); + + describe('setupTOTP test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'associateSoftwareToken'); + expect(await auth.setupTOTP(user)).toBe('secretCode'); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + }); + + test('err case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'associateSoftwareToken') + .mockImplementationOnce(callback => { + callback.onFailure('err'); + }); + try { + await auth.setupTOTP(user); + } catch (e) { + expect(e).toBe('err'); + } + expect(spyon).toBeCalled(); + spyon.mockClear(); + }); + }); + + describe('verifyTotpToken test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'verifySoftwareToken'); + expect(await auth.verifyTotpToken(user, 'challengeAnswer')).toBe( + 'Success' + ); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + }); + + test('err case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'verifySoftwareToken') + .mockImplementationOnce((challengeAnswer, device, callback) => { + callback.onFailure('err'); + }); + try { + await auth.verifyTotpToken(user, 'challengeAnswer'); + } catch (e) { + expect(e).toBe('err'); + } + expect(spyon).toBeCalled(); + spyon.mockClear(); + }); + }); + + describe('setPreferredMFA test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest.spyOn(CognitoUser.prototype, 'setUserMfaPreference'); + const spyon2 = jest + .spyOn(Auth.prototype, 'getPreferredMFA') + .mockImplementationOnce(() => { + return Promise.resolve('SMS_MFA'); + }); + expect(await auth.setPreferredMFA(user, 'TOTP')).toBe('Success'); + expect(spyon).toBeCalled(); + + spyon.mockClear(); + spyon2.mockClear(); + }); + + 'User has not verified software token mfa'; + + test('totp not setup but TOTP chosed', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'setUserMfaPreference') + .mockImplementationOnce((smsMfaSettings, totpMfaSettings, callback) => { + const err = { + message: 'User has not verified software token mfa', + }; + callback(err, null); + }); + const spyon2 = jest + .spyOn(Auth.prototype, 'getPreferredMFA') + .mockImplementationOnce(() => { + return Promise.resolve('SMS_MFA'); + }); + + try { + await auth.setPreferredMFA(user, 'TOTP'); + } catch (e) { + expect(e).not.toBeNull(); + } + expect(spyon).toBeCalled(); + + spyon.mockClear(); + spyon2.mockClear(); + }); + + test('incorrect mfa type', async () => { + const auth = new Auth(authOptions); + try { + await auth.setPreferredMFA(user, 'incorrect mfa type'); + } catch (e) { + expect(e).not.toBeNull(); + } + }); + }); + + describe('getPreferredMFA test', () => { + test('happy case', async () => { + const auth = new Auth(authOptions); + + expect(await auth.getPreferredMFA(user)).toBe('SMS_MFA'); + }); + + test('error case', async () => { + const auth = new Auth(authOptions); + + const spyon = jest + .spyOn(CognitoUser.prototype, 'getUserData') + .mockImplementationOnce(callback => { + callback('err', null); + }); + try { + await auth.getPreferredMFA(user); + } catch (e) { + expect(e).toBe('err'); + } + }); + }); +}); diff --git a/packages/auth/build.js b/packages/auth/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/auth/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/auth/index-rn.js b/packages/auth/index-rn.js new file mode 100644 index 00000000000..b918804d60f --- /dev/null +++ b/packages/auth/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib-esm/index.js'); diff --git a/packages/auth/index.js b/packages/auth/index.js new file mode 100644 index 00000000000..59ff98ebd70 --- /dev/null +++ b/packages/auth/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-auth.min.js'); +} else { + module.exports = require('./dist/aws-amplify-auth.js'); +} diff --git a/packages/auth/package.json b/packages/auth/package.json index 1a6e086d001..6c794affae0 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -2,53 +2,35 @@ "name": "@aws-amplify/auth", "version": "1.4.2", "description": "Auth category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "test:watch": "tslint 'src/**/*.ts' && jest --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "build:watch": "npm run clean && tsc --watch", - "clean": "rimraf lib lib-esm dist", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/cache": "^1.1.2", "@aws-amplify/core": "^1.2.2", @@ -56,9 +38,25 @@ "crypto-js": "^3.1.9-1" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, + "preset": "ts-jest", "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ "ts", diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/auth/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/auth/webpack.config.dev.js b/packages/auth/webpack.config.dev.js new file mode 100644 index 00000000000..962b8a7cc63 --- /dev/null +++ b/packages/auth/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-auth': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/auth/webpack.config.js b/packages/auth/webpack.config.js index 7a97e3e87a3..29792425ad2 100644 --- a/packages/auth/webpack.config.js +++ b/packages/auth/webpack.config.js @@ -1,14 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-auth': './src/index.ts', - 'aws-amplify-auth.min': './src/index.ts', - }, - externals: { - 'react-native': 'react-native', + 'aws-amplify-auth.min': './lib-esm/index.js', }, + externals: ['react-native', '@aws-amplify/cache', '@aws-amplify/core'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -21,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/aws-amplify-angular/jest.config.js b/packages/aws-amplify-angular/jest.config.js index 8745d831aed..85dbae0998d 100644 --- a/packages/aws-amplify-angular/jest.config.js +++ b/packages/aws-amplify-angular/jest.config.js @@ -1,6 +1,6 @@ module.exports = { preset: 'jest-preset-angular', roots: ['src'], - setupTestFrameworkScriptFile: '/test_setup/setup-jest.ts', + setupFilesAfterEnv: ['/test_setup/setup-jest.ts'], testURL: 'http://localhost/', }; diff --git a/packages/aws-amplify-angular/package.json b/packages/aws-amplify-angular/package.json index 24e645f0747..6ec41573244 100644 --- a/packages/aws-amplify-angular/package.json +++ b/packages/aws-amplify-angular/package.json @@ -8,7 +8,7 @@ "scripts": { "cleantemp": "rimraf coverage dist tmp docs", "ngcompile": "node_modules/.bin/ngc -p tsconfig-aot.json", - "test": "jest --maxWorkers 2", + "test": "jest -w 1 --maxWorkers 2", "transpile": "ngc", "package": "rollup -c rollup.config.js", "minify": "uglifyjs dist/bundles/aws-amplify-angular.umd.js --screw-ie8 --compress --mangle --comments --output dist/bundles/aws-amplify-angular.umd.min.js", @@ -31,7 +31,6 @@ "@angular/forms": "^6.0.3", "@angular/platform-browser": "^5.2.9", "@angular/platform-browser-dynamic": "^5.2.9", - "@types/jest": "^23.1.5", "@types/lodash": "^4.14.106", "@types/node": "^9.4.6", "@types/paho-mqtt": "^1.0.3", @@ -44,8 +43,7 @@ "babel-preset-env": "^1.7.0", "babel-preset-es2015": "^6.24.1", "css-loader": "^0.28.1", - "jest": "^23.4.0", - "jest-preset-angular": "^5.2.3", + "jest-preset-angular": "^7.1.1", "json-loader": "^0.5.4", "ng-mocks": "7.x.x", "raw-loader": "^0.5.1", diff --git a/packages/aws-amplify-angular/src/__tests__/components/authenticator/require-new-password.component.ionic.spec.ts b/packages/aws-amplify-angular/src/__tests__/components/authenticator/require-new-password.component.ionic.spec.ts index 63bc4a939ab..7ea27d0d103 100644 --- a/packages/aws-amplify-angular/src/__tests__/components/authenticator/require-new-password.component.ionic.spec.ts +++ b/packages/aws-amplify-angular/src/__tests__/components/authenticator/require-new-password.component.ionic.spec.ts @@ -95,9 +95,9 @@ describe('RequireNewPasswordComponentCore: ', () => { 'ion-button' ); const signInButton = Object.values(buttons).find( - el => el.innerHTML === 'Back to Sign In' + el => (el as HTMLElement).innerHTML === 'Back to Sign In' ); - signInButton.click(); + (signInButton as HTMLElement).click(); expect(onSignInSpy).toHaveBeenCalled(); }); @@ -112,9 +112,9 @@ describe('RequireNewPasswordComponentCore: ', () => { 'ion-button' ); const submitButton = Object.values(buttons).find( - el => el.innerHTML === 'Submit' + el => (el as any).innerHTML === 'Submit' ); - submitButton.click(); + (submitButton as any).click(); expect(onSubmitSpy).toHaveBeenCalled(); }); }); diff --git a/packages/aws-amplify-angular/src/__tests__/components/storage/s3-album.component.spec.ts b/packages/aws-amplify-angular/src/__tests__/components/storage/s3-album.component.spec.ts index ea7eef89731..4246b8d2a89 100644 --- a/packages/aws-amplify-angular/src/__tests__/components/storage/s3-album.component.spec.ts +++ b/packages/aws-amplify-angular/src/__tests__/components/storage/s3-album.component.spec.ts @@ -26,13 +26,3 @@ describe('S3AlbumComponentCore: ', () => { expect(component).toBeTruthy(); }); }); - -describe('S3AlbumComponentIonic: ', () => { - let component: S3AlbumComponentIonic; - let service: AmplifyService; - - beforeEach(() => { - service = new AmplifyService(); - component = new S3AlbumComponentCore(service); - }); -}); diff --git a/packages/aws-amplify-angular/test_setup/setup-jest.ts b/packages/aws-amplify-angular/test_setup/setup-jest.ts index d81ecbe1a6b..0381fc3c0bb 100644 --- a/packages/aws-amplify-angular/test_setup/setup-jest.ts +++ b/packages/aws-amplify-angular/test_setup/setup-jest.ts @@ -4,21 +4,22 @@ window.alert = msg => { console.log(msg); }; -function noOp() {} +function noOp(): any {} if (typeof window.URL.createObjectURL === 'undefined') { Object.defineProperty(window.URL, 'createObjectURL', { value: noOp }); } -class Worker { - constructor(stringUrl) { - this.url = stringUrl; - this.onmessage = () => {}; - } - - postMessage(msg) { - this.onmessage(msg); +class MockWorker implements Worker { + onmessage = noOp; + postMessage = noOp; + terminate = noOp; + addEventListener = noOp; + removeEventListener = noOp; + onerror = noOp; + dispatchEvent(event: Event): boolean { + throw new Error('Method not implemented.'); } } -window.Worker = Worker; +window.Worker = MockWorker; diff --git a/packages/aws-amplify-react-native/package.json b/packages/aws-amplify-react-native/package.json index 9d94b8b7593..bc24d7ab2db 100644 --- a/packages/aws-amplify-react-native/package.json +++ b/packages/aws-amplify-react-native/package.json @@ -4,7 +4,7 @@ "description": "AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.", "main": "dist/index.js", "scripts": { - "test": "jest --passWithNoTests --coverage --maxWorkers 2", + "test": "jest -w 1 --passWithNoTests --coverage --maxWorkers 2", "build": "npm run clean && babel src --out-dir dist --copy-files", "watch": "npm run clean && babel src --out-dir dist --copy-files --watch", "generate-docs": "rimraf docs && jsdoc -c ./jsDoc.config.json --readme ../../media/api_reference_home.md ./src -r -d ./docs", @@ -35,7 +35,7 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.git" + "url": "https://github.com/aws-amplify/amplify-js.git" }, "author": "Amazon Web Services", "license": "Apache-2.0" diff --git a/packages/aws-amplify-react/__tests__/Auth/Provider/withAuth0-test.tsx b/packages/aws-amplify-react/__tests__/Auth/Provider/withAuth0-test.tsx index 5c644bb0b39..54e8362c372 100644 --- a/packages/aws-amplify-react/__tests__/Auth/Provider/withAuth0-test.tsx +++ b/packages/aws-amplify-react/__tests__/Auth/Provider/withAuth0-test.tsx @@ -1,5 +1,5 @@ import Auth from '@aws-amplify/auth'; -import React, { Component } from 'react'; +import * as React from 'react'; import withAuth0, { Auth0Button } from '../../../src/Auth/Provider/withAuth0'; import { SignInButton, Button } from '../../../src/AmplifyUI'; @@ -16,7 +16,7 @@ const auth0_config = { describe('withAuth0 test', () => { describe('render test', () => { test('render correctly', () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -30,7 +30,7 @@ describe('withAuth0 test', () => { describe('signIn test', () => { test('happy case', async () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -47,13 +47,13 @@ describe('withAuth0 test', () => { try { await comp.signIn(); expect(mockFn).toBeCalled(); - } catch (e) {} + } catch (e) { } }); }); describe('initialize test', () => { test('happy case', async () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -99,7 +99,7 @@ describe('withAuth0 test', () => { }); test('return if parse hash failed', async () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -139,7 +139,7 @@ describe('withAuth0 test', () => { }); test('directly return if in signedin state', async () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -179,7 +179,7 @@ describe('withAuth0 test', () => { }); test('directly return if no auth0 config', async () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } diff --git a/packages/aws-amplify-react/__tests__/Auth/Provider/withOAuth-test.tsx b/packages/aws-amplify-react/__tests__/Auth/Provider/withOAuth-test.tsx index d10261577c8..d9132ffba78 100644 --- a/packages/aws-amplify-react/__tests__/Auth/Provider/withOAuth-test.tsx +++ b/packages/aws-amplify-react/__tests__/Auth/Provider/withOAuth-test.tsx @@ -1,13 +1,11 @@ import Auth from '@aws-amplify/auth'; import * as React from 'react'; -import { Component } from 'react'; import withOAuth, { OAuthButton } from '../../../src/Auth/Provider/withOAuth'; -import { SignInButton, Button } from '../../../src/AmplifyUI'; describe('withOAuth test', () => { describe('render test', () => { test('render correctly', () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -26,7 +24,7 @@ describe('withOAuth test', () => { describe('signIn test', () => { test('happy case with connected response', () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } @@ -45,7 +43,7 @@ describe('withOAuth test', () => { }); test('Passing in a social provider', () => { - const MockComp = class extends Component { + const MockComp = class extends React.Component { render() { return
; } diff --git a/packages/aws-amplify-react/__tests__/Widget/__snapshots__/Picker-test.tsx.snap b/packages/aws-amplify-react/__tests__/Widget/__snapshots__/Picker-test.tsx.snap index f7ac7edd8bb..45898c92123 100644 --- a/packages/aws-amplify-react/__tests__/Widget/__snapshots__/Picker-test.tsx.snap +++ b/packages/aws-amplify-react/__tests__/Widget/__snapshots__/Picker-test.tsx.snap @@ -1,7 +1,13 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Picker test render test render correcly 1`] = ` -
+
../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", "moduleFileExtensions": [ diff --git a/packages/aws-amplify-react/src/Auth/Greetings.tsx b/packages/aws-amplify-react/src/Auth/Greetings.tsx index 49bb170be57..b939179b471 100644 --- a/packages/aws-amplify-react/src/Auth/Greetings.tsx +++ b/packages/aws-amplify-react/src/Auth/Greetings.tsx @@ -179,18 +179,19 @@ export default class Greetings extends AuthPiece< // @ts-ignore const auth0_config = auth0 || oauth.auth0; + let SignOutComponent = SignOut; // @ts-ignore - if (googleClientId) SignOut = withGoogle(SignOut); + if (googleClientId) SignOutComponent = withGoogle(SignOut); // @ts-ignore - if (facebookAppId) SignOut = withFacebook(SignOut); + if (facebookAppId) SignOutComponent = withFacebook(SignOut); // @ts-ignore - if (amazonClientId) SignOut = withAmazon(SignOut); + if (amazonClientId) SignOutComponent = withAmazon(SignOut); // @ts-ignore - if (auth0_config) SignOut = withAuth0(SignOut); + if (auth0_config) SignOutComponent = withAuth0(SignOut); const stateAndProps = Object.assign({}, this.props, this.state); - return ; + return ; } noUserGreetings(theme) { diff --git a/packages/aws-amplify-react/test_Setup/enzymeSetup.ts b/packages/aws-amplify-react/test_Setup/enzymeSetup.ts index 6339f2b0487..3aede5b7f67 100644 --- a/packages/aws-amplify-react/test_Setup/enzymeSetup.ts +++ b/packages/aws-amplify-react/test_Setup/enzymeSetup.ts @@ -11,11 +11,11 @@ * and limitations under the License. */ -import Enzyme, { shallow, render, mount } from 'enzyme'; -import Adapter from 'enzyme-adapter-react-16'; +import { configure, shallow, render, mount } from 'enzyme'; +import * as Adapter from 'enzyme-adapter-react-16'; // React 16 Enzyme adapter -Enzyme.configure({ adapter: new Adapter() }); +configure({ adapter: new Adapter() }); // Make Enzyme functions available in all test files without importing global.shallow = shallow; diff --git a/packages/aws-amplify-react/webpack.config.dev.js b/packages/aws-amplify-react/webpack.config.dev.js new file mode 100644 index 00000000000..695ecaf4652 --- /dev/null +++ b/packages/aws-amplify-react/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-react': './lib/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/aws-amplify-react/webpack.config.js b/packages/aws-amplify-react/webpack.config.js new file mode 100644 index 00000000000..ed344ea586c --- /dev/null +++ b/packages/aws-amplify-react/webpack.config.js @@ -0,0 +1,52 @@ +module.exports = { + entry: { + 'aws-amplify-react.min': './lib/index.js', + }, + externals: [ + '@aws-amplify/auth', + '@aws-amplify/analytics', + '@aws-amplify/api', + '@aws-amplify/core', + '@aws-amplify/interactions', + '@aws-amplify/storage', + '@aws-amplify/ui', + '@aws-amplify/ui/dist/style.css', + '@aws-amplify/xr', + 'aws-amplify', + 'react', + ], + output: { + filename: '[name].js', + path: __dirname + '/dist', + library: 'aws_amplify_react', + libraryTarget: 'umd', + umdNamedDefine: true, + 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: [ + // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. + //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, + { + test: /\.js?$/, + exclude: /node_modules/, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], + }, + ], + }, +}; diff --git a/packages/aws-amplify-vue/package.json b/packages/aws-amplify-vue/package.json index a8c07361a9a..ffde6f6d74d 100644 --- a/packages/aws-amplify-vue/package.json +++ b/packages/aws-amplify-vue/package.json @@ -10,7 +10,7 @@ "build": "vue-cli-service build --target lib --name aws-amplify-vue ./src/Amplify.vue", "build-stats": "vue-cli-service build --report --target lib --name aws-amplify-vue ./src/Amplify.vue", "test": "./node_modules/.bin/vue-cli-service test:unit", - "debug": "node --debug-brk --inspect ./node_modules/.bin/jest -i" + "debug": "node --debug-brk --inspect ./node_modules/.bin/jest -w 1 -i" }, "dependencies": { "lodash.orderby": "^4.6.0", diff --git a/packages/aws-amplify/build.js b/packages/aws-amplify/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/aws-amplify/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/aws-amplify/index-rn.js b/packages/aws-amplify/index-rn.js new file mode 100644 index 00000000000..b918804d60f --- /dev/null +++ b/packages/aws-amplify/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib-esm/index.js'); diff --git a/packages/aws-amplify/index.js b/packages/aws-amplify/index.js new file mode 100644 index 00000000000..aed5067be8c --- /dev/null +++ b/packages/aws-amplify/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify.min.js'); +} else { + module.exports = require('./dist/aws-amplify.js'); +} diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index 0d5a7d309f1..c085ebf68f4 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -2,13 +2,19 @@ "name": "aws-amplify", "version": "1.2.2", "description": "AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.", - "main": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "scripts": { - "test": "jest --passWithNoTests --coverage --maxWorkers 2", + "test": "jest -w 1 --passWithNoTests --coverage --maxWorkers 2", "build-with-test": "npm run clean && npm test && tsc && webpack -p", - "build": "npm run clean && tsc && webpack -p", - "clean": "rimraf lib lib-esm dist", + "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", + "build:esm": "node ./build es6", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'", "generate-docs-local": "typedoc --out docs src", @@ -16,34 +22,14 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/analytics": "^1.3.2", "@aws-amplify/api": "^1.2.2", diff --git a/packages/aws-amplify/tsconfig.json b/packages/aws-amplify/tsconfig.json deleted file mode 100755 index eea8410e99f..00000000000 --- a/packages/aws-amplify/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ "./node_modules/@types" ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/aws-amplify/webpack.config.dev.js b/packages/aws-amplify/webpack.config.dev.js new file mode 100644 index 00000000000..238c17bfedc --- /dev/null +++ b/packages/aws-amplify/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify': './lib-esm/index.js', +}; +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 fff42473576..6181ac86df9 100644 --- a/packages/aws-amplify/webpack.config.js +++ b/packages/aws-amplify/webpack.config.js @@ -1,11 +1,19 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify': './src/index.ts', - 'aws-amplify.min': './src/index.ts', + 'aws-amplify.min': './lib-esm/index.js', }, + externals: [ + '@aws-amplify/analytics', + '@aws-amplify/api', + '@aws-amplify/auth', + '@aws-amplify/cache', + '@aws-amplify/core', + '@aws-amplify/interactions', + '@aws-amplify/pubsub', + '@aws-amplify/storage', + '@aws-amplify/ui', + '@aws-amplify/xr', + ], output: { filename: '[name].js', path: __dirname + '/dist', @@ -15,45 +23,28 @@ module.exports = { devtoolModuleFilenameTemplate: require('../aws-amplify/webpack-utils') .devtoolModuleFilenameTemplate, }, - externals: { - 'react-native': 'react-native', - }, // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/cache/build.js b/packages/cache/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/cache/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/cache/index-rn.js b/packages/cache/index-rn.js new file mode 100644 index 00000000000..b918804d60f --- /dev/null +++ b/packages/cache/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib-esm/index.js'); diff --git a/packages/cache/index.js b/packages/cache/index.js new file mode 100644 index 00000000000..1151f669b9a --- /dev/null +++ b/packages/cache/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-cache.min.js'); +} else { + module.exports = require('./dist/aws-amplify-cache.js'); +} diff --git a/packages/cache/package.json b/packages/cache/package.json index b72615c1550..e53056dd463 100644 --- a/packages/cache/package.json +++ b/packages/cache/package.json @@ -2,60 +2,56 @@ "name": "@aws-amplify/cache", "version": "1.1.2", "description": "Cache category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./lib/index.js": "./lib/reactnative.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "clean": "rimraf lib lib-esm dist", - "format": "tsfmt --useTsfmt tsfmt.json -r src/**/*.ts", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", + "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, - "react-native": { - "./lib/index.js": "./lib/reactnative.js" - }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/core": "^1.2.2" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/cache/tsconfig.json b/packages/cache/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/cache/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/cache/webpack.config.dev.js b/packages/cache/webpack.config.dev.js new file mode 100644 index 00000000000..cac1a803e53 --- /dev/null +++ b/packages/cache/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-cache': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/cache/webpack.config.js b/packages/cache/webpack.config.js index 0c9165e2d09..ad238306246 100644 --- a/packages/cache/webpack.config.js +++ b/packages/cache/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-cache': './src/index.ts', - 'aws-amplify-cache.min': './src/index.ts', + 'aws-amplify-cache.min': './lib-esm/index.js', }, + externals: ['@aws-amplify/core', 'react-native'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/core/__tests__/Credentials-test.ts b/packages/core/__tests__/Credentials-test.ts index 3ea844e56b5..9f8b84a6ce7 100644 --- a/packages/core/__tests__/Credentials-test.ts +++ b/packages/core/__tests__/Credentials-test.ts @@ -4,102 +4,101 @@ import Amplify from '../src/Amplify'; import { CognitoIdentityCredentials } from 'aws-sdk'; const authClass = { - getModuleName() { - return 'Auth'; - } - currentUserCredentials() { - return Promise.resolve('cred'); - } -} + getModuleName() { + return 'Auth'; + }, + currentUserCredentials() { + return Promise.resolve('cred'); + }, +}; const cacheClass = { - getModuleName() { - return 'Cache'; - } + getModuleName() { + return 'Cache'; + }, - getItem() { - return null; - } -} + getItem() { + return null; + }, +}; -const cognitoCredentialSpyon = jest.spyOn(CognitoIdentityCredentials.prototype, 'get').mockImplementation((callback) => { - callback(null); -}) +const cognitoCredentialSpyon = jest + .spyOn(CognitoIdentityCredentials.prototype, 'get') + .mockImplementation(callback => { + callback(null); + }); const options = { - userPoolId: "awsUserPoolsId", - userPoolWebClientId: "awsUserPoolsWebClientId", - region: "region", - identityPoolId: "awsCognitoIdentityPoolId", - mandatorySignIn: false -} + userPoolId: 'awsUserPoolsId', + userPoolWebClientId: 'awsUserPoolsWebClientId', + region: 'region', + identityPoolId: 'awsCognitoIdentityPoolId', + mandatorySignIn: false, +}; beforeAll(() => { - AWS.config.update({ - credentials: null, - }); + AWS.config.update({ + credentials: null, + }); }); describe('Credentials test', () => { - describe('configure test', () => { - test('happy case', () => { - const config = { - attr: 'attr' - } - - const credentials = new Credentials(null); - expect(credentials.configure(config)).toEqual({ - attr: 'attr' - }); - }); - }); - - describe('getCredSource test', () => { - test('happy case', () => { - const credentials = new Credentials(null); - credentials['_credentials_source'] = 'source'; - expect(credentials.getCredSource()).toBe('source'); - - }); - }); - - describe('get test', () => { - test('credentials in the memory and not expired', async () => { - Amplify.register(authClass); - Amplify.register(cacheClass); - const credentials = new Credentials(null); - - credentials['_credentials'] = { - expired: false, - expireTime: new Date().getTime() + 20*60*1000 - } - expect(await credentials.get()).toEqual(credentials['_credentials']); - - }); - - test('credentials not in memory or being expired', async () => { - const credentials = new Credentials(null); - - expect(await credentials.get()).toBe('cred'); - }); - }); - - describe.skip('refreshFederatedToken test', () => { - test('federated info and not expired, then refresh it successfully', async () => { - const credentials = new Credentials(null); - }); - - test('federated info and expired, then refresh it successfully', async () => { - const credentials = new Credentials(null); - }); - - test('with federated info and expired, no refresh handler provided', async () => { - const credentials = new Credentials(null); - }); - - test('with federated info and expired, then refresh failed', async () => { - const credentials = new Credentials(null); - }); - }); - -}); \ No newline at end of file + describe('configure test', () => { + test('happy case', () => { + const config = { + attr: 'attr', + }; + + const credentials = new Credentials(null); + expect(credentials.configure(config)).toEqual({ + attr: 'attr', + }); + }); + }); + + describe('getCredSource test', () => { + test('happy case', () => { + const credentials = new Credentials(null); + credentials['_credentials_source'] = 'source'; + expect(credentials.getCredSource()).toBe('source'); + }); + }); + + describe('get test', () => { + test('credentials in the memory and not expired', async () => { + Amplify.register(authClass); + Amplify.register(cacheClass); + const credentials = new Credentials(null); + + credentials['_credentials'] = { + expired: false, + expireTime: new Date().getTime() + 20 * 60 * 1000, + }; + expect(await credentials.get()).toEqual(credentials['_credentials']); + }); + + test('credentials not in memory or being expired', async () => { + const credentials = new Credentials(null); + + expect(await credentials.get()).toBe('cred'); + }); + }); + + describe.skip('refreshFederatedToken test', () => { + test('federated info and not expired, then refresh it successfully', async () => { + const credentials = new Credentials(null); + }); + + test('federated info and expired, then refresh it successfully', async () => { + const credentials = new Credentials(null); + }); + + test('with federated info and expired, no refresh handler provided', async () => { + const credentials = new Credentials(null); + }); + + test('with federated info and expired, then refresh failed', async () => { + const credentials = new Credentials(null); + }); + }); +}); diff --git a/packages/core/__tests__/ServiceWorker-test.ts b/packages/core/__tests__/ServiceWorker-test.ts index de3a731a295..75a362c51c9 100644 --- a/packages/core/__tests__/ServiceWorker-test.ts +++ b/packages/core/__tests__/ServiceWorker-test.ts @@ -17,14 +17,18 @@ describe('ServiceWorker test', () => { return expect(enablePush).toThrow('Service Worker not registered'); }); - test('fails when registering', () => { + test('fails when registering', async () => { global.navigator.serviceWorker = { register: () => Promise.reject('an error'), }; const serviceWorker = new ServiceWorker(); - return expect(serviceWorker.register()).rejects.toThrow('an error'); + try { + await serviceWorker.register(); + } catch (e) { + expect(e).toEqual('an error'); + } }); }); describe('Register with status', () => { diff --git a/packages/core/build.js b/packages/core/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/core/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/core/index-rn.js b/packages/core/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/core/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/core/index.js b/packages/core/index.js new file mode 100644 index 00000000000..59c650a080b --- /dev/null +++ b/packages/core/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-core.min.js'); +} else { + module.exports = require('./dist/aws-amplify-core.js'); +} diff --git a/packages/core/package.json b/packages/core/package.json index 4f5ae3388b2..89a05541d7c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -2,18 +2,19 @@ "name": "@aws-amplify/core", "version": "1.2.2", "description": "Core category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", "publishConfig": { "access": "public" }, "scripts": { - "test": "jest --coverage", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "build:watch": "npm run clean && tsc --watch", - "clean": "rimraf lib lib-esm dist", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, @@ -24,42 +25,42 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", + "homepage": "https://aws-amplify.github.io/", "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" + "prettier": "^1.7.4", + "typescript": "^3.2.2" }, "dependencies": { "aws-sdk": "2.518.0", "url": "^0.11.0" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/core/src/ClientDevice/browser.ts b/packages/core/src/ClientDevice/browser.ts index 2212acff277..e0fbda665fa 100644 --- a/packages/core/src/ClientDevice/browser.ts +++ b/packages/core/src/ClientDevice/browser.ts @@ -42,13 +42,13 @@ function browserClientInfo() { const timezone = browserTimezone(); return { - platform: platform, + platform, make: product || vendor, model: type.type, version: type.version, appVersion: [type.type, type.version].join('/'), - language: language, - timezone: timezone, + language, + timezone, }; } diff --git a/packages/core/src/ClientDevice/ios.ts b/packages/core/src/ClientDevice/ios.ts index 4abb428d2c3..2766507de15 100644 --- a/packages/core/src/ClientDevice/ios.ts +++ b/packages/core/src/ClientDevice/ios.ts @@ -26,8 +26,8 @@ export const clientInfo = () => { platform: OS, version: String(Version), appVersion: [OS, String(Version)].join('/'), - make: make, - model: model, + make, + model, }; }; diff --git a/packages/core/src/ServiceWorker/ServiceWorker.ts b/packages/core/src/ServiceWorker/ServiceWorker.ts index 8937930b82a..698cfebc2ed 100644 --- a/packages/core/src/ServiceWorker/ServiceWorker.ts +++ b/packages/core/src/ServiceWorker/ServiceWorker.ts @@ -70,7 +70,7 @@ class ServiceWorkerClass { if (navigator && 'serviceWorker' in navigator) { navigator.serviceWorker .register(filePath, { - scope: scope, + scope, }) .then(registration => { if (registration.installing) { diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json deleted file mode 100755 index 7404f30a802..00000000000 --- a/packages/core/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object", - "es2017" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/core/typings.d.ts b/packages/core/typings.d.ts new file mode 100644 index 00000000000..bb9e57ffd38 --- /dev/null +++ b/packages/core/typings.d.ts @@ -0,0 +1,3 @@ +declare module '*.json' { + export const version: any; +} diff --git a/packages/core/webpack.config.dev.js b/packages/core/webpack.config.dev.js new file mode 100644 index 00000000000..cf6d3b2c8ad --- /dev/null +++ b/packages/core/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-core': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/core/webpack.config.js b/packages/core/webpack.config.js index 2eee298222d..2e82d3ec00b 100644 --- a/packages/core/webpack.config.js +++ b/packages/core/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-core': './src/index.ts', - 'aws-amplify-core.min': './src/index.ts', + 'aws-amplify-core.min': './lib-esm/index.js', }, + externals: ['aws-sdk/global'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/interactions/build.js b/packages/interactions/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/interactions/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/interactions/index-rn.js b/packages/interactions/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/interactions/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/interactions/index.js b/packages/interactions/index.js new file mode 100644 index 00000000000..3a9e9d4db34 --- /dev/null +++ b/packages/interactions/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-interactions.min.js'); +} else { + module.exports = require('./dist/aws-amplify-interactions.js'); +} diff --git a/packages/interactions/package.json b/packages/interactions/package.json index 344355c8565..cbc320a2234 100644 --- a/packages/interactions/package.json +++ b/packages/interactions/package.json @@ -2,57 +2,53 @@ "name": "@aws-amplify/interactions", "version": "1.1.2", "description": "Interactions category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", + "test": "tslint 'src/**/*.ts' && jest -w 1 --coverage", "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "clean": "rimraf lib lib-esm dist", + "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", + "build:esm": "node ./build es6", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/core": "^1.2.2" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/interactions/tsconfig.json b/packages/interactions/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/interactions/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/interactions/webpack.config.dev.js b/packages/interactions/webpack.config.dev.js new file mode 100644 index 00000000000..bf79bc71240 --- /dev/null +++ b/packages/interactions/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-interactions': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/interactions/webpack.config.js b/packages/interactions/webpack.config.js index 0ee0fda6ad8..268bcbcc269 100644 --- a/packages/interactions/webpack.config.js +++ b/packages/interactions/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-interactions': './src/index.ts', - 'aws-amplify-interactions.min': './src/index.ts', + 'aws-amplify-interactions.min': './lib-esm/index.js', }, + externals: ['aws-sdk/clients/lexruntime', '@aws-amplify/core'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/predictions/build.js b/packages/predictions/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/predictions/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/predictions/index-rn.js b/packages/predictions/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/predictions/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/predictions/index.js b/packages/predictions/index.js new file mode 100644 index 00000000000..5d16b4468a6 --- /dev/null +++ b/packages/predictions/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-predictions.min.js'); +} else { + module.exports = require('./dist/aws-amplify-predictions.js'); +} diff --git a/packages/predictions/package.json b/packages/predictions/package.json index 77d30bf1f7d..d4900e3d333 100644 --- a/packages/predictions/package.json +++ b/packages/predictions/package.json @@ -2,53 +2,34 @@ "name": "@aws-amplify/predictions", "version": "1.1.2", "description": "Machine learning category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", - "publishConfig": { - "access": "public" + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "clean": "rimraf lib lib-esm dist", - "format": "tsfmt --useTsfmt tsfmt.json -r src/**/*.ts", - "lint": "tslint 'src/**/*.ts'" + "test": "jest -w 1 --passWithNoTests --coverage --maxWorkers 2", + "build-with-test": "npm run clean && npm test && tsc && webpack -p", + "build:cjs": "node ./build es5 && webpack && webpack --config ./webpack.config.dev.js", + "build:esm": "node ./build es6", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", + "format": "echo \"Not implemented\"", + "lint": "tslint 'src/**/*.ts'", + "generate-docs-local": "typedoc --out docs src", + "generate-docs-root": "typedoc --out ../../docs src" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "prettier": "^1.7.4", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "typescript-formatter": "^6.0.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/core": "^1.2.2", "@aws-amplify/storage": "^1.2.2", @@ -57,8 +38,23 @@ "uuid": "^3.2.1" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/predictions/tsconfig.json b/packages/predictions/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/predictions/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/predictions/webpack.config.dev.js b/packages/predictions/webpack.config.dev.js new file mode 100644 index 00000000000..a9152d2dc16 --- /dev/null +++ b/packages/predictions/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-predictions': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/predictions/webpack.config.js b/packages/predictions/webpack.config.js index 55abb224fe1..9e9992ae282 100644 --- a/packages/predictions/webpack.config.js +++ b/packages/predictions/webpack.config.js @@ -1,54 +1,39 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-predictions': './src/index.ts', - 'aws-amplify-predictions.min': './src/index.ts', + 'aws-amplify-predictions.min': './lib-esm/index.js', }, + externals: ['@aws-amplify/core'], output: { filename: '[name].js', path: __dirname + '/dist', library: 'aws_amplify_predictions', libraryTarget: 'umd', umdNamedDefine: true, + devtoolModuleFilenameTemplate: require('../aws-amplify/webpack-utils') + .devtoolModuleFilenameTemplate, }, // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/pubsub/__tests__/PubSub-unit-test.ts b/packages/pubsub/__tests__/PubSub-unit-test.ts index 16cac3b9cfe..3e9575d4f5e 100644 --- a/packages/pubsub/__tests__/PubSub-unit-test.ts +++ b/packages/pubsub/__tests__/PubSub-unit-test.ts @@ -49,12 +49,6 @@ const credentials = { authenticated: true, }; -const spyon = jest.spyOn(Credentials, 'get').mockImplementation(() => { - return new Promise((res, rej) => { - res(credentials); - }); -}); - const testPubSubAsync = (pubsub, topic, message, options?) => new Promise((resolve, reject) => { const obs = pubsub.subscribe(topic, options).subscribe({ @@ -109,6 +103,18 @@ const testAppSyncAsync = (pubsub, topic, message) => testClient.send(topic, JSON.stringify({ data: { testKey: message } })); }); +beforeEach(() => { + const spyon = jest.spyOn(Credentials, 'get').mockImplementation(() => { + return new Promise((res, rej) => { + res(credentials); + }); + }); +}); + +afterEach(() => { + jest.restoreAllMocks(); +}); + describe('PubSub', () => { describe('constructor test', () => { test('happy case', () => { @@ -128,7 +134,7 @@ describe('PubSub', () => { expect(config).toEqual(options); }); - test('should accept PubSub key in configuration object', async () => { + test('should accept PubSub key in configuration object', () => { const pubsub = new PubSub({}); const options = { @@ -303,7 +309,7 @@ describe('PubSub', () => { await testPubSubAsync(pubsub, 'topicA', 'my message MqttOverWSProvider'); }); - test('error is thrown if provider name is not found', async () => { + test('error is thrown if provider name is not found', () => { const testProviderName = 'FooProvider'; const pubsub = new PubSub(); @@ -345,7 +351,7 @@ describe('PubSub', () => { expect( pubsub.publish('topicA', 'my message AWSIoTProvider') - ).rejects.toThrowError('Failed to publish'); + ).rejects.toMatch('Failed to publish'); }); test('On unsubscribe when is the last observer it should disconnect the websocket', async () => { @@ -379,6 +385,7 @@ describe('PubSub', () => { expect(spyDisconnect).toHaveBeenCalled(); spyDisconnect.mockClear(); }); + test( 'For multiple observers, client should not be disconnected if there are ' + 'other observers connected when unsubscribing', diff --git a/packages/pubsub/build.js b/packages/pubsub/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/pubsub/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/pubsub/index-rn.js b/packages/pubsub/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/pubsub/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/pubsub/index.js b/packages/pubsub/index.js new file mode 100644 index 00000000000..5c80750ef6f --- /dev/null +++ b/packages/pubsub/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-pubsub.min.js'); +} else { + module.exports = require('./dist/aws-amplify-pubsub.js'); +} diff --git a/packages/pubsub/package.json b/packages/pubsub/package.json index e09110fba42..6768d2f619e 100644 --- a/packages/pubsub/package.json +++ b/packages/pubsub/package.json @@ -2,61 +2,62 @@ "name": "@aws-amplify/pubsub", "version": "1.2.2", "description": "Pubsub category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", + "test": "tslint 'src/**/*.ts' && jest -w 1 --coverage", "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && cpx src/vendor/** lib/vendor && webpack", - "clean": "rimraf lib lib-esm dist", + "build:cjs": "node ./build es5 && cpx src/vendor/** lib/vendor && webpack && webpack --config ./webpack.config.dev.js", + "build:esm": "node ./build es6 && cpx src/vendor/** lib-esm/vendor", + "build": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", + "homepage": "https://aws-amplify.github.io/", "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "@types/zen-observable": "^0.5.3", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "cpx": "^1.5.0", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" + "cpx": "^1.5.0" }, "dependencies": { "@aws-amplify/core": "^1.2.2", + "@types/zen-observable": "^0.5.3", "uuid": "^3.2.1", "zen-observable": "^0.8.6" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/pubsub/tsconfig.json b/packages/pubsub/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/pubsub/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/pubsub/webpack.config.dev.js b/packages/pubsub/webpack.config.dev.js new file mode 100644 index 00000000000..80372c0a752 --- /dev/null +++ b/packages/pubsub/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-pubsub': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/pubsub/webpack.config.js b/packages/pubsub/webpack.config.js index 0c4c7cb4c8e..f9eb307a534 100644 --- a/packages/pubsub/webpack.config.js +++ b/packages/pubsub/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-pubsub': './src/index.ts', - 'aws-amplify-pubsub.min': './src/index.ts', + 'aws-amplify-pubsub.min': './lib-esm/index.js', }, + externals: ['@aws-amplify/core'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/pushnotification/__tests__/PushNotification-unit-test.ts b/packages/pushnotification/__tests__/PushNotification-unit-test.ts deleted file mode 100644 index 22370187876..00000000000 --- a/packages/pushnotification/__tests__/PushNotification-unit-test.ts +++ /dev/null @@ -1,3 +0,0 @@ -test('happy case', () => { - expect(1).toBe(1); -}); diff --git a/packages/pushnotification/package.json b/packages/pushnotification/package.json index 2fe15f47879..12816887775 100644 --- a/packages/pushnotification/package.json +++ b/packages/pushnotification/package.json @@ -9,7 +9,7 @@ "access": "public" }, "scripts": { - "test": "jest --coverage", + "test": "jest -w 1 --coverage --passWithNoTests", "build-with-test": "npm run clean && npm test && tsc", "build": "npm run clean && tsc", "clean": "rimraf lib lib-esm dist", @@ -18,14 +18,14 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", + "homepage": "https://aws-amplify.github.io/", "devDependencies": { "@types/jest": "^20.0.8", "@types/node": "^8.10.15", diff --git a/packages/storage/build.js b/packages/storage/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/storage/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/storage/index-rn.js b/packages/storage/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/storage/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/storage/index.js b/packages/storage/index.js new file mode 100644 index 00000000000..e955745a1eb --- /dev/null +++ b/packages/storage/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-storage.min.js'); +} else { + module.exports = require('./dist/aws-amplify-storage.js'); +} diff --git a/packages/storage/package.json b/packages/storage/package.json index c90f7e1941c..20b375f455c 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -2,58 +2,59 @@ "name": "@aws-amplify/storage", "version": "1.2.2", "description": "Storage category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "test:watch": "tslint 'src/**/*.ts' && jest --watch", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "clean": "rimraf lib lib-esm dist", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", + "homepage": "https://aws-amplify.github.io/", "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" + "typescript": "^3.2.2" }, "dependencies": { "@aws-amplify/core": "^1.2.2" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/storage/tsconfig.json b/packages/storage/tsconfig.json deleted file mode 100755 index dc9789d81e2..00000000000 --- a/packages/storage/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/storage/webpack.config.dev.js b/packages/storage/webpack.config.dev.js new file mode 100644 index 00000000000..a28938c82a5 --- /dev/null +++ b/packages/storage/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-storage': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/storage/webpack.config.js b/packages/storage/webpack.config.js index a5dfe14132b..8a12647dc5c 100644 --- a/packages/storage/webpack.config.js +++ b/packages/storage/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-storage': './src/index.ts', - 'aws-amplify-storage.min': './src/index.ts', + 'aws-amplify-storage.min': './lib-esm/index.js', }, + externals: ['@aws-amplify/core', 'aws-sdk/clients/s3'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/packages/xr/build.js b/packages/xr/build.js new file mode 100644 index 00000000000..905dbb2c99d --- /dev/null +++ b/packages/xr/build.js @@ -0,0 +1,5 @@ +'use strict'; + +const build = require('../../scripts/build'); + +build(process.argv[2]); diff --git a/packages/xr/index-rn.js b/packages/xr/index-rn.js new file mode 100644 index 00000000000..647221a0d17 --- /dev/null +++ b/packages/xr/index-rn.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/index.js'); diff --git a/packages/xr/index.js b/packages/xr/index.js new file mode 100644 index 00000000000..d278a08f23a --- /dev/null +++ b/packages/xr/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/aws-amplify-xr.min.js'); +} else { + module.exports = require('./dist/aws-amplify-xr.js'); +} diff --git a/packages/xr/package.json b/packages/xr/package.json index 46b48ba2df0..1a86b125c22 100644 --- a/packages/xr/package.json +++ b/packages/xr/package.json @@ -2,58 +2,56 @@ "name": "@aws-amplify/xr", "version": "0.2.2", "description": "XR category of aws-amplify", - "main": "./lib/index.js", - "module": "./lib/index.js", - "typings": "./lib/index.d.ts", + "main": "./index.js", + "module": "./lib-esm/index.js", + "typings": "./lib-esm/index.d.ts", + "react-native": { + "./index": "./lib-esm/index.js" + }, "publishConfig": { "access": "public" }, "scripts": { - "test": "tslint 'src/**/*.ts' && jest --coverage", - "build-with-test": "npm run clean && npm test && tsc && webpack", - "build": "npm run clean && tsc && webpack", - "watch": "tsc --watch", - "clean": "rimraf lib lib-esm dist", + "test": "tslint 'src/**/*.ts' && 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": "npm run clean && npm run build:esm && npm run build:cjs", + "clean": "rimraf lib-esm lib dist", "format": "echo \"Not implemented\"", "lint": "tslint 'src/**/*.ts'" }, "repository": { "type": "git", - "url": "git+https://github.com/aws/aws-amplify.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://github.com/aws/aws-amplify#readme", - "devDependencies": { - "@types/jest": "^20.0.8", - "@types/node": "^8.10.15", - "awesome-typescript-loader": "^3.2.2", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "babel-preset-react": "^6.24.1", - "babel-preset-stage-2": "^6.24.1", - "compression-webpack-plugin": "^1.1.3", - "find": "^0.2.7", - "jest": "^22.4.3", - "json-loader": "^0.5.7", - "prepend-file": "^1.3.1", - "rimraf": "^2.6.2", - "source-map-loader": "^0.2.1", - "ts-jest": "^22.0.0", - "tslint": "^5.7.0", - "tslint-config-airbnb": "^5.8.0", - "uglifyjs-webpack-plugin": "^0.4.6", - "webpack": "^3.5.5" - }, + "homepage": "https://aws-amplify.github.io/", "dependencies": { "@aws-amplify/core": "^1.2.2" }, "jest": { + "globals": { + "ts-jest": { + "diagnostics": false, + "tsConfig": { + "lib": [ + "es5", + "es2015", + "dom", + "esnext.asynciterable", + "es2017.object" + ], + "allowJs": true + } + } + }, "transform": { - "^.+\\.(js|jsx|ts|tsx)$": "../../node_modules/ts-jest/preprocessor.js" + "^.+\\.(js|jsx|ts|tsx)$": "ts-jest" }, "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$", "moduleFileExtensions": [ diff --git a/packages/xr/tsconfig.json b/packages/xr/tsconfig.json deleted file mode 100644 index 24ffb9654d2..00000000000 --- a/packages/xr/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -//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": "es5", - "noImplicitAny": false, - "lib": [ - "es5", - "es2015", - "dom", - "esnext.asynciterable", - "es2017.object" - ], - "sourceMap": true, - "module": "commonjs", - "moduleResolution": "node", - "allowJs": false, - "declaration": true, - "typeRoots": [ - "./node_modules/@types", - "../../node_modules/@types" - ], - // temporary fix - "types": ["node", "lodash"] - }, - "include": [ - "src/**/*" - ] -} \ No newline at end of file diff --git a/packages/xr/webpack.config.dev.js b/packages/xr/webpack.config.dev.js new file mode 100644 index 00000000000..37821072389 --- /dev/null +++ b/packages/xr/webpack.config.dev.js @@ -0,0 +1,6 @@ +var config = require('./webpack.config.js'); + +var entry = { + 'aws-amplify-xr': './lib-esm/index.js', +}; +module.exports = Object.assign(config, { entry, mode: 'development' }); diff --git a/packages/xr/webpack.config.js b/packages/xr/webpack.config.js index 9f28dcd2a45..07182197a0f 100644 --- a/packages/xr/webpack.config.js +++ b/packages/xr/webpack.config.js @@ -1,11 +1,8 @@ -const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); -const CompressionPlugin = require('compression-webpack-plugin'); - module.exports = { entry: { - 'aws-amplify-xr': './src/index.ts', - 'aws-amplify-xr.min': './src/index.ts', + 'aws-amplify-xr.min': './lib-esm/index.js', }, + externals: ['@aws-amplify/core'], output: { filename: '[name].js', path: __dirname + '/dist', @@ -18,39 +15,25 @@ module.exports = { // Enable sourcemaps for debugging webpack's output. devtool: 'source-map', resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. - extensions: ['.ts', '.tsx', '.js', '.json'], + extensions: ['.js', '.json'], }, - plugins: [ - new UglifyJsPlugin({ - minimize: true, - sourceMap: true, - include: /\.min\.js$/, - }), - new CompressionPlugin({ - include: /\.min\.js$/, - }), - ], + mode: 'production', module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. - { - test: /\.tsx?$/, - loader: 'awesome-typescript-loader', - exclude: /node_modules/, - query: { - declaration: false, - }, - }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. //{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { - test: /\.jsx?$/, + test: /\.js?$/, exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: ['react', 'es2015', 'stage-2'], - }, + use: [ + 'babel-loader', + { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + ], }, ], }, diff --git a/scripts/build.js b/scripts/build.js new file mode 100644 index 00000000000..7fefa356cdb --- /dev/null +++ b/scripts/build.js @@ -0,0 +1,174 @@ +'use strict'; + +const utility = require('./utility'); +const ts = require('typescript'); +const externals = require('./rollup-externals'); + +const currentPath = process.argv[1].slice(0, process.argv[1].lastIndexOf('/')); +const tscES5OutDir = `/lib`; +const tscES6OutDir = `/lib-esm`; +const packageInfo = require(`${currentPath}/package`); + +async function buildRollUp() { + console.log(`Building Roll up bundle file under ${currentPath}`); + const rollup = require('rollup'); + const resolve = require('rollup-plugin-node-resolve'); + const sourceMaps = require('rollup-plugin-sourcemaps'); + const json = require('rollup-plugin-json'); + + const input = `${currentPath}${tscES5OutDir}/index.js`; + const file = `${currentPath}${packageInfo.main.slice( + packageInfo.main.indexOf('/') + )}`; + // For more info see: https://github.com/rollup/rollup/issues/1518#issuecomment-321875784 + const onwarn = warning => { + if (warning.code === 'THIS_IS_UNDEFINED') { + return; + } + console.warn(warning.message); + }; + + const inputOptions = { + input, + plugins: [json(), resolve({ extensions: ['.js', '.json'] }), sourceMaps()], + external: externals[packageInfo.name], + onwarn, + }; + + const outputOptions = { + file, + format: 'cjs', + name: 'index', + sourcemap: true, + exports: 'named', + }; + + console.log(`Using the rollup configuration:`); + console.log(inputOptions); + console.log(outputOptions); + + try { + const bundle = await rollup.rollup(inputOptions); + await bundle.write(outputOptions); + } catch (e) { + console.log(e); + } +} + +function tsc(fileNames, options) { + let program = ts.createProgram(fileNames, options); + let emitResult = program.emit(); + + allDiagnostics.forEach(diagnostic => { + if (diagnostic.file) { + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition( + diagnostic.start + ); + let message = ts.flattenDiagnosticMessageText( + diagnostic.messageText, + '\n' + ); + console.log( + `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}` + ); + } else { + console.log( + `${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}` + ); + } + }); + + let exitCode = emitResult.emitSkipped ? 1 : 0; + console.log(`Process exiting with code '${exitCode}'.`); + process.exit(exitCode); +} + +async function buildES5() { + const jsx = packageInfo.name === 'aws-amplify-react' ? 'react' : undefined; + const allowJs = packageInfo.name === 'aws-amplify-react' ? true : false; + // tsconfig for ES5 generating + let compilerOptions = { + noImplicitAny: false, + lib: ['dom', 'es2017', 'esnext.asynciterable'], + jsx: jsx, + sourceMap: true, + target: 'es5', + module: 'commonjs', + moduleResolution: 'node', + allowJs: allowJs, + declaration: true, + typeRoots: [ + `${currentPath}/node_modules/@types`, + `${__dirname.slice(0, __dirname.lastIndexOf('/'))}/node_modules/@types`, + ], + // temporary fix + types: ['node'], + outDir: `${currentPath}${tscES5OutDir}`, + }; + + compilerOptions = ts.convertCompilerOptionsFromJson(compilerOptions); + const include = [`${currentPath}/src`]; + console.log(`Using the typescript compiler options:`); + console.log(compilerOptions); + + let fileList = []; + Promise.all( + include.map(async source => { + const list = await utility.iterateFiles(source); + return (fileList = fileList.concat(list)); + }) + ).then(() => { + console.log('Files to be transpiled by tsc:'); + console.log(fileList); + tsc(fileList, compilerOptions.options); + }); +} + +function buildES6() { + const jsx = packageInfo.name === 'aws-amplify-react' ? 'react' : undefined; + const allowJs = packageInfo.name === 'aws-amplify-react' ? true : false; + // tsconfig for ESM generating + let compilerOptions = { + noImplicitAny: false, + lib: ['dom', 'es2017', 'esnext.asynciterable'], + jsx: jsx, + sourceMap: true, + target: 'es5', + module: 'es2015', + moduleResolution: 'node', + allowJs: allowJs, + declaration: true, + typeRoots: [ + `${currentPath}/node_modules/@types`, + `${__dirname.slice(0, __dirname.lastIndexOf('/'))}/node_modules/@types`, + ], + // temporary fix + types: ['node'], + outDir: `${currentPath}${tscES6OutDir}`, + }; + + compilerOptions = ts.convertCompilerOptionsFromJson(compilerOptions); + const include = [`${currentPath}/src`]; + console.log(`Using the typescript compiler options:`); + console.log(compilerOptions); + + let fileList = []; + Promise.all( + include.map(async source => { + const list = await utility.iterateFiles(source); + return (fileList = fileList.concat(list)); + }) + ).then(() => { + console.log('Files to be transpiled by tsc:'); + console.log(fileList); + tsc(fileList, compilerOptions.options); + }); +} + +function build(type) { + if (type === 'rollup') buildRollUp(); + if (type === 'es5') buildES5(); + if (type === 'es6') buildES6(); +} + +module.exports = build; diff --git a/scripts/rollup-externals.js b/scripts/rollup-externals.js new file mode 100644 index 00000000000..d9b263bf045 --- /dev/null +++ b/scripts/rollup-externals.js @@ -0,0 +1,93 @@ +const core_externals = ['aws-sdk', 'aws-sdk/global', 'react-native', 'url']; + +const analytics_externals = [ + '@aws-amplify/cache', + '@aws-amplify/core', + 'uuid', + 'aws-sdk/clients/pinpoint', + 'react-native', + 'aws-sdk/clients/kinesis', +]; + +const api_externals = [ + 'axios', + 'graphql', + 'graphql/language/ast', + 'graphql/language/parser', + 'graphql/language/printer', + 'uuid', + 'zen-observable', + '@aws-amplify/cache', + '@aws-amplify/core', +]; + +const auth_externals = [ + '@aws-amplify/cache', + '@aws-amplify/core', + 'amazon-cognito-auth-js', + 'amazon-cognito-identity-js', +]; + +const cache_externals = ['@aws-amplify/core']; + +const storage_externals = ['@aws-amplify/core', 'aws-sdk/clients/s3']; + +const interactions_externals = [ + 'aws-sdk/clients/lexruntime', + '@aws-amplify/core', + 'handlebars', +]; + +const xr_externals = ['@aws-amplify/core']; + +const pubsub_externals = [ + '@aws-amplify/core', + '@types/zen-observable', + 'uuid', + 'zen-observable', + 'paho-mqtt', +]; + +const amplify_externals = [ + '@aws-amplify/analytics', + '@aws-amplify/api', + '@aws-amplify/auth', + '@aws-amplify/cache', + '@aws-amplify/core', + '@aws-amplify/interactions', + '@aws-amplify/pubsub', + '@aws-amplify/storage', + '@aws-amplify/ui', + '@aws-amplify/xr', +]; + +const aws_amplify_react = [ + '@aws-amplify/auth', + '@aws-amplify/analytics', + '@aws-amplify/api', + '@aws-amplify/core', + '@aws-amplify/interactions', + '@aws-amplify/storage', + '@aws-amplify/ui', + '@aws-amplify/ui/dist/style.css', + '@aws-amplify/xr', + 'react', + 'regenerator-runtime/runtime', + 'qrcode.react', +]; + +const rollup_externals = { + '@aws-amplify/analytics': analytics_externals, + '@aws-amplify/api': api_externals, + '@aws-amplify/auth': auth_externals, + 'aws-amplify': amplify_externals, + 'aws-amplify-react': aws_amplify_react, + '@aws-amplify/cache': cache_externals, + '@aws-amplify/core': core_externals, + '@aws-amplify/interactions': interactions_externals, + '@aws-amplify/pubsub': pubsub_externals, + '@aws-amplify/storage': storage_externals, + '@aws-amplify/xr': xr_externals, +}; + +module.exports = rollup_externals; diff --git a/scripts/utility.js b/scripts/utility.js new file mode 100644 index 00000000000..01b727e95cf --- /dev/null +++ b/scripts/utility.js @@ -0,0 +1,49 @@ +const fs = require('fs'); +const path = require('path'); + +/** + * get an array of the files under the give path + */ +function iterateFiles(source) { + let fileList = []; + return new Promise((res, rej) => { + fs.readdir(source, function(err, files) { + if (err) { + console.error('Could not list the directory.', err); + return rej(err); + } + + Promise.all( + files.map(file => { + const filePath = path.join(source, file); + return new Promise((res, rej) => { + fs.stat(filePath, (error, stat) => { + if (error) { + console.error('Error stating file.', error); + return rej(error); + } + + if (stat.isFile()) { + fileList.push(filePath); + return res(); + } else if (stat.isDirectory()) { + iterateFiles(filePath).then(list => { + fileList = fileList.concat(list); + return res(); + }); + } else { + return res(); + } + }); + }); + }) + ).then(() => { + return res(fileList); + }); + }); + }); +} + +const utility = {}; +utility.iterateFiles = iterateFiles; +module.exports = utility;