@aws-amplify/core 6.0.1-console-preview.5f040a2.0 → 6.0.1-console-preview.23dc225.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 (260) hide show
  1. package/lib/Cache/StorageCache.d.ts +14 -31
  2. package/lib/Cache/StorageCache.js +97 -102
  3. package/lib/Cache/StorageCache.native.d.ts +19 -0
  4. package/lib/Cache/StorageCache.native.js +164 -0
  5. package/lib/Cache/{AsyncStorageCache.d.ts → StorageCacheCommon.d.ts} +124 -99
  6. package/lib/Cache/{AsyncStorageCache.js → StorageCacheCommon.js} +497 -432
  7. package/lib/Cache/constants.d.ts +6 -0
  8. package/lib/Cache/constants.js +17 -0
  9. package/lib/Cache/index.d.ts +2 -0
  10. package/lib/Cache/index.js +7 -0
  11. package/lib/Cache/types/cache.d.ts +38 -0
  12. package/lib/Cache/types/index.d.ts +1 -1
  13. package/lib/Cache/types/index.js +1 -1
  14. package/lib/Cache/{Utils → utils}/CacheList.d.ts +1 -1
  15. package/lib/Cache/{Utils → utils}/CacheList.js +2 -1
  16. package/lib/Cache/utils/cacheHelpers.d.ts +14 -0
  17. package/lib/Cache/utils/cacheHelpers.js +51 -0
  18. package/lib/Cache/{Utils → utils}/errorHelpers.d.ts +0 -1
  19. package/lib/Cache/{Utils → utils}/errorHelpers.js +0 -4
  20. package/lib/Cache/utils/index.d.ts +2 -0
  21. package/lib/Cache/utils/index.js +12 -0
  22. package/lib/Hub/index.d.ts +7 -0
  23. package/lib/Hub/index.js +8 -1
  24. package/lib/Platform/customUserAgent.d.ts +16 -0
  25. package/lib/Platform/customUserAgent.js +70 -0
  26. package/lib/Platform/index.js +10 -1
  27. package/lib/Platform/types.d.ts +33 -1
  28. package/lib/Platform/types.js +1 -0
  29. package/lib/Platform/version.d.ts +1 -1
  30. package/lib/Platform/version.js +1 -1
  31. package/lib/Reachability/Reachability.d.ts +1 -0
  32. package/lib/Reachability/Reachability.js +36 -0
  33. package/lib/Signer/Signer.js +3 -2
  34. package/lib/awsClients/cognitoIdentity/base.js +2 -1
  35. package/lib/awsClients/pinpoint/base.js +2 -1
  36. package/lib/awsClients/pinpoint/getInAppMessages.js +2 -1
  37. package/lib/awsClients/pinpoint/putEvents.js +2 -1
  38. package/lib/awsClients/pinpoint/updateEndpoint.js +2 -1
  39. package/lib/clients/middleware/signing/signer/signatureV4/index.d.ts +0 -1
  40. package/lib/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  41. package/lib/clients/middleware/signing/signer/signatureV4/presignUrl.js +2 -1
  42. package/lib/index.d.ts +2 -5
  43. package/lib/index.js +3 -6
  44. package/lib/libraryUtils.d.ts +7 -5
  45. package/lib/libraryUtils.js +11 -6
  46. package/lib/parseAWSExports.js +75 -14
  47. package/lib/providers/pinpoint/apis/flushEvents.d.ts +2 -2
  48. package/lib/providers/pinpoint/apis/record.js +3 -3
  49. package/lib/providers/pinpoint/apis/updateEndpoint.js +6 -6
  50. package/lib/singleton/API/types.d.ts +4 -3
  51. package/lib/singleton/Amplify.d.ts +2 -2
  52. package/lib/singleton/Amplify.js +6 -5
  53. package/lib/singleton/Auth/types.d.ts +28 -1
  54. package/lib/singleton/Cache/types.d.ts +18 -0
  55. package/lib/singleton/Cache/types.js +4 -0
  56. package/lib/singleton/types.d.ts +3 -1
  57. package/lib/storage/DefaultStorage.js +1 -1
  58. package/lib/storage/utils.d.ts +1 -1
  59. package/lib/storage/utils.js +3 -3
  60. package/lib/tsconfig.tsbuildinfo +1 -1
  61. package/lib/utils/amplifyUrl/index.d.ts +13 -0
  62. package/lib/utils/amplifyUrl/index.js +10 -0
  63. package/lib/utils/amplifyUrl/polyfill.d.ts +0 -0
  64. package/lib/utils/amplifyUrl/polyfill.js +4 -0
  65. package/lib/utils/amplifyUrl/polyfill.native.d.ts +1 -0
  66. package/lib/utils/amplifyUuid/index.d.ts +3 -0
  67. package/lib/utils/amplifyUuid/index.js +9 -0
  68. package/lib/utils/amplifyUuid/polyfill.d.ts +0 -0
  69. package/lib/utils/amplifyUuid/polyfill.js +4 -0
  70. package/lib/utils/amplifyUuid/polyfill.native.d.ts +1 -0
  71. package/lib/utils/amplifyUuid/polyfill.native.js +6 -0
  72. package/lib/utils/deepFreeze.d.ts +1 -0
  73. package/lib/utils/deepFreeze.js +38 -0
  74. package/lib/{ClientDevice/android.d.ts → utils/getClientInfo/getClientInfo.android.d.ts} +1 -1
  75. package/lib/{ClientDevice/android.js → utils/getClientInfo/getClientInfo.android.js} +4 -4
  76. package/lib/{ClientDevice/browser.d.ts → utils/getClientInfo/getClientInfo.d.ts} +1 -9
  77. package/lib/{ClientDevice/ios.d.ts → utils/getClientInfo/getClientInfo.ios.d.ts} +1 -1
  78. package/lib/{ClientDevice/ios.js → utils/getClientInfo/getClientInfo.ios.js} +4 -4
  79. package/lib/{ClientDevice/browser.js → utils/getClientInfo/getClientInfo.js} +6 -18
  80. package/lib/utils/getClientInfo/index.d.ts +1 -0
  81. package/lib/utils/getClientInfo/index.js +7 -0
  82. package/lib/utils/index.d.ts +2 -0
  83. package/lib/utils/index.js +5 -1
  84. package/lib-esm/Cache/StorageCache.d.ts +14 -31
  85. package/lib-esm/Cache/StorageCache.js +97 -102
  86. package/lib-esm/Cache/StorageCache.native.d.ts +19 -0
  87. package/lib-esm/Cache/StorageCache.native.js +161 -0
  88. package/lib-esm/Cache/{AsyncStorageCache.d.ts → StorageCacheCommon.d.ts} +124 -99
  89. package/lib-esm/Cache/{AsyncStorageCache.js → StorageCacheCommon.js} +496 -430
  90. package/lib-esm/Cache/constants.d.ts +6 -0
  91. package/lib-esm/Cache/constants.js +14 -0
  92. package/lib-esm/Cache/index.d.ts +2 -0
  93. package/lib-esm/Cache/index.js +4 -0
  94. package/lib-esm/Cache/types/cache.d.ts +38 -0
  95. package/lib-esm/Cache/types/index.d.ts +1 -1
  96. package/lib-esm/Cache/types/index.js +1 -1
  97. package/lib-esm/Cache/{Utils → utils}/CacheList.d.ts +1 -1
  98. package/lib-esm/Cache/{Utils → utils}/CacheList.js +1 -1
  99. package/lib-esm/Cache/utils/cacheHelpers.d.ts +14 -0
  100. package/lib-esm/Cache/utils/cacheHelpers.js +44 -0
  101. package/lib-esm/Cache/{Utils → utils}/errorHelpers.d.ts +0 -1
  102. package/lib-esm/Cache/{Utils → utils}/errorHelpers.js +0 -4
  103. package/lib-esm/Cache/utils/index.d.ts +2 -0
  104. package/lib-esm/Cache/utils/index.js +4 -0
  105. package/lib-esm/Hub/index.d.ts +7 -0
  106. package/lib-esm/Hub/index.js +7 -0
  107. package/lib-esm/Platform/customUserAgent.d.ts +16 -0
  108. package/lib-esm/Platform/customUserAgent.js +65 -0
  109. package/lib-esm/Platform/index.js +10 -1
  110. package/lib-esm/Platform/types.d.ts +33 -1
  111. package/lib-esm/Platform/types.js +1 -0
  112. package/lib-esm/Platform/version.d.ts +1 -1
  113. package/lib-esm/Platform/version.js +1 -1
  114. package/lib-esm/Reachability/Reachability.d.ts +1 -0
  115. package/lib-esm/Reachability/Reachability.js +36 -0
  116. package/lib-esm/Signer/Signer.js +3 -2
  117. package/lib-esm/awsClients/cognitoIdentity/base.js +2 -1
  118. package/lib-esm/awsClients/pinpoint/base.js +2 -1
  119. package/lib-esm/awsClients/pinpoint/getInAppMessages.js +2 -1
  120. package/lib-esm/awsClients/pinpoint/putEvents.js +2 -1
  121. package/lib-esm/awsClients/pinpoint/updateEndpoint.js +2 -1
  122. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.d.ts +0 -1
  123. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  124. package/lib-esm/clients/middleware/signing/signer/signatureV4/presignUrl.js +2 -1
  125. package/lib-esm/index.d.ts +2 -5
  126. package/lib-esm/index.js +1 -4
  127. package/lib-esm/libraryUtils.d.ts +7 -5
  128. package/lib-esm/libraryUtils.js +5 -3
  129. package/lib-esm/parseAWSExports.js +75 -14
  130. package/lib-esm/providers/pinpoint/apis/flushEvents.d.ts +2 -2
  131. package/lib-esm/providers/pinpoint/apis/record.js +3 -3
  132. package/lib-esm/providers/pinpoint/apis/updateEndpoint.js +6 -6
  133. package/lib-esm/singleton/API/types.d.ts +4 -3
  134. package/lib-esm/singleton/Amplify.d.ts +2 -2
  135. package/lib-esm/singleton/Amplify.js +6 -5
  136. package/lib-esm/singleton/Auth/types.d.ts +28 -1
  137. package/lib-esm/singleton/Cache/types.d.ts +18 -0
  138. package/lib-esm/singleton/Cache/types.js +3 -0
  139. package/lib-esm/singleton/types.d.ts +3 -1
  140. package/lib-esm/storage/DefaultStorage.js +2 -2
  141. package/lib-esm/storage/utils.d.ts +1 -1
  142. package/lib-esm/storage/utils.js +1 -1
  143. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  144. package/lib-esm/utils/amplifyUrl/index.d.ts +13 -0
  145. package/lib-esm/utils/amplifyUrl/index.js +6 -0
  146. package/lib-esm/utils/amplifyUuid/index.d.ts +3 -0
  147. package/lib-esm/utils/amplifyUuid/index.js +6 -0
  148. package/lib-esm/utils/amplifyUuid/polyfill.native.js +4 -0
  149. package/lib-esm/utils/deepFreeze.d.ts +1 -0
  150. package/lib-esm/utils/deepFreeze.js +34 -0
  151. package/lib-esm/{ClientDevice/android.d.ts → utils/getClientInfo/getClientInfo.android.d.ts} +1 -1
  152. package/lib-esm/{ClientDevice/android.js → utils/getClientInfo/getClientInfo.android.js} +2 -2
  153. package/lib-esm/{ClientDevice/browser.d.ts → utils/getClientInfo/getClientInfo.d.ts} +1 -9
  154. package/lib-esm/{ClientDevice/ios.d.ts → utils/getClientInfo/getClientInfo.ios.d.ts} +1 -1
  155. package/lib-esm/{ClientDevice/ios.js → utils/getClientInfo/getClientInfo.ios.js} +2 -2
  156. package/lib-esm/{ClientDevice/browser.js → utils/getClientInfo/getClientInfo.js} +4 -14
  157. package/lib-esm/utils/getClientInfo/index.d.ts +1 -0
  158. package/lib-esm/utils/getClientInfo/index.js +3 -0
  159. package/lib-esm/utils/index.d.ts +2 -0
  160. package/lib-esm/utils/index.js +2 -0
  161. package/package.json +7 -17
  162. package/src/Cache/StorageCache.native.ts +65 -0
  163. package/src/Cache/StorageCache.ts +61 -158
  164. package/src/Cache/StorageCacheCommon.ts +581 -0
  165. package/src/Cache/constants.ts +18 -0
  166. package/src/Cache/index.ts +6 -0
  167. package/src/Cache/types/cache.ts +51 -0
  168. package/src/Cache/types/index.ts +1 -1
  169. package/src/Cache/{Utils → utils}/CacheList.ts +185 -185
  170. package/src/Cache/utils/cacheHelpers.ts +52 -0
  171. package/src/Cache/{Utils → utils}/errorHelpers.ts +0 -4
  172. package/src/Cache/{Utils → utils}/index.ts +4 -5
  173. package/src/Hub/index.ts +8 -0
  174. package/src/Platform/customUserAgent.ts +75 -0
  175. package/src/Platform/index.ts +14 -1
  176. package/src/Platform/types.ts +45 -1
  177. package/src/Platform/version.ts +1 -1
  178. package/src/Reachability/Reachability.ts +14 -0
  179. package/src/Signer/Signer.ts +3 -2
  180. package/src/awsClients/cognitoIdentity/base.ts +4 -1
  181. package/src/awsClients/pinpoint/base.ts +2 -1
  182. package/src/awsClients/pinpoint/getInAppMessages.ts +2 -1
  183. package/src/awsClients/pinpoint/putEvents.ts +2 -1
  184. package/src/awsClients/pinpoint/updateEndpoint.ts +2 -1
  185. package/src/clients/middleware/signing/signer/signatureV4/index.ts +0 -2
  186. package/src/clients/middleware/signing/signer/signatureV4/presignUrl.ts +2 -1
  187. package/src/index.ts +3 -4
  188. package/src/libraryUtils.ts +17 -10
  189. package/src/parseAWSExports.ts +76 -13
  190. package/src/providers/pinpoint/apis/flushEvents.ts +2 -2
  191. package/src/providers/pinpoint/apis/record.ts +3 -3
  192. package/src/providers/pinpoint/apis/updateEndpoint.ts +6 -6
  193. package/src/singleton/API/types.ts +4 -3
  194. package/src/singleton/Amplify.ts +10 -8
  195. package/src/singleton/Auth/types.ts +50 -1
  196. package/src/singleton/Cache/types.ts +27 -0
  197. package/src/singleton/types.ts +3 -1
  198. package/src/storage/DefaultStorage.ts +2 -2
  199. package/src/storage/utils.ts +1 -1
  200. package/src/utils/amplifyUrl/index.ts +9 -0
  201. package/src/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.ts → utils/amplifyUrl/polyfill.native.ts} +1 -0
  202. package/src/utils/amplifyUuid/index.ts +9 -0
  203. package/src/utils/amplifyUuid/polyfill.native.ts +6 -0
  204. package/src/utils/amplifyUuid/polyfill.ts +4 -0
  205. package/src/utils/deepFreeze.ts +16 -0
  206. package/src/{ClientDevice/android.ts → utils/getClientInfo/getClientInfo.android.ts} +2 -2
  207. package/src/{ClientDevice/ios.ts → utils/getClientInfo/getClientInfo.ios.ts} +3 -3
  208. package/src/{ClientDevice/browser.ts → utils/getClientInfo/getClientInfo.ts} +4 -16
  209. package/src/utils/getClientInfo/index.ts +4 -0
  210. package/src/utils/index.ts +2 -0
  211. package/lib/Cache/BrowserStorageCache.d.ts +0 -166
  212. package/lib/Cache/BrowserStorageCache.js +0 -456
  213. package/lib/Cache/InMemoryCache.d.ts +0 -129
  214. package/lib/Cache/InMemoryCache.js +0 -342
  215. package/lib/Cache/Utils/CacheUtils.d.ts +0 -25
  216. package/lib/Cache/Utils/CacheUtils.js +0 -86
  217. package/lib/Cache/Utils/index.d.ts +0 -2
  218. package/lib/Cache/Utils/index.js +0 -16
  219. package/lib/Cache/reactnative.d.ts +0 -3
  220. package/lib/Cache/reactnative.js +0 -8
  221. package/lib/Cache/types/Cache.d.ts +0 -55
  222. package/lib/ClientDevice/index.d.ts +0 -23
  223. package/lib/ClientDevice/index.js +0 -18
  224. package/lib/ClientDevice/reactnative.d.ts +0 -7
  225. package/lib/ClientDevice/reactnative.js +0 -24
  226. package/lib-esm/Cache/BrowserStorageCache.d.ts +0 -166
  227. package/lib-esm/Cache/BrowserStorageCache.js +0 -453
  228. package/lib-esm/Cache/InMemoryCache.d.ts +0 -129
  229. package/lib-esm/Cache/InMemoryCache.js +0 -339
  230. package/lib-esm/Cache/Utils/CacheUtils.d.ts +0 -25
  231. package/lib-esm/Cache/Utils/CacheUtils.js +0 -79
  232. package/lib-esm/Cache/Utils/index.d.ts +0 -2
  233. package/lib-esm/Cache/Utils/index.js +0 -4
  234. package/lib-esm/Cache/reactnative.d.ts +0 -3
  235. package/lib-esm/Cache/reactnative.js +0 -6
  236. package/lib-esm/Cache/types/Cache.d.ts +0 -55
  237. package/lib-esm/ClientDevice/index.d.ts +0 -23
  238. package/lib-esm/ClientDevice/index.js +0 -15
  239. package/lib-esm/ClientDevice/reactnative.d.ts +0 -7
  240. package/lib-esm/ClientDevice/reactnative.js +0 -21
  241. package/src/Cache/AsyncStorageCache.ts +0 -495
  242. package/src/Cache/BrowserStorageCache.ts +0 -504
  243. package/src/Cache/CHANGELOG.md +0 -1239
  244. package/src/Cache/InMemoryCache.ts +0 -347
  245. package/src/Cache/Utils/CacheUtils.ts +0 -90
  246. package/src/Cache/reactnative.ts +0 -9
  247. package/src/Cache/types/Cache.ts +0 -75
  248. package/src/ClientDevice/index.ts +0 -14
  249. package/src/ClientDevice/reactnative.ts +0 -18
  250. package/lib/Cache/types/{Cache.js → cache.js} +0 -0
  251. package/lib/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.js → utils/amplifyUrl/polyfill.native.js} +1 -1
  252. /package/lib-esm/Cache/types/{Cache.js → cache.js} +0 -0
  253. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.d.ts → utils/amplifyUrl/polyfill.d.ts} +0 -0
  254. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.js → utils/amplifyUrl/polyfill.js} +0 -0
  255. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.d.ts → utils/amplifyUrl/polyfill.native.d.ts} +0 -0
  256. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.js → utils/amplifyUrl/polyfill.native.js} +0 -0
  257. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.d.ts → lib-esm/utils/amplifyUuid/polyfill.d.ts} +0 -0
  258. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.js → lib-esm/utils/amplifyUuid/polyfill.js} +0 -0
  259. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.native.d.ts → lib-esm/utils/amplifyUuid/polyfill.native.d.ts} +0 -0
  260. /package/src/{clients/middleware/signing/signer/signatureV4/polyfills/index.ts → utils/amplifyUrl/polyfill.ts} +0 -0
