@aws-amplify/core 6.0.1-console-preview.8d88eef.0 → 6.0.1-console-preview.be08038.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/Cache/StorageCacheCommon.js +1 -4
  2. package/lib/I18n/I18n.js +1 -6
  3. package/lib/Platform/version.d.ts +1 -1
  4. package/lib/Platform/version.js +1 -1
  5. package/lib/Reachability/Reachability.js +6 -1
  6. package/lib/index.d.ts +2 -1
  7. package/lib/libraryUtils.d.ts +2 -0
  8. package/lib/libraryUtils.js +4 -1
  9. package/lib/parseAWSExports.js +26 -6
  10. package/lib/singleton/Auth/types.d.ts +2 -2
  11. package/lib/singleton/Interactions/types.d.ts +21 -0
  12. package/lib/singleton/Interactions/types.js +4 -0
  13. package/lib/singleton/types.d.ts +3 -5
  14. package/lib/tsconfig.tsbuildinfo +1 -1
  15. package/lib/utils/deepFreeze.js +1 -1
  16. package/lib/utils/sessionListener/SessionListener.d.ts +10 -0
  17. package/lib/utils/sessionListener/SessionListener.js +55 -0
  18. package/lib/utils/sessionListener/SessionListener.native.d.ts +10 -0
  19. package/lib/utils/sessionListener/SessionListener.native.js +54 -0
  20. package/lib/utils/sessionListener/index.d.ts +2 -0
  21. package/lib/utils/sessionListener/index.js +7 -0
  22. package/lib/utils/sessionListener/types.d.ts +6 -0
  23. package/lib/utils/sessionListener/types.js +4 -0
  24. package/lib-esm/Cache/StorageCacheCommon.js +1 -4
  25. package/lib-esm/I18n/I18n.js +1 -6
  26. package/lib-esm/Platform/version.d.ts +1 -1
  27. package/lib-esm/Platform/version.js +1 -1
  28. package/lib-esm/Reachability/Reachability.js +7 -2
  29. package/lib-esm/index.d.ts +2 -1
  30. package/lib-esm/libraryUtils.d.ts +2 -0
  31. package/lib-esm/libraryUtils.js +2 -0
  32. package/lib-esm/parseAWSExports.js +26 -6
  33. package/lib-esm/singleton/Auth/types.d.ts +2 -2
  34. package/lib-esm/singleton/Interactions/types.d.ts +21 -0
  35. package/lib-esm/singleton/Interactions/types.js +3 -0
  36. package/lib-esm/singleton/types.d.ts +3 -5
  37. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  38. package/lib-esm/utils/deepFreeze.js +1 -1
  39. package/lib-esm/utils/sessionListener/SessionListener.d.ts +10 -0
  40. package/lib-esm/utils/sessionListener/SessionListener.js +52 -0
  41. package/lib-esm/utils/sessionListener/SessionListener.native.d.ts +10 -0
  42. package/lib-esm/utils/sessionListener/SessionListener.native.js +51 -0
  43. package/lib-esm/utils/sessionListener/index.d.ts +2 -0
  44. package/lib-esm/utils/sessionListener/index.js +4 -0
  45. package/lib-esm/utils/sessionListener/types.d.ts +6 -0
  46. package/lib-esm/utils/sessionListener/types.js +3 -0
  47. package/package.json +4 -4
  48. package/src/Cache/StorageCacheCommon.ts +0 -4
  49. package/src/I18n/I18n.ts +1 -6
  50. package/src/Platform/version.ts +1 -1
  51. package/src/Reachability/Reachability.ts +8 -2
  52. package/src/index.ts +1 -1
  53. package/src/libraryUtils.ts +4 -0
  54. package/src/parseAWSExports.ts +34 -7
  55. package/src/singleton/Auth/types.ts +2 -2
  56. package/src/singleton/Interactions/types.ts +29 -0
  57. package/src/singleton/types.ts +3 -7
  58. package/src/utils/deepFreeze.ts +1 -1
  59. package/src/utils/sessionListener/SessionListener.native.ts +70 -0
  60. package/src/utils/sessionListener/SessionListener.ts +74 -0
  61. package/src/utils/sessionListener/index.ts +6 -0
  62. package/src/utils/sessionListener/types.ts +11 -0