@@ -0,0 +1,581 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Amplify } from '../singleton';
5
+ import { ConsoleLogger as Logger } from '../Logger';
6
+ import { KeyValueStorageInterface } from '../types';
7
+ import { currentSizeKey, defaultConfig } from './constants';
8
+ import { CacheConfig, CacheItem, CacheItemOptions } from './types';
9
+ import { getCurrentSizeKey, getCurrentTime, getByteLength } from './utils';
10
+ import { assert, CacheErrorCode } from './utils/errorHelpers';
11
+
12
+ const logger = new Logger('StorageCache');
13
+
14
+ /**
15
+ * Initialization of the cache
16
+ *
17
+ */
18
+ export abstract class StorageCacheCommon {
19
+ protected config: CacheConfig;
20
+ protected keyValueStorage: KeyValueStorageInterface;
21
+
22
+ /**
23
+ * Initialize the cache
24
+ *
25
+ * @param config - Custom configuration for this instance.
26
+ */
27
+ constructor({
28
+ config,
29
+ keyValueStorage,
30
+ }: {
31
+ config?: CacheConfig;
32
+ keyValueStorage: KeyValueStorageInterface;
33
+ }) {
34
+ const globalCacheConfig = Amplify.getConfig().Cache ?? {};
35
+
36
+ this.config = {
37
+ ...defaultConfig,
38
+ ...globalCacheConfig,
39
+ ...config,
40
+ };
41
+ this.keyValueStorage = keyValueStorage;
42
+
43
+ this.sanitizeConfig();
44
+ }
45
+
46
+ protected abstract getAllCacheKeys(options?: {
47
+ omitSizeKey?: boolean;
48
+ }): Promise<string[]>;
49
+
50
+ public getModuleName() {
51
+ return 'Cache';
52
+ }
53
+
54
+ /**
55
+ * Set custom configuration for the cache instance.
56
+ *
57
+ * @param config - customized configuration (without keyPrefix, which can't be changed)
58
+ *
59
+ * @return - the current configuration
60
+ */
61
+ public configure(config?: Omit<CacheConfig, 'keyPrefix'>): CacheConfig {
62
+ if (config) {
63
+ if ((config as CacheConfig).keyPrefix) {
64
+ logger.warn(
65
+ 'keyPrefix can not be re-configured on an existing Cache instance.'
66
+ );
67
+ }
68
+
69
+ this.config = {
70
+ ...this.config,
71
+ ...config,
72
+ };
73
+ }
74
+
75
+ this.sanitizeConfig();
76
+
77
+ return this.config;
78
+ }
79
+
80
+ /**
81
+ * return the current size of the cache
82
+ * @return {Promise}
83
+ */
84
+ public async getCurrentCacheSize() {
85
+ let size = await this.getStorage().getItem(
86
+ getCurrentSizeKey(this.config.keyPrefix)
87
+ );
88
+ if (!size) {
89
+ await this.getStorage().setItem(
90
+ getCurrentSizeKey(this.config.keyPrefix),
91
+ '0'
92
+ );
93
+ size = '0';
94
+ }
95
+ return Number(size);
96
+ }
97
+
98
+ /**
99
+ * Set item into cache. You can put number, string, boolean or object.
100
+ * The cache will first check whether has the same key.
101
+ * If it has, it will delete the old item and then put the new item in
102
+ * The cache will pop out items if it is full
103
+ * You can specify the cache item options. The cache will abort and output a warning:
104
+ * If the key is invalid
105
+ * If the size of the item exceeds itemMaxSize.
106
+ * If the value is undefined
107
+ * If incorrect cache item configuration
108
+ * If error happened with browser storage
109
+ *
110
+ * @param {String} key - the key of the item
111
+ * @param {Object} value - the value of the item
112
+ * @param {Object} [options] - optional, the specified meta-data
113
+ *
114
+ * @return {Promise}
115
+ */
116
+ public async setItem(
117
+ key: string,
118
+ value: any,
119
+ options?: Record<string, any>
120
+ ): Promise<void> {
121
+ logger.debug(
122
+ `Set item: key is ${key}, value is ${value} with options: ${options}`
123
+ );
124
+
125
+ if (!key || key === currentSizeKey) {
126
+ logger.warn(
127
+ `Invalid key: should not be empty or reserved key: '${currentSizeKey}'`
128
+ );
129
+ return;
130
+ }
131
+
132
+ if (typeof value === 'undefined') {
133
+ logger.warn(`The value of item should not be undefined!`);
134
+ return;
135
+ }
136
+
137
+ const cacheItemOptions = {
138
+ priority:
139
+ options?.priority !== undefined
140
+ ? options.priority
141
+ : this.config.defaultPriority,
142
+ expires:
143
+ options?.expires !== undefined
144
+ ? options.expires
145
+ : this.config.defaultTTL + getCurrentTime(),
146
+ };
147
+
148
+ if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
149
+ logger.warn(
150
+ `Invalid parameter: priority due to out or range. It should be within 1 and 5.`
151
+ );
152
+ return;
153
+ }
154
+
155
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
156
+ const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
157
+
158
+ // check whether this item is too big;
159
+ if (item.byteSize > this.config.itemMaxSize) {
160
+ logger.warn(
161
+ `Item with key: ${key} you are trying to put into is too big!`
162
+ );
163
+ return;
164
+ }
165
+
166
+ try {
167
+ // first look into the storage, if it exists, delete it.
168
+ const val = await this.getStorage().getItem(prefixedKey);
169
+ if (val) {
170
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
171
+ }
172
+
173
+ // check whether the cache is full
174
+ if (await this.isCacheFull(item.byteSize)) {
175
+ const validKeys = await this.clearInvalidAndGetRemainingKeys();
176
+ if (await this.isCacheFull(item.byteSize)) {
177
+ const sizeToPop = await this.sizeToPop(item.byteSize);
178
+ await this.popOutItems(validKeys, sizeToPop);
179
+ }
180
+ }
181
+ // put item in the cache
182
+ return this.setCacheItem(prefixedKey, item);
183
+ } catch (e) {
184
+ logger.warn(`setItem failed! ${e}`);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Get item from cache. It will return null if item doesn’t exist or it has been expired.
190
+ * If you specified callback function in the options,
191
+ * then the function will be executed if no such item in the cache
192
+ * and finally put the return value into cache.
193
+ * Please make sure the callback function will return the value you want to put into the cache.
194
+ * The cache will abort output a warning:
195
+ * If the key is invalid
196
+ * If error happened with AsyncStorage
197
+ *
198
+ * @param {String} key - the key of the item
199
+ * @param {Object} [options] - the options of callback function
200
+ *
201
+ * @return {Promise} - return a promise resolves to be the value of the item
202
+ */
203
+ public async getItem(
204
+ key: string,
205
+ options?: CacheItemOptions
206
+ ): Promise<CacheItem['data']> {
207
+ logger.debug(`Get item: key is ${key} with options ${options}`);
208
+ let cached;
209
+
210
+ if (!key || key === currentSizeKey) {
211
+ logger.warn(
212
+ `Invalid key: should not be empty or reserved key: '${currentSizeKey}'`
213
+ );
214
+ return null;
215
+ }
216
+
217
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
218
+
219
+ try {
220
+ cached = await this.getStorage().getItem(prefixedKey);
221
+ if (cached != null) {
222
+ if (await this.isExpired(prefixedKey)) {
223
+ // if expired, remove that item and return null
224
+ await this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize);
225
+ } else {
226
+ // if not expired, update its visitedTime and return the value
227
+ const item = await this.updateVisitedTime(
228
+ JSON.parse(cached),
229
+ prefixedKey
230
+ );
231
+ return item.data;
232
+ }
233
+ }
234
+
235
+ if (options?.callback) {
236
+ const val = options.callback();
237
+ if (val !== null) {
238
+ await this.setItem(key, val, options);
239
+ }
240
+ return val;
241
+ }
242
+ return null;
243
+ } catch (e) {
244
+ logger.warn(`getItem failed! ${e}`);
245
+ return null;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * remove item from the cache
251
+ * The cache will abort output a warning:
252
+ * If error happened with AsyncStorage
253
+ * @param {String} key - the key of the item
254
+ * @return {Promise}
255
+ */
256
+ public async removeItem(key: string): Promise<void> {
257
+ logger.debug(`Remove item: key is ${key}`);
258
+
259
+ if (!key || key === currentSizeKey) {
260
+ logger.warn(
261
+ `Invalid key: should not be empty or reserved key: '${currentSizeKey}'`
262
+ );
263
+ return;
264
+ }
265
+
266
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
267
+
268
+ try {
269
+ const val = await this.getStorage().getItem(prefixedKey);
270
+ if (val) {
271
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
272
+ }
273
+ } catch (e) {
274
+ logger.warn(`removeItem failed! ${e}`);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Return all the keys owned by this cache.
280
+ * Will return an empty array if error occurred.
281
+ *
282
+ * @return {Promise}
283
+ */
284
+ public async getAllKeys() {
285
+ try {
286
+ return await this.getAllCacheKeys();
287
+ } catch (e) {
288
+ logger.warn(`getAllkeys failed! ${e}`);
289
+ return [];
290
+ }
291
+ }
292
+
293
+ protected getStorage(): KeyValueStorageInterface {
294
+ return this.keyValueStorage;
295
+ }
296
+
297
+ /**
298
+ * check whether item is expired
299
+ *
300
+ * @param key - the key of the item
301
+ *
302
+ * @return true if the item is expired.
303
+ */
304
+ protected async isExpired(key: string): Promise<boolean> {
305
+ const text = await this.getStorage().getItem(key);
306
+ assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`);
307
+ const item: CacheItem = JSON.parse(text);
308
+ if (getCurrentTime() >= item.expires) {
309
+ return true;
310
+ }
311
+ return false;
312
+ }
313
+
314
+ /**
315
+ * delete item from cache
316
+ *
317
+ * @param prefixedKey - the key of the item
318
+ * @param size - optional, the byte size of the item
319
+ */
320
+ protected async removeCacheItem(
321
+ prefixedKey: string,
322
+ size?: number
323
+ ): Promise<void> {
324
+ const item = await this.getStorage().getItem(prefixedKey);
325
+ assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`);
326
+ const itemSize: number = size ?? JSON.parse(item).byteSize;
327
+ // first try to update the current size of the cache
328
+ await this.decreaseCurrentSizeInBytes(itemSize);
329
+
330
+ // try to remove the item from cache
331
+ try {
332
+ await this.getStorage().removeItem(prefixedKey);
333
+ } catch (removeItemError) {
334
+ // if some error happened, we need to rollback the current size
335
+ await this.increaseCurrentSizeInBytes(itemSize);
336
+ logger.error(`Failed to remove item: ${removeItemError}`);
337
+ }
338
+ }
339
+
340
+ /**
341
+ * produce a JSON object with meta-data and data value
342
+ * @param value - the value of the item
343
+ * @param options - optional, the specified meta-data
344
+ *
345
+ * @return - the item which has the meta-data and the value
346
+ */
347
+ protected fillCacheItem(
348
+ key: string,
349
+ value: object | number | string | boolean,
350
+ options: CacheItemOptions
351
+ ): CacheItem {
352
+ const item: CacheItem = {
353
+ key,
354
+ data: value,
355
+ timestamp: getCurrentTime(),
356
+ visitedTime: getCurrentTime(),
357
+ priority: options.priority ?? 0,
358
+ expires: options.expires ?? 0,
359
+ type: typeof value,
360
+ byteSize: 0,
361
+ };
362
+ // calculate byte size
363
+ item.byteSize = getByteLength(JSON.stringify(item));
364
+ // re-calculate using cache item with updated byteSize property
365
+ item.byteSize = getByteLength(JSON.stringify(item));
366
+ return item;
367
+ }
368
+
369
+ private sanitizeConfig(): void {
370
+ if (this.config.itemMaxSize > this.config.capacityInBytes) {
371
+ logger.error(
372
+ 'Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.'
373
+ );
374
+ this.config.itemMaxSize = defaultConfig.itemMaxSize;
375
+ }
376
+
377
+ if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {
378
+ logger.error(
379
+ 'Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.'
380
+ );
381
+ this.config.defaultPriority = defaultConfig.defaultPriority;
382
+ }
383
+
384
+ if (
385
+ Number(this.config.warningThreshold) > 1 ||
386
+ Number(this.config.warningThreshold) < 0
387
+ ) {
388
+ logger.error(
389
+ 'Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.'
390
+ );
391
+ this.config.warningThreshold = defaultConfig.warningThreshold;
392
+ }
393
+
394
+ // Set 5MB limit
395
+ const cacheLimit: number = 5 * 1024 * 1024;
396
+ if (this.config.capacityInBytes > cacheLimit) {
397
+ logger.error(
398
+ 'Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.'
399
+ );
400
+ this.config.capacityInBytes = defaultConfig.capacityInBytes;
401
+ }
402
+ }
403
+
404
+ /**
405
+ * increase current size of the cache
406
+ *
407
+ * @param amount - the amount of the cache szie which need to be increased
408
+ */
409
+ private async increaseCurrentSizeInBytes(amount: number): Promise<void> {
410
+ const size = await this.getCurrentCacheSize();
411
+ await this.getStorage().setItem(
412
+ getCurrentSizeKey(this.config.keyPrefix),
413
+ (size + amount).toString()
414
+ );
415
+ }
416
+
417
+ /**
418
+ * decrease current size of the cache
419
+ *
420
+ * @param amount - the amount of the cache size which needs to be decreased
421
+ */
422
+ private async decreaseCurrentSizeInBytes(amount: number): Promise<void> {
423
+ const size = await this.getCurrentCacheSize();
424
+ await this.getStorage().setItem(
425
+ getCurrentSizeKey(this.config.keyPrefix),
426
+ (size - amount).toString()
427
+ );
428
+ }
429
+
430
+ /**
431
+ * update the visited time if item has been visited
432
+ *
433
+ * @param item - the item which need to be updated
434
+ * @param prefixedKey - the key of the item
435
+ *
436
+ * @return the updated item
437
+ */
438
+ private async updateVisitedTime(
439
+ item: CacheItem,
440
+ prefixedKey: string
441
+ ): Promise<CacheItem> {
442
+ item.visitedTime = getCurrentTime();
443
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
444
+ return item;
445
+ }
446
+
447
+ /**
448
+ * put item into cache
449
+ *
450
+ * @param prefixedKey - the key of the item
451
+ * @param itemData - the value of the item
452
+ * @param itemSizeInBytes - the byte size of the item
453
+ */
454
+ private async setCacheItem(
455
+ prefixedKey: string,
456
+ item: CacheItem
457
+ ): Promise<void> {
458
+ // first try to update the current size of the cache.
459
+ await this.increaseCurrentSizeInBytes(item.byteSize);
460
+
461
+ // try to add the item into cache
462
+ try {
463
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
464
+ } catch (setItemErr) {
465
+ // if some error happened, we need to rollback the current size
466
+ await this.decreaseCurrentSizeInBytes(item.byteSize);
467
+ logger.error(`Failed to set item ${setItemErr}`);
468
+ }
469
+ }
470
+
471
+ /**
472
+ * total space needed when poping out items
473
+ *
474
+ * @param itemSize
475
+ *
476
+ * @return total space needed
477
+ */
478
+ private async sizeToPop(itemSize: number): Promise<number> {
479
+ const cur = await this.getCurrentCacheSize();
480
+ const spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
481
+ const cacheThresholdSpace =
482
+ (1 - this.config.warningThreshold) * this.config.capacityInBytes;
483
+ return spaceItemNeed > cacheThresholdSpace
484
+ ? spaceItemNeed
485
+ : cacheThresholdSpace;
486
+ }
487
+
488
+ /**
489
+ * see whether cache is full
490
+ *
491
+ * @param itemSize
492
+ *
493
+ * @return true if cache is full
494
+ */
495
+ private async isCacheFull(itemSize: number): Promise<boolean> {
496
+ const cur = await this.getCurrentCacheSize();
497
+ return itemSize + cur > this.config.capacityInBytes;
498
+ }
499
+
500
+ /**
501
+ * get all the items we have, sort them by their priority,
502
+ * if priority is same, sort them by their last visited time
503
+ * pop out items from the low priority (5 is the lowest)
504
+ * @private
505
+ * @param keys - all the keys in this cache
506
+ * @param sizeToPop - the total size of the items which needed to be poped out
507
+ */
508
+ private async popOutItems(keys: string[], sizeToPop: number): Promise<void> {
509
+ const items: any[] = [];
510
+ let remainedSize = sizeToPop;
511
+ for (let i = 0; i < keys.length; i += 1) {
512
+ const val = await this.getStorage().getItem(keys[i]);
513
+ if (val != null) {
514
+ const item = JSON.parse(val);
515
+ items.push(item);
516
+ }
517
+ }
518
+
519
+ // first compare priority
520
+ // then compare visited time
521
+ items.sort((a, b) => {
522
+ if (a.priority > b.priority) {
523
+ return -1;
524
+ } else if (a.priority < b.priority) {
525
+ return 1;
526
+ } else {
527
+ if (a.visitedTime < b.visitedTime) {
528
+ return -1;
529
+ } else return 1;
530
+ }
531
+ });
532
+
533
+ for (let i = 0; i < items.length; i += 1) {
534
+ // pop out items until we have enough room for new item
535
+ await this.removeCacheItem(items[i].key, items[i].byteSize);
536
+ remainedSize -= items[i].byteSize;
537
+ if (remainedSize <= 0) {
538
+ return;
539
+ }
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Scan the storage and combine the following operations for efficiency
545
+ * 1. Clear out all expired keys owned by this cache, not including the size key.
546
+ * 2. Return the remaining keys.
547
+ *
548
+ * @return The remaining valid keys
549
+ */
550
+ private async clearInvalidAndGetRemainingKeys(): Promise<string[]> {
551
+ const remainingKeys = [];
552
+ const keys = await this.getAllCacheKeys({
553
+ omitSizeKey: true,
554
+ });
555
+ for (const key of keys) {
556
+ if (await this.isExpired(key)) {
557
+ await this.removeCacheItem(key);
558
+ } else {
559
+ remainingKeys.push(key);
560
+ }
561
+ }
562
+ return remainingKeys;
563
+ }
564
+
565
+ /**
566
+ * clear the entire cache
567
+ * The cache will abort and output a warning if error occurs
568
+ * @return {Promise}
569
+ */
570
+ async clear() {
571
+ logger.debug(`Clear Cache`);
572
+ try {
573
+ const keys = await this.getAllKeys();
574
+ for (const key of keys) {
575
+ await this.getStorage().removeItem(key);
576
+ }
577
+ } catch (e) {
578
+ logger.warn(`clear failed! ${e}`);
579
+ }
580
+ }
581
+ }
@@ -0,0 +1,18 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { CacheConfig } from './types';
5
+
6
+ /**
7
+ * Default cache config
8
+ */
9
+ export const defaultConfig: Omit<CacheConfig, 'storage'> = {
10
+ keyPrefix: 'aws-amplify-cache',
11
+ capacityInBytes: 1048576, // 1MB
12
+ itemMaxSize: 210000, // about 200kb
13
+ defaultTTL: 259200000, // about 3 days
14
+ defaultPriority: 5,
15
+ warningThreshold: 0.8,
16
+ };
17
+
18
+ export const currentSizeKey = 'CurSize';
@@ -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 { StorageCache } from './StorageCache';
5
+
6
+ export const Cache = new StorageCache();
@@ -0,0 +1,51 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { CacheConfig } from '../../singleton/Cache/types';
5
+ export { CacheConfig };
6
+
7
+ /**
8
+ * Cache Interface
9
+ */
10
+ export interface Cache {
11
+ /** Put item into cache */
12
+ setItem(key: string, value: any, options?: CacheItemOptions): Promise<void>;
13
+
14
+ /** Get item from cache */
15
+ getItem(key: string, options?: CacheItemOptions): Promise<CacheItem['data']>;
16
+
17
+ /** Remove item from cache */
18
+ removeItem(key: string): Promise<void>;
19
+
20
+ /** Remove all items from cache */
21
+ clear(): Promise<void>;
22
+
23
+ /** Get all keys form cache */
24
+ getAllKeys(): Promise<string[]>;
25
+
26
+ /** Get current size of the cache */
27
+ getCurrentCacheSize(): Promise<number>;
28
+
29
+ /** create a new instance with customized config */
30
+ createInstance(config: CacheConfig): Cache;
31
+
32
+ /** change current configuration */
33
+ configure(config: CacheConfig): CacheConfig;
34
+ }
35
+
36
+ export interface CacheItem {
37
+ key: string;
38
+ data: any;
39
+ timestamp: number;
40
+ visitedTime: number;
41
+ priority: number;
42
+ expires: number;
43
+ type: string;
44
+ byteSize: number;
45
+ }
46
+
47
+ export interface CacheItemOptions {
48
+ priority?: number;
49
+ expires?: number;
50
+ callback?: Function;
51
+ }
@@ -1,4 +1,4 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- export * from './Cache';
4
+ export * from './cache';