@@ -18,7 +18,7 @@ export var deepFreeze = function (object) {
18
18
  for (var propNames_1 = __values(propNames), propNames_1_1 = propNames_1.next(); !propNames_1_1.done; propNames_1_1 = propNames_1.next()) {
19
19
  var name_1 = propNames_1_1.value;
20
20
  var value = object[name_1];
21
- if ((value && typeof value === "object") || typeof value === "function") {
21
+ if ((value && typeof value === 'object') || typeof value === 'function') {
22
22
  deepFreeze(value);
23
23
  }
24
24
  }
@@ -0,0 +1,10 @@
1
+ import { SessionStateChangeListener, SessionListenerInterface } from './types';
2
+ export declare class SessionListener implements SessionListenerInterface {
3
+ private listenerActive;
4
+ constructor();
5
+ addStateChangeListener(listener: SessionStateChangeListener, notifyOnAdd?: boolean): void;
6
+ removeStateChangeListener(handler: SessionStateChangeListener): void;
7
+ private handleVisibilityChange;
8
+ private notifyHandlers;
9
+ private getSessionState;
10
+ }
@@ -0,0 +1,52 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { isBrowser } from '../isBrowser';
4
+ var stateChangeListeners = new Set();
5
+ var SessionListener = /** @class */ (function () {
6
+ function SessionListener() {
7
+ this.listenerActive = false;
8
+ this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
9
+ // Setup state listeners
10
+ if (isBrowser()) {
11
+ document.addEventListener('visibilitychange', this.handleVisibilityChange, false);
12
+ this.listenerActive = true;
13
+ }
14
+ }
15
+ SessionListener.prototype.addStateChangeListener = function (listener, notifyOnAdd) {
16
+ if (notifyOnAdd === void 0) { notifyOnAdd = false; }
17
+ // No-op if document listener is not active
18
+ if (!this.listenerActive) {
19
+ return;
20
+ }
21
+ stateChangeListeners.add(listener);
22
+ // Notify new handlers of the current status on add
23
+ if (notifyOnAdd) {
24
+ listener(this.getSessionState());
25
+ }
26
+ };
27
+ SessionListener.prototype.removeStateChangeListener = function (handler) {
28
+ // No-op if document listener is not active
29
+ if (!this.listenerActive) {
30
+ return;
31
+ }
32
+ stateChangeListeners.delete(handler);
33
+ };
34
+ SessionListener.prototype.handleVisibilityChange = function () {
35
+ this.notifyHandlers();
36
+ };
37
+ SessionListener.prototype.notifyHandlers = function () {
38
+ var sessionState = this.getSessionState();
39
+ stateChangeListeners.forEach(function (listener) {
40
+ listener(sessionState);
41
+ });
42
+ };
43
+ SessionListener.prototype.getSessionState = function () {
44
+ if (isBrowser() && document.visibilityState !== 'hidden') {
45
+ return 'started';
46
+ }
47
+ // If, for any reason, document is undefined the session will never start
48
+ return 'ended';
49
+ };
50
+ return SessionListener;
51
+ }());
52
+ export { SessionListener };
@@ -0,0 +1,10 @@
1
+ import { SessionStateChangeListener, SessionListenerInterface } from './types';
2
+ export declare class SessionListener implements SessionListenerInterface {
3
+ private currentAppState?;
4
+ constructor();
5
+ addStateChangeListener(listener: SessionStateChangeListener, notifyOnAdd?: boolean): void;
6
+ removeStateChangeListener(handler: SessionStateChangeListener): void;
7
+ private handleStateChange;
8
+ private notifyHandlers;
9
+ private getSessionState;
10
+ }
@@ -0,0 +1,51 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { loadAppState } from '@aws-amplify/react-native';
4
+ var stateChangeListeners = new Set();
5
+ var isActive = function (appState) { return appState === 'active'; };
6
+ var isInactive = function (appState) {
7
+ return appState === 'inactive' || appState === 'background';
8
+ };
9
+ var SessionListener = /** @class */ (function () {
10
+ function SessionListener() {
11
+ this.handleStateChange = this.handleStateChange.bind(this);
12
+ // Setup state listeners
13
+ loadAppState().addEventListener('change', this.handleStateChange);
14
+ }
15
+ SessionListener.prototype.addStateChangeListener = function (listener, notifyOnAdd) {
16
+ if (notifyOnAdd === void 0) { notifyOnAdd = false; }
17
+ stateChangeListeners.add(listener);
18
+ // Notify new handlers of the current state on add if the current state has been determined
19
+ if (notifyOnAdd && this.currentAppState !== undefined) {
20
+ listener(this.getSessionState());
21
+ }
22
+ };
23
+ SessionListener.prototype.removeStateChangeListener = function (handler) {
24
+ stateChangeListeners.delete(handler);
25
+ };
26
+ SessionListener.prototype.handleStateChange = function (nextAppState) {
27
+ if ((this.currentAppState === undefined ||
28
+ isInactive(this.currentAppState)) &&
29
+ isActive(nextAppState)) {
30
+ this.notifyHandlers('started');
31
+ }
32
+ else if (isActive(this.currentAppState) && isInactive(nextAppState)) {
33
+ this.notifyHandlers('ended');
34
+ }
35
+ this.currentAppState = nextAppState;
36
+ };
37
+ SessionListener.prototype.notifyHandlers = function (state) {
38
+ stateChangeListeners.forEach(function (listener) {
39
+ listener(state);
40
+ });
41
+ };
42
+ SessionListener.prototype.getSessionState = function () {
43
+ if (isActive(this.currentAppState)) {
44
+ return 'started';
45
+ }
46
+ // Consider any other app state as ended
47
+ return 'ended';
48
+ };
49
+ return SessionListener;
50
+ }());
51
+ export { SessionListener };
@@ -0,0 +1,2 @@
1
+ import { SessionListener } from './SessionListener';
2
+ export declare const sessionListener: SessionListener;
@@ -0,0 +1,4 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { SessionListener } from './SessionListener';
4
+ export var sessionListener = new SessionListener();
@@ -0,0 +1,6 @@
1
+ export type SessionState = 'started' | 'ended';
2
+ export type SessionStateChangeListener = (state: SessionState) => void;
3
+ export interface SessionListenerInterface {
4
+ addStateChangeListener: (listener: SessionStateChangeListener) => void;
5
+ removeStateChangeListener: (listener: SessionStateChangeListener) => void;
6
+ }
@@ -0,0 +1,3 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aws-amplify/core",
3
- "version": "6.0.1-console-preview.8d88eef.0+8d88eef",
3
+ "version": "6.0.1-console-preview.be08038.0+be08038",
4
4
  "description": "Core category of aws-amplify",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib-esm/index.js",
@@ -55,7 +55,7 @@
55
55
  "server"
56
56
  ],
57
57
  "dependencies": {
58
- "@aws-crypto/sha256-js": "5.0.0",
58
+ "@aws-crypto/sha256-js": "5.2.0",
59
59
  "@aws-sdk/types": "3.398.0",
60
60
  "@smithy/util-hex-encoding": "2.0.0",
61
61
  "js-cookie": "^3.0.5",
@@ -64,7 +64,7 @@
64
64
  "uuid": "^9.0.0"
65
65
  },
66
66
  "devDependencies": {
67
- "@aws-amplify/react-native": "1.0.1-console-preview.8d88eef.0+8d88eef",
67
+ "@aws-amplify/react-native": "1.0.1-console-preview.be08038.0+be08038",
68
68
  "@types/js-cookie": "3.0.2",
69
69
  "@types/uuid": "^9.0.0",
70
70
  "find": "^0.2.7",
@@ -169,5 +169,5 @@
169
169
  "lib-esm"
170
170
  ]
171
171
  },
172
- "gitHead": "8d88eef4137cef4fbe03d7d3683b5bec59feb7b8"
172
+ "gitHead": "be08038c5b37a510243f077c6d3209e5383f8866"
173
173
  }
@@ -1,7 +1,6 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { Amplify } from '../singleton';
5
4
  import { ConsoleLogger as Logger } from '../Logger';
6
5
  import { KeyValueStorageInterface } from '../types';
7
6
  import { currentSizeKey, defaultConfig } from './constants';
@@ -31,11 +30,8 @@ export abstract class StorageCacheCommon {
31
30
  config?: CacheConfig;
32
31
  keyValueStorage: KeyValueStorageInterface;
33
32
  }) {
34
- const globalCacheConfig = Amplify.getConfig().Cache ?? {};
35
-
36
33
  this.config = {
37
34
  ...defaultConfig,
38
- ...globalCacheConfig,
39
35
  ...config,
40
36
  };
41
37
  this.keyValueStorage = keyValueStorage;
package/src/I18n/I18n.ts CHANGED
@@ -37,12 +37,7 @@ export class I18n {
37
37
  * Sets the default language from the configuration when required.
38
38
  */
39
39
  setDefaultLanguage() {
40
- if (!this._lang) {
41
- const i18nConfig = Amplify.getConfig().I18n;
42
- this._lang = i18nConfig?.language;
43
- }
44
-
45
- // Default to window language if not set in config
40
+ // Default to window language if not set in instance
46
41
  if (
47
42
  !this._lang &&
48
43
  typeof window !== 'undefined' &&
@@ -1,2 +1,2 @@
1
1
  // generated by genversion
2
- export const version = '6.0.1-console-preview.8d88eef.0+8d88eef';
2
+ export const version = '6.0.1-console-preview.be08038.0+be08038';
@@ -1,7 +1,7 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { CompletionObserver, Observable } from 'rxjs';
4
+ import { CompletionObserver, Observable, from } from 'rxjs';
5
5
  import { isWebWorker } from '../libraryUtils';
6
6
  import { NetworkStatus } from './types';
7
7
 
@@ -9,7 +9,13 @@ export class Reachability {
9
9
  private static _observers: Array<CompletionObserver<NetworkStatus>> = [];
10
10
 
11
11
  networkMonitor(_?: unknown): Observable<NetworkStatus> {
12
- const globalObj = isWebWorker() ? self : window;
12
+ const globalObj = isWebWorker()
13
+ ? self
14
+ : typeof window !== 'undefined' && window;
15
+
16
+ if (!globalObj) {
17
+ return from([{ online: true }]);
18
+ }
13
19
 
14
20
  return new Observable(observer => {
15
21
  observer.next({ online: globalObj.navigator.onLine });
package/src/index.ts CHANGED
@@ -24,7 +24,6 @@ export {
24
24
  AuthUserPoolConfig,
25
25
  AuthUserPoolAndIdentityPoolConfig,
26
26
  APIConfig,
27
- CacheConfig,
28
27
  StorageAccessLevel,
29
28
  StorageConfig,
30
29
  GetCredentialsOptions,
@@ -62,6 +61,7 @@ export { KeyValueStorageInterface } from './types';
62
61
 
63
62
  // Cache exports
64
63
  export { Cache } from './Cache';
64
+ export { CacheConfig } from './Cache/types';
65
65
 
66
66
  // Internationalization utilities
67
67
  export { I18n } from './I18n';
@@ -101,3 +101,7 @@ export { getCrypto } from './utils/globalHelpers';
101
101
 
102
102
  // Hub
103
103
  export { HubInternal } from './Hub';
104
+
105
+ // Session listener
106
+ export { sessionListener } from './utils/sessionListener';
107
+ export { SessionState } from './utils/sessionListener/types';
@@ -1,7 +1,7 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  import { ConsoleLogger as Logger } from './Logger';
4
- import { OAuthConfig, AuthConfigUserAttributes } from './singleton/Auth/types';
4
+ import { OAuthConfig, AuthConfigUserAttributes, OAuthProvider } from './singleton/Auth/types';
5
5
  import { ResourcesConfig } from './singleton/types';
6
6
 
7
7
  const logger = new Logger('parseAWSExports');
@@ -32,6 +32,8 @@ export const parseAWSExports = (
32
32
  aws_appsync_authenticationType,
33
33
  aws_appsync_graphqlEndpoint,
34
34
  aws_appsync_region,
35
+ aws_bots,
36
+ aws_bots_config,
35
37
  aws_cognito_identity_pool_id,
36
38
  aws_cognito_sign_up_verification_method,
37
39
  aws_cognito_mfa_configuration,
@@ -39,6 +41,7 @@ export const parseAWSExports = (
39
41
  aws_cognito_password_protection_settings,
40
42
  aws_cognito_verification_mechanisms,
41
43
  aws_cognito_signup_attributes,
44
+ aws_cognito_social_providers,
42
45
  aws_cognito_username_attributes,
43
46
  aws_mandatory_sign_in,
44
47
  aws_mobile_analytics_app_id,
@@ -89,6 +92,13 @@ export const parseAWSExports = (
89
92
  }
90
93
  }
91
94
 
95
+ // Interactions
96
+ if (Array.isArray(aws_bots_config)) {
97
+ amplifyConfig.Interactions = {
98
+ LexV1: Object.fromEntries(aws_bots_config.map(bot => [bot.name, bot])),
99
+ };
100
+ }
101
+
92
102
  // API
93
103
  if (aws_appsync_graphqlEndpoint) {
94
104
  const defaultAuthMode = authTypeMapping[aws_appsync_authenticationType];
@@ -169,16 +179,26 @@ export const parseAWSExports = (
169
179
  username:
170
180
  loginWithEmailEnabled || loginWithPhoneEnabled ? false : true,
171
181
  email: loginWithEmailEnabled,
172
- phone: loginWithPhoneEnabled,
173
- ...(oauth &&
174
- Object.keys(oauth).length > 0 && {
175
- oauth: getOAuthConfig(oauth),
176
- }),
182
+ phone: loginWithPhoneEnabled
177
183
  },
178
184
  },
179
185
  };
180
186
  }
181
187
 
188
+ const hasOAuthConfig = oauth ? Object.keys(oauth).length > 0 : false;
189
+ const hasSocialProviderConfig = aws_cognito_social_providers ? aws_cognito_social_providers.length > 0 : false;
190
+ if (amplifyConfig.Auth && hasOAuthConfig) {
191
+ amplifyConfig.Auth.Cognito.loginWith = {
192
+ ...amplifyConfig.Auth.Cognito.loginWith,
193
+ oauth: {
194
+ ...(getOAuthConfig(oauth)),
195
+ ...(hasSocialProviderConfig && {
196
+ providers: parseSocialProviders(aws_cognito_social_providers)
197
+ })
198
+ },
199
+ };
200
+ }
201
+
182
202
  // Storage
183
203
  if (aws_user_files_s3_bucket) {
184
204
  amplifyConfig.Storage = {
@@ -243,5 +263,12 @@ const getOAuthConfig = ({
243
263
  scopes: scope,
244
264
  redirectSignIn: getRedirectUrl(redirectSignIn),
245
265
  redirectSignOut: getRedirectUrl(redirectSignOut),
246
- responseType,
266
+ responseType
247
267
  });
268
+
269
+ const parseSocialProviders = (aws_cognito_social_providers: string[]) => {
270
+ return aws_cognito_social_providers.map((provider: string) => {
271
+ const updatedProvider = provider.toLowerCase();
272
+ return updatedProvider.charAt(0).toUpperCase() + updatedProvider.slice(1);
273
+ }) as OAuthProvider[];
274
+ };
@@ -166,10 +166,10 @@ export type OAuthConfig = {
166
166
  redirectSignIn: Array<string>;
167
167
  redirectSignOut: Array<string>;
168
168
  responseType: 'code' | 'token';
169
- providers?: Array<OAuthProviders | CustomProvider>;
169
+ providers?: Array<OAuthProvider | CustomProvider>;
170
170
  };
171
171
 
172
- type OAuthProviders = 'Google' | 'Facebook' | 'Amazon' | 'Apple';
172
+ export type OAuthProvider = 'Google' | 'Facebook' | 'Amazon' | 'Apple';
173
173
  type CustomProvider = { custom: string };
174
174
 
175
175
  type CustomScope = string & {};
@@ -0,0 +1,29 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ interface LexV1BotConfig {
5
+ alias: string;
6
+ region: string;
7
+ }
8
+
9
+ interface LexV2BotConfig {
10
+ botId: string;
11
+ aliasId: string;
12
+ localeId: string;
13
+ region: string;
14
+ }
15
+
16
+ type InteractionsLexV1Config = {
17
+ LexV1: Record<string, LexV1BotConfig>;
18
+ };
19
+
20
+ type InteractionsLexV2Config = {
21
+ LexV2: Record<string, LexV2BotConfig>;
22
+ };
23
+
24
+ type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
25
+ U[keyof U];
26
+
27
+ export type InteractionsConfig = AtLeastOne<
28
+ InteractionsLexV1Config & InteractionsLexV2Config
29
+ >;
@@ -12,15 +12,14 @@ import {
12
12
  GetCredentialsOptions,
13
13
  CognitoIdentityPoolConfig,
14
14
  } from './Auth/types';
15
- import { CacheConfig } from './Cache/types';
16
15
  import { GeoConfig } from './Geo/types';
17
16
  import {
18
17
  LibraryStorageOptions,
19
18
  StorageAccessLevel,
20
19
  StorageConfig,
21
20
  } from './Storage/types';
22
- import { I18nConfig } from '../I18n/types';
23
21
  import { NotificationsConfig } from './Notifications/types';
22
+ import { InteractionsConfig } from './Interactions/types';
24
23
 
25
24
  export type LegacyConfig = {
26
25
  /**
@@ -33,10 +32,7 @@ export type ResourcesConfig = {
33
32
  API?: APIConfig;
34
33
  Analytics?: AnalyticsConfig;
35
34
  Auth?: AuthConfig;
36
- Cache?: CacheConfig;
37
- // DataStore?: {};
38
- I18n?: I18nConfig;
39
- // Interactions?: {};
35
+ Interactions?: InteractionsConfig;
40
36
  Notifications?: NotificationsConfig;
41
37
  // Predictions?: {};
42
38
  Storage?: StorageConfig;
@@ -56,8 +52,8 @@ export {
56
52
  AuthUserPoolConfig,
57
53
  AuthIdentityPoolConfig,
58
54
  AuthUserPoolAndIdentityPoolConfig,
59
- CacheConfig,
60
55
  GetCredentialsOptions,
56
+ InteractionsConfig,
61
57
  StorageAccessLevel,
62
58
  StorageConfig,
63
59
  AnalyticsConfig,
@@ -7,7 +7,7 @@ export const deepFreeze = (object: any) => {
7
7
  for (const name of propNames) {
8
8
  const value = object[name];
9
9
 
10
- if ((value && typeof value === "object") || typeof value === "function") {
10
+ if ((value && typeof value === 'object') || typeof value === 'function') {
11
11
  deepFreeze(value);
12
12
  }
13
13
  }
@@ -0,0 +1,70 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { loadAppState } from '@aws-amplify/react-native';
5
+ import {
6
+ SessionStateChangeListener,
7
+ SessionState,
8
+ SessionListenerInterface,
9
+ } from './types';
10
+
11
+ const stateChangeListeners = new Set<SessionStateChangeListener>();
12
+ const isActive = (appState?: string) => appState === 'active';
13
+ const isInactive = (appState?: string) =>
14
+ appState === 'inactive' || appState === 'background';
15
+
16
+ export class SessionListener implements SessionListenerInterface {
17
+ private currentAppState?: string;
18
+
19
+ constructor() {
20
+ this.handleStateChange = this.handleStateChange.bind(this);
21
+
22
+ // Setup state listeners
23
+ loadAppState().addEventListener('change', this.handleStateChange);
24
+ }
25
+
26
+ public addStateChangeListener(
27
+ listener: SessionStateChangeListener,
28
+ notifyOnAdd: boolean = false
29
+ ) {
30
+ stateChangeListeners.add(listener);
31
+
32
+ // Notify new handlers of the current state on add if the current state has been determined
33
+ if (notifyOnAdd && this.currentAppState !== undefined) {
34
+ listener(this.getSessionState());
35
+ }
36
+ }
37
+
38
+ public removeStateChangeListener(handler: SessionStateChangeListener) {
39
+ stateChangeListeners.delete(handler);
40
+ }
41
+
42
+ private handleStateChange(nextAppState: string) {
43
+ if (
44
+ (this.currentAppState === undefined ||
45
+ isInactive(this.currentAppState)) &&
46
+ isActive(nextAppState)
47
+ ) {
48
+ this.notifyHandlers('started');
49
+ } else if (isActive(this.currentAppState) && isInactive(nextAppState)) {
50
+ this.notifyHandlers('ended');
51
+ }
52
+
53
+ this.currentAppState = nextAppState;
54
+ }
55
+
56
+ private notifyHandlers(state: SessionState) {
57
+ stateChangeListeners.forEach(listener => {
58
+ listener(state);
59
+ });
60
+ }
61
+
62
+ private getSessionState() {
63
+ if (isActive(this.currentAppState)) {
64
+ return 'started';
65
+ }
66
+
67
+ // Consider any other app state as ended
68
+ return 'ended';
69
+ }
70
+ }
@@ -0,0 +1,74 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { isBrowser } from '../isBrowser';
5
+ import { SessionStateChangeListener, SessionListenerInterface } from './types';
6
+
7
+ const stateChangeListeners = new Set<SessionStateChangeListener>();
8
+
9
+ export class SessionListener implements SessionListenerInterface {
10
+ private listenerActive: boolean;
11
+
12
+ constructor() {
13
+ this.listenerActive = false;
14
+ this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
15
+
16
+ // Setup state listeners
17
+ if (isBrowser()) {
18
+ document.addEventListener(
19
+ 'visibilitychange',
20
+ this.handleVisibilityChange,
21
+ false
22
+ );
23
+
24
+ this.listenerActive = true;
25
+ }
26
+ }
27
+
28
+ public addStateChangeListener(
29
+ listener: SessionStateChangeListener,
30
+ notifyOnAdd: boolean = false
31
+ ) {
32
+ // No-op if document listener is not active
33
+ if (!this.listenerActive) {
34
+ return;
35
+ }
36
+
37
+ stateChangeListeners.add(listener);
38
+
39
+ // Notify new handlers of the current status on add
40
+ if (notifyOnAdd) {
41
+ listener(this.getSessionState());
42
+ }
43
+ }
44
+
45
+ public removeStateChangeListener(handler: SessionStateChangeListener) {
46
+ // No-op if document listener is not active
47
+ if (!this.listenerActive) {
48
+ return;
49
+ }
50
+
51
+ stateChangeListeners.delete(handler);
52
+ }
53
+
54
+ private handleVisibilityChange() {
55
+ this.notifyHandlers();
56
+ }
57
+
58
+ private notifyHandlers() {
59
+ const sessionState = this.getSessionState();
60
+
61
+ stateChangeListeners.forEach(listener => {
62
+ listener(sessionState);
63
+ });
64
+ }
65
+
66
+ private getSessionState() {
67
+ if (isBrowser() && document.visibilityState !== 'hidden') {
68
+ return 'started';
69
+ }
70
+
71
+ // If, for any reason, document is undefined the session will never start
72
+ return 'ended';
73
+ }
74
+ }
@@ -0,0 +1,6 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { SessionListener } from './SessionListener';
5
+
6
+ export const sessionListener = new SessionListener();
@@ -0,0 +1,11 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export type SessionState = 'started' | 'ended';
5
+
6
+ export type SessionStateChangeListener = (state: SessionState) => void;
7
+
8
+ export interface SessionListenerInterface {
9
+ addStateChangeListener: (listener: SessionStateChangeListener) => void;
10
+ removeStateChangeListener: (listener: SessionStateChangeListener) => void;
11
+ }