@aws-amplify/core 5.8.2 → 6.0.1-console-preview.7919075.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 (300) hide show
  1. package/README.md +3 -0
  2. package/lib/Amplify.d.ts +18 -17
  3. package/lib/Amplify.js +9 -0
  4. package/lib/AwsClients/CognitoIdentity/base.d.ts +3 -10
  5. package/lib/AwsClients/CognitoIdentity/getCredentialsForIdentity.d.ts +3 -17
  6. package/lib/AwsClients/CognitoIdentity/getCredentialsForIdentity.js +8 -8
  7. package/lib/AwsClients/CognitoIdentity/getId.d.ts +3 -17
  8. package/lib/AwsClients/Pinpoint/base.d.ts +2 -10
  9. package/lib/AwsClients/Pinpoint/getInAppMessages.d.ts +3 -17
  10. package/lib/AwsClients/Pinpoint/getInAppMessages.js +1 -1
  11. package/lib/AwsClients/Pinpoint/putEvents.d.ts +3 -17
  12. package/lib/AwsClients/Pinpoint/putEvents.js +6 -0
  13. package/lib/AwsClients/Pinpoint/updateEndpoint.d.ts +3 -17
  14. package/lib/AwsClients/Pinpoint/updateEndpoint.js +2 -2
  15. package/lib/Cache/AsyncStorageCache.d.ts +154 -0
  16. package/lib/Cache/AsyncStorageCache.js +744 -0
  17. package/lib/Cache/BrowserStorageCache.d.ts +166 -0
  18. package/lib/Cache/BrowserStorageCache.js +469 -0
  19. package/lib/Cache/InMemoryCache.d.ts +129 -0
  20. package/lib/Cache/InMemoryCache.js +349 -0
  21. package/lib/Cache/StorageCache.d.ts +39 -0
  22. package/lib/Cache/StorageCache.js +121 -0
  23. package/lib/Cache/Utils/CacheList.d.ts +89 -0
  24. package/lib/Cache/Utils/CacheList.js +196 -0
  25. package/lib/Cache/Utils/CacheUtils.d.ts +25 -0
  26. package/lib/Cache/Utils/CacheUtils.js +88 -0
  27. package/lib/Cache/Utils/index.d.ts +2 -0
  28. package/lib/Cache/Utils/index.js +16 -0
  29. package/lib/Cache/reactnative.d.ts +3 -0
  30. package/lib/Cache/reactnative.js +8 -0
  31. package/lib/Cache/types/Cache.d.ts +55 -0
  32. package/lib/Cache/types/Cache.js +4 -0
  33. package/lib/Cache/types/index.d.ts +1 -0
  34. package/lib/Cache/types/index.js +19 -0
  35. package/lib/ClientDevice/android.js +3 -2
  36. package/lib/ClientDevice/ios.d.ts +2 -2
  37. package/lib/ClientDevice/ios.js +3 -2
  38. package/lib/ClientDevice/reactnative.js +3 -2
  39. package/lib/Credentials.d.ts +1 -1
  40. package/lib/Credentials.js +2 -1
  41. package/lib/Errors.d.ts +19 -0
  42. package/lib/Errors.js +50 -1
  43. package/lib/Hub.js +1 -0
  44. package/lib/I18n/I18n.d.ts +29 -9
  45. package/lib/I18n/I18n.js +30 -5
  46. package/lib/I18n/index.d.ts +18 -5
  47. package/lib/I18n/index.js +35 -5
  48. package/lib/I18n/types.d.ts +4 -1
  49. package/lib/I18n/types.js +3 -0
  50. package/lib/JS.d.ts +6 -6
  51. package/lib/Logger/ConsoleLogger.d.ts +11 -11
  52. package/lib/OAuthHelper/GoogleOAuth.js +2 -1
  53. package/lib/Platform/detectFramework.js +2 -1
  54. package/lib/Platform/detection/Next.d.ts +1 -1
  55. package/lib/Platform/detection/React.js +1 -0
  56. package/lib/Platform/version.d.ts +1 -1
  57. package/lib/Platform/version.js +1 -1
  58. package/lib/Providers/AWSCloudWatchProvider.d.ts +2 -2
  59. package/lib/Providers/AWSCloudWatchProvider.js +35 -12
  60. package/lib/RNComponents/index.d.ts +1 -1
  61. package/lib/RNComponents/reactnative.js +3 -2
  62. package/lib/ServiceWorker/ServiceWorker.d.ts +4 -4
  63. package/lib/ServiceWorker/ServiceWorker.js +37 -11
  64. package/lib/Signer.d.ts +14 -1
  65. package/lib/StorageHelper/cookieStorage.d.ts +13 -0
  66. package/lib/StorageHelper/cookieStorage.js +167 -0
  67. package/lib/StorageHelper/inMemoryStorage.d.ts +10 -0
  68. package/lib/StorageHelper/inMemoryStorage.js +82 -0
  69. package/lib/StorageHelper/index.d.ts +7 -3
  70. package/lib/StorageHelper/index.js +9 -1
  71. package/lib/StorageHelper/localStorage.d.ts +32 -0
  72. package/lib/StorageHelper/localStorage.js +114 -0
  73. package/lib/StorageHelper/reactnative.d.ts +71 -1
  74. package/lib/StorageHelper/reactnative.js +154 -10
  75. package/lib/StorageHelper/sessionStorage.d.ts +32 -0
  76. package/lib/StorageHelper/sessionStorage.js +114 -0
  77. package/lib/UniversalStorage/index.d.ts +2 -2
  78. package/lib/Util/BackgroundProcessManager.d.ts +2 -2
  79. package/lib/Util/BackgroundProcessManager.js +1 -0
  80. package/lib/Util/DateUtils.d.ts +12 -1
  81. package/lib/Util/Reachability.js +7 -5
  82. package/lib/Util/Reachability.native.d.ts +3 -2
  83. package/lib/Util/StringUtils.js +3 -10
  84. package/lib/Util/errors/AssertError.d.ts +2 -0
  85. package/lib/Util/errors/AssertError.js +11 -0
  86. package/lib/clients/middleware/retry/defaultRetryDecider.d.ts +1 -1
  87. package/lib/clients/middleware/retry/defaultRetryDecider.js +17 -13
  88. package/lib/clients/middleware/retry/isClockSkewError.js +1 -1
  89. package/lib/clients/middleware/retry/middleware.d.ts +1 -1
  90. package/lib/clients/middleware/retry/middleware.js +13 -13
  91. package/lib/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +1 -1
  92. package/lib/clients/serde/responseInfo.js +1 -1
  93. package/lib/clients/types/aws.d.ts +4 -0
  94. package/lib/clients/types/index.d.ts +1 -1
  95. package/lib/constants.d.ts +7 -0
  96. package/lib/constants.js +9 -1
  97. package/lib/index.d.ts +18 -4
  98. package/lib/index.js +32 -5
  99. package/lib/parseAWSExports.d.ts +1 -1
  100. package/lib/singleton/Auth/index.d.ts +30 -0
  101. package/lib/singleton/Auth/index.js +133 -0
  102. package/lib/singleton/Auth/types.d.ts +95 -0
  103. package/lib/singleton/Auth/types.js +6 -0
  104. package/lib/singleton/Auth/utils/index.d.ts +5 -0
  105. package/lib/singleton/Auth/utils/index.js +52 -0
  106. package/lib/singleton/Storage/types.d.ts +14 -0
  107. package/lib/singleton/Storage/types.js +4 -0
  108. package/lib/singleton/index.d.ts +46 -0
  109. package/lib/singleton/index.js +160 -0
  110. package/lib/singleton/types.d.ts +21 -0
  111. package/lib/singleton/types.js +4 -0
  112. package/lib/tsconfig.tsbuildinfo +1 -1
  113. package/lib/types/types.d.ts +31 -1
  114. package/lib/types/types.js +2 -0
  115. package/lib-esm/Amplify.d.ts +18 -17
  116. package/lib-esm/Amplify.js +9 -0
  117. package/lib-esm/AwsClients/CognitoIdentity/base.d.ts +3 -10
  118. package/lib-esm/AwsClients/CognitoIdentity/getCredentialsForIdentity.d.ts +3 -17
  119. package/lib-esm/AwsClients/CognitoIdentity/getCredentialsForIdentity.js +8 -8
  120. package/lib-esm/AwsClients/CognitoIdentity/getId.d.ts +3 -17
  121. package/lib-esm/AwsClients/Pinpoint/base.d.ts +2 -10
  122. package/lib-esm/AwsClients/Pinpoint/getInAppMessages.d.ts +3 -17
  123. package/lib-esm/AwsClients/Pinpoint/getInAppMessages.js +1 -1
  124. package/lib-esm/AwsClients/Pinpoint/putEvents.d.ts +3 -17
  125. package/lib-esm/AwsClients/Pinpoint/putEvents.js +6 -0
  126. package/lib-esm/AwsClients/Pinpoint/updateEndpoint.d.ts +3 -17
  127. package/lib-esm/AwsClients/Pinpoint/updateEndpoint.js +2 -2
  128. package/lib-esm/Cache/AsyncStorageCache.d.ts +154 -0
  129. package/lib-esm/Cache/AsyncStorageCache.js +737 -0
  130. package/lib-esm/Cache/BrowserStorageCache.d.ts +166 -0
  131. package/lib-esm/Cache/BrowserStorageCache.js +466 -0
  132. package/lib-esm/Cache/InMemoryCache.d.ts +129 -0
  133. package/lib-esm/Cache/InMemoryCache.js +346 -0
  134. package/lib-esm/Cache/StorageCache.d.ts +39 -0
  135. package/lib-esm/Cache/StorageCache.js +118 -0
  136. package/lib-esm/Cache/Utils/CacheList.d.ts +89 -0
  137. package/lib-esm/Cache/Utils/CacheList.js +194 -0
  138. package/lib-esm/Cache/Utils/CacheUtils.d.ts +25 -0
  139. package/lib-esm/Cache/Utils/CacheUtils.js +81 -0
  140. package/lib-esm/Cache/Utils/index.d.ts +2 -0
  141. package/lib-esm/Cache/Utils/index.js +4 -0
  142. package/lib-esm/Cache/reactnative.d.ts +3 -0
  143. package/lib-esm/Cache/reactnative.js +6 -0
  144. package/lib-esm/Cache/types/Cache.d.ts +55 -0
  145. package/lib-esm/Cache/types/Cache.js +3 -0
  146. package/lib-esm/Cache/types/index.d.ts +1 -0
  147. package/lib-esm/Cache/types/index.js +3 -0
  148. package/lib-esm/ClientDevice/android.js +1 -0
  149. package/lib-esm/ClientDevice/ios.d.ts +2 -2
  150. package/lib-esm/ClientDevice/ios.js +1 -0
  151. package/lib-esm/ClientDevice/reactnative.js +1 -0
  152. package/lib-esm/Credentials.d.ts +1 -1
  153. package/lib-esm/Credentials.js +2 -1
  154. package/lib-esm/Errors.d.ts +19 -0
  155. package/lib-esm/Errors.js +49 -0
  156. package/lib-esm/Hub.js +1 -0
  157. package/lib-esm/I18n/I18n.d.ts +29 -9
  158. package/lib-esm/I18n/I18n.js +30 -5
  159. package/lib-esm/I18n/index.d.ts +18 -5
  160. package/lib-esm/I18n/index.js +35 -5
  161. package/lib-esm/I18n/types.d.ts +4 -1
  162. package/lib-esm/I18n/types.js +3 -0
  163. package/lib-esm/JS.d.ts +6 -6
  164. package/lib-esm/Logger/ConsoleLogger.d.ts +11 -11
  165. package/lib-esm/OAuthHelper/GoogleOAuth.js +2 -1
  166. package/lib-esm/Platform/detectFramework.js +2 -1
  167. package/lib-esm/Platform/detection/Next.d.ts +1 -1
  168. package/lib-esm/Platform/detection/React.js +1 -0
  169. package/lib-esm/Platform/version.d.ts +1 -1
  170. package/lib-esm/Platform/version.js +1 -1
  171. package/lib-esm/Providers/AWSCloudWatchProvider.d.ts +2 -2
  172. package/lib-esm/Providers/AWSCloudWatchProvider.js +33 -10
  173. package/lib-esm/RNComponents/index.d.ts +1 -1
  174. package/lib-esm/RNComponents/reactnative.js +1 -0
  175. package/lib-esm/ServiceWorker/ServiceWorker.d.ts +4 -4
  176. package/lib-esm/ServiceWorker/ServiceWorker.js +37 -11
  177. package/lib-esm/Signer.d.ts +14 -1
  178. package/lib-esm/StorageHelper/cookieStorage.d.ts +13 -0
  179. package/lib-esm/StorageHelper/cookieStorage.js +141 -0
  180. package/lib-esm/StorageHelper/inMemoryStorage.d.ts +10 -0
  181. package/lib-esm/StorageHelper/inMemoryStorage.js +79 -0
  182. package/lib-esm/StorageHelper/index.d.ts +7 -3
  183. package/lib-esm/StorageHelper/index.js +4 -0
  184. package/lib-esm/StorageHelper/localStorage.d.ts +32 -0
  185. package/lib-esm/StorageHelper/localStorage.js +111 -0
  186. package/lib-esm/StorageHelper/reactnative.d.ts +71 -1
  187. package/lib-esm/StorageHelper/reactnative.js +153 -9
  188. package/lib-esm/StorageHelper/sessionStorage.d.ts +32 -0
  189. package/lib-esm/StorageHelper/sessionStorage.js +111 -0
  190. package/lib-esm/UniversalStorage/index.d.ts +2 -2
  191. package/lib-esm/Util/BackgroundProcessManager.d.ts +2 -2
  192. package/lib-esm/Util/BackgroundProcessManager.js +1 -0
  193. package/lib-esm/Util/DateUtils.d.ts +12 -1
  194. package/lib-esm/Util/Reachability.js +5 -3
  195. package/lib-esm/Util/Reachability.native.d.ts +3 -2
  196. package/lib-esm/Util/StringUtils.js +3 -10
  197. package/lib-esm/Util/errors/AssertError.d.ts +2 -0
  198. package/lib-esm/Util/errors/AssertError.js +7 -0
  199. package/lib-esm/clients/middleware/retry/defaultRetryDecider.d.ts +1 -1
  200. package/lib-esm/clients/middleware/retry/defaultRetryDecider.js +17 -13
  201. package/lib-esm/clients/middleware/retry/isClockSkewError.js +1 -1
  202. package/lib-esm/clients/middleware/retry/middleware.d.ts +1 -1
  203. package/lib-esm/clients/middleware/retry/middleware.js +13 -13
  204. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +1 -1
  205. package/lib-esm/clients/serde/responseInfo.js +1 -1
  206. package/lib-esm/clients/types/aws.d.ts +4 -0
  207. package/lib-esm/clients/types/index.d.ts +1 -1
  208. package/lib-esm/constants.d.ts +7 -0
  209. package/lib-esm/constants.js +8 -0
  210. package/lib-esm/index.d.ts +18 -4
  211. package/lib-esm/index.js +15 -3
  212. package/lib-esm/parseAWSExports.d.ts +1 -1
  213. package/lib-esm/singleton/Auth/index.d.ts +30 -0
  214. package/lib-esm/singleton/Auth/index.js +129 -0
  215. package/lib-esm/singleton/Auth/types.d.ts +95 -0
  216. package/lib-esm/singleton/Auth/types.js +5 -0
  217. package/lib-esm/singleton/Auth/utils/index.d.ts +5 -0
  218. package/lib-esm/singleton/Auth/utils/index.js +45 -0
  219. package/lib-esm/singleton/Storage/types.d.ts +14 -0
  220. package/lib-esm/singleton/Storage/types.js +3 -0
  221. package/lib-esm/singleton/index.d.ts +46 -0
  222. package/lib-esm/singleton/index.js +156 -0
  223. package/lib-esm/singleton/types.d.ts +21 -0
  224. package/lib-esm/singleton/types.js +3 -0
  225. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  226. package/lib-esm/types/types.d.ts +31 -1
  227. package/lib-esm/types/types.js +2 -0
  228. package/package.json +38 -15
  229. package/src/Amplify.ts +9 -3
  230. package/src/AwsClients/CognitoIdentity/base.ts +2 -1
  231. package/src/AwsClients/CognitoIdentity/getCredentialsForIdentity.ts +13 -6
  232. package/src/AwsClients/Pinpoint/base.ts +6 -2
  233. package/src/AwsClients/Pinpoint/getInAppMessages.ts +1 -1
  234. package/src/AwsClients/Pinpoint/putEvents.ts +6 -0
  235. package/src/AwsClients/Pinpoint/updateEndpoint.ts +2 -2
  236. package/src/Cache/AsyncStorageCache.ts +500 -0
  237. package/src/Cache/BrowserStorageCache.ts +517 -0
  238. package/src/Cache/CHANGELOG.md +1227 -0
  239. package/src/Cache/InMemoryCache.ts +354 -0
  240. package/src/Cache/StorageCache.ts +157 -0
  241. package/src/Cache/Utils/CacheList.ts +198 -0
  242. package/src/Cache/Utils/CacheUtils.ts +92 -0
  243. package/src/Cache/Utils/index.ts +11 -0
  244. package/src/Cache/reactnative.ts +9 -0
  245. package/src/Cache/types/Cache.ts +75 -0
  246. package/src/Cache/types/index.ts +4 -0
  247. package/src/ClientDevice/android.ts +1 -1
  248. package/src/ClientDevice/ios.ts +2 -2
  249. package/src/ClientDevice/reactnative.ts +1 -1
  250. package/src/Credentials.ts +19 -17
  251. package/src/Errors.ts +41 -0
  252. package/src/Hub.ts +1 -0
  253. package/src/I18n/I18n.ts +40 -12
  254. package/src/I18n/index.ts +45 -12
  255. package/src/I18n/types.ts +3 -0
  256. package/src/JS.ts +24 -17
  257. package/src/Logger/ConsoleLogger.ts +10 -10
  258. package/src/OAuthHelper/FacebookOAuth.ts +2 -2
  259. package/src/OAuthHelper/GoogleOAuth.ts +9 -6
  260. package/src/Platform/detectFramework.ts +1 -1
  261. package/src/Platform/detection/React.ts +5 -3
  262. package/src/Platform/version.ts +1 -1
  263. package/src/Providers/AWSCloudWatchProvider.ts +39 -14
  264. package/src/RNComponents/index.ts +1 -1
  265. package/src/RNComponents/reactnative.ts +1 -1
  266. package/src/ServiceWorker/ServiceWorker.ts +58 -18
  267. package/src/Signer.ts +22 -3
  268. package/src/StorageHelper/cookieStorage.ts +99 -0
  269. package/src/StorageHelper/inMemoryStorage.ts +32 -0
  270. package/src/StorageHelper/index.ts +6 -1
  271. package/src/StorageHelper/localStorage.ts +60 -0
  272. package/src/StorageHelper/reactnative.ts +94 -14
  273. package/src/StorageHelper/sessionStorage.ts +60 -0
  274. package/src/Util/BackgroundProcessManager.ts +33 -9
  275. package/src/Util/DateUtils.ts +14 -5
  276. package/src/Util/Reachability.native.ts +3 -2
  277. package/src/Util/Reachability.ts +9 -7
  278. package/src/Util/Retry.ts +2 -1
  279. package/src/Util/StringUtils.ts +3 -10
  280. package/src/Util/errors/AssertError.ts +11 -0
  281. package/src/clients/handlers/fetch.ts +2 -2
  282. package/src/clients/middleware/retry/defaultRetryDecider.ts +12 -6
  283. package/src/clients/middleware/retry/isClockSkewError.ts +1 -1
  284. package/src/clients/middleware/retry/middleware.ts +9 -9
  285. package/src/clients/middleware/signing/middleware.ts +1 -1
  286. package/src/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.ts +1 -1
  287. package/src/clients/serde/responseInfo.ts +2 -1
  288. package/src/clients/types/aws.ts +10 -0
  289. package/src/clients/types/index.ts +1 -0
  290. package/src/constants.ts +16 -0
  291. package/src/global.d.ts +11 -0
  292. package/src/index.ts +66 -4
  293. package/src/parseAWSExports.ts +1 -1
  294. package/src/singleton/Auth/index.ts +113 -0
  295. package/src/singleton/Auth/types.ts +129 -0
  296. package/src/singleton/Auth/utils/index.ts +68 -0
  297. package/src/singleton/Storage/types.ts +21 -0
  298. package/src/singleton/index.ts +144 -0
  299. package/src/singleton/types.ts +48 -0
  300. package/src/types/types.ts +38 -1
@@ -0,0 +1,517 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { ConsoleLogger as Logger } from '../Logger';
5
+ import { defaultConfig, getCurrTime } from './Utils';
6
+ import { StorageCache } from './StorageCache';
7
+ import { ICache, CacheConfig, CacheItem, CacheItemOptions } from './types';
8
+ import { asserts } from '../Util/errors/AssertError';
9
+ import { STORAGE_CACHE_EXCEPTION } from '../constants';
10
+ import { getCurrSizeKey } from './Utils/CacheUtils';
11
+
12
+ const logger = new Logger('Cache');
13
+
14
+ /**
15
+ * Customized storage based on the SessionStorage or LocalStorage with LRU implemented
16
+ */
17
+ export class BrowserStorageCacheClass extends StorageCache implements ICache {
18
+ /**
19
+ * initialize the cache
20
+ * @param config - the configuration of the cache
21
+ */
22
+ constructor(config?: CacheConfig) {
23
+ super(config);
24
+
25
+ asserts(!!this.cacheConfig.storage, {
26
+ name: STORAGE_CACHE_EXCEPTION,
27
+ message: 'Storage is not defined in the cache config',
28
+ });
29
+ this.cacheConfig.storage = this.cacheConfig.storage;
30
+ this.getItem = this.getItem.bind(this);
31
+ this.setItem = this.setItem.bind(this);
32
+ this.removeItem = this.removeItem.bind(this);
33
+ }
34
+ private getStorage(): Storage {
35
+ asserts(!!this.cacheConfig.storage, {
36
+ name: STORAGE_CACHE_EXCEPTION,
37
+ message: 'Storage is not defined in the cache config',
38
+ });
39
+ return this.cacheConfig.storage;
40
+ }
41
+ /**
42
+ * decrease current size of the cache
43
+ *
44
+ * @private
45
+ * @param amount - the amount of the cache size which needs to be decreased
46
+ */
47
+ private _decreaseCurSizeInBytes(amount: number): void {
48
+ const curSize: number = this.getCacheCurSize();
49
+ this.getStorage().setItem(
50
+ getCurrSizeKey(this.cacheConfig.keyPrefix),
51
+ (curSize - amount).toString()
52
+ );
53
+ }
54
+
55
+ /**
56
+ * increase current size of the cache
57
+ *
58
+ * @private
59
+ * @param amount - the amount of the cache szie which need to be increased
60
+ */
61
+ private _increaseCurSizeInBytes(amount: number): void {
62
+ const curSize: number = this.getCacheCurSize();
63
+ this.getStorage().setItem(
64
+ getCurrSizeKey(this.cacheConfig.keyPrefix),
65
+ (curSize + amount).toString()
66
+ );
67
+ }
68
+
69
+ /**
70
+ * update the visited time if item has been visited
71
+ *
72
+ * @private
73
+ * @param item - the item which need to be refreshed
74
+ * @param prefixedKey - the key of the item
75
+ *
76
+ * @return the refreshed item
77
+ */
78
+ private _refreshItem(item: CacheItem, prefixedKey: string): CacheItem {
79
+ item.visitedTime = getCurrTime();
80
+ this.getStorage().setItem(prefixedKey, JSON.stringify(item));
81
+ return item;
82
+ }
83
+
84
+ /**
85
+ * check wether item is expired
86
+ *
87
+ * @private
88
+ * @param key - the key of the item
89
+ *
90
+ * @return true if the item is expired.
91
+ */
92
+ private _isExpired(key: string): boolean {
93
+ const text: string | null = this.getStorage().getItem(key);
94
+ asserts(text !== null, {
95
+ name: STORAGE_CACHE_EXCEPTION,
96
+ message: `Item not found in the storage by the key: ${key}.`,
97
+ });
98
+ const item: CacheItem = JSON.parse(text);
99
+ if (getCurrTime() >= item.expires) {
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ /**
106
+ * delete item from cache
107
+ *
108
+ * @private
109
+ * @param prefixedKey - the key of the item
110
+ * @param size - optional, the byte size of the item
111
+ */
112
+ private _removeItem(prefixedKey: string, size?: number): void {
113
+ const item = this.getStorage().getItem(prefixedKey);
114
+ asserts(item !== null, {
115
+ name: STORAGE_CACHE_EXCEPTION,
116
+ message: `Item not found in the storage by the key: ${prefixedKey}.`,
117
+ });
118
+ const itemSize: number = size ?? JSON.parse(item).byteSize;
119
+ this._decreaseCurSizeInBytes(itemSize);
120
+ // remove the cache item
121
+ this.getStorage().removeItem(prefixedKey);
122
+ }
123
+
124
+ /**
125
+ * put item into cache
126
+ *
127
+ * @private
128
+ * @param prefixedKey - the key of the item
129
+ * @param itemData - the value of the item
130
+ * @param itemSizeInBytes - the byte size of the item
131
+ */
132
+ private _setItem(prefixedKey: string, item: CacheItem): void {
133
+ // update the cache size
134
+ this._increaseCurSizeInBytes(item.byteSize);
135
+
136
+ try {
137
+ this.getStorage().setItem(prefixedKey, JSON.stringify(item));
138
+ } catch (setItemErr) {
139
+ // if failed, we need to rollback the cache size
140
+ this._decreaseCurSizeInBytes(item.byteSize);
141
+ logger.error(`Failed to set item ${setItemErr}`);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * total space needed when poping out items
147
+ *
148
+ * @private
149
+ * @param itemSize
150
+ *
151
+ * @return total space needed
152
+ */
153
+ private _sizeToPop(itemSize: number): number {
154
+ const spaceItemNeed =
155
+ this.getCacheCurSize() + itemSize - this.cacheConfig.capacityInBytes;
156
+ const cacheThresholdSpace =
157
+ (1 - this.cacheConfig.warningThreshold) *
158
+ this.cacheConfig.capacityInBytes;
159
+ return spaceItemNeed > cacheThresholdSpace
160
+ ? spaceItemNeed
161
+ : cacheThresholdSpace;
162
+ }
163
+
164
+ /**
165
+ * see whether cache is full
166
+ *
167
+ * @private
168
+ * @param itemSize
169
+ *
170
+ * @return true if cache is full
171
+ */
172
+ private _isCacheFull(itemSize: number): boolean {
173
+ return itemSize + this.getCacheCurSize() > this.cacheConfig.capacityInBytes;
174
+ }
175
+
176
+ /**
177
+ * scan the storage and find out all the keys owned by this cache
178
+ * also clean the expired keys while scanning
179
+ *
180
+ * @private
181
+ *
182
+ * @return array of keys
183
+ */
184
+ private _findValidKeys(): string[] {
185
+ const keys: string[] = [];
186
+ const keyInCache: string[] = [];
187
+ // get all keys in Storage
188
+ for (let i = 0; i < this.getStorage().length; i += 1) {
189
+ const key = this.getStorage().key(i);
190
+ if (key) {
191
+ keyInCache.push(key);
192
+ }
193
+ }
194
+
195
+ // find those items which belong to our cache and also clean those expired items
196
+ for (let i = 0; i < keyInCache.length; i += 1) {
197
+ const key: string = keyInCache[i];
198
+ if (
199
+ key.indexOf(this.cacheConfig.keyPrefix) === 0 &&
200
+ key !== getCurrSizeKey(this.cacheConfig.keyPrefix)
201
+ ) {
202
+ if (this._isExpired(key)) {
203
+ this._removeItem(key);
204
+ } else {
205
+ keys.push(key);
206
+ }
207
+ }
208
+ }
209
+ return keys;
210
+ }
211
+
212
+ /**
213
+ * get all the items we have, sort them by their priority,
214
+ * if priority is same, sort them by their last visited time
215
+ * pop out items from the low priority (5 is the lowest)
216
+ *
217
+ * @private
218
+ * @param keys - all the keys in this cache
219
+ * @param sizeToPop - the total size of the items which needed to be poped out
220
+ */
221
+ private _popOutItems(keys: string[], sizeToPop: number): void {
222
+ const items: CacheItem[] = [];
223
+ let remainedSize: number = sizeToPop;
224
+ // get the items from Storage
225
+ for (let i = 0; i < keys.length; i += 1) {
226
+ const val: string | null = this.getStorage().getItem(keys[i]);
227
+ if (val != null) {
228
+ const item: CacheItem = JSON.parse(val);
229
+ items.push(item);
230
+ }
231
+ }
232
+
233
+ // first compare priority
234
+ // then compare visited time
235
+ items.sort((a, b) => {
236
+ if (a.priority > b.priority) {
237
+ return -1;
238
+ } else if (a.priority < b.priority) {
239
+ return 1;
240
+ } else {
241
+ if (a.visitedTime < b.visitedTime) {
242
+ return -1;
243
+ } else return 1;
244
+ }
245
+ });
246
+
247
+ for (let i = 0; i < items.length; i += 1) {
248
+ // pop out items until we have enough room for new item
249
+ this._removeItem(items[i].key, items[i].byteSize);
250
+ remainedSize -= items[i].byteSize;
251
+ if (remainedSize <= 0) {
252
+ return;
253
+ }
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Set item into cache. You can put number, string, boolean or object.
259
+ * The cache will first check whether has the same key.
260
+ * If it has, it will delete the old item and then put the new item in
261
+ * The cache will pop out items if it is full
262
+ * You can specify the cache item options. The cache will abort and output a warning:
263
+ * If the key is invalid
264
+ * If the size of the item exceeds itemMaxSize.
265
+ * If the value is undefined
266
+ * If incorrect cache item configuration
267
+ * If error happened with browser storage
268
+ *
269
+ * @param key - the key of the item
270
+ * @param value - the value of the item
271
+ * @param {Object} [options] - optional, the specified meta-data
272
+ */
273
+ public setItem(
274
+ key: string,
275
+ value: object | number | string | boolean,
276
+ options?: CacheItemOptions
277
+ ): void {
278
+ logger.log(
279
+ `Set item: key is ${key}, value is ${value} with options: ${options}`
280
+ );
281
+ const prefixedKey: string = this.cacheConfig.keyPrefix + key;
282
+ // invalid keys
283
+ if (
284
+ prefixedKey === this.cacheConfig.keyPrefix ||
285
+ prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)
286
+ ) {
287
+ logger.warn(`Invalid key: should not be empty or 'CurSize'`);
288
+ return;
289
+ }
290
+
291
+ if (typeof value === 'undefined') {
292
+ logger.warn(`The value of item should not be undefined!`);
293
+ return;
294
+ }
295
+
296
+ const cacheItemOptions = {
297
+ priority:
298
+ options && options.priority !== undefined
299
+ ? options.priority
300
+ : this.cacheConfig.defaultPriority,
301
+ expires:
302
+ options && options.expires !== undefined
303
+ ? options.expires
304
+ : this.cacheConfig.defaultTTL + getCurrTime(),
305
+ };
306
+
307
+ if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
308
+ logger.warn(
309
+ `Invalid parameter: priority due to out or range. It should be within 1 and 5.`
310
+ );
311
+ return;
312
+ }
313
+
314
+ const item: CacheItem = this.fillCacheItem(
315
+ prefixedKey,
316
+ value,
317
+ cacheItemOptions
318
+ );
319
+
320
+ // check wether this item is too big;
321
+ if (item.byteSize > this.cacheConfig.itemMaxSize) {
322
+ logger.warn(
323
+ `Item with key: ${key} you are trying to put into is too big!`
324
+ );
325
+ return;
326
+ }
327
+
328
+ try {
329
+ // first look into the storage, if it exists, delete it.
330
+ const val: string | null = this.getStorage().getItem(prefixedKey);
331
+ if (val) {
332
+ this._removeItem(prefixedKey, JSON.parse(val).byteSize);
333
+ }
334
+
335
+ // check whether the cache is full
336
+ if (this._isCacheFull(item.byteSize)) {
337
+ const validKeys: string[] = this._findValidKeys();
338
+ // check again and then pop out items
339
+ if (this._isCacheFull(item.byteSize)) {
340
+ const sizeToPop: number = this._sizeToPop(item.byteSize);
341
+ this._popOutItems(validKeys, sizeToPop);
342
+ }
343
+ }
344
+
345
+ // put item in the cache
346
+ // may failed due to storage full
347
+ this._setItem(prefixedKey, item);
348
+ } catch (e) {
349
+ logger.warn(`setItem failed! ${e}`);
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Get item from cache. It will return null if item doesn’t exist or it has been expired.
355
+ * If you specified callback function in the options,
356
+ * then the function will be executed if no such item in the cache
357
+ * and finally put the return value into cache.
358
+ * Please make sure the callback function will return the value you want to put into the cache.
359
+ * The cache will abort output a warning:
360
+ * If the key is invalid
361
+ * If error happened with browser storage
362
+ *
363
+ * @param key - the key of the item
364
+ * @param {Object} [options] - the options of callback function
365
+ *
366
+ * @return - return the value of the item
367
+ */
368
+ public getItem(key: string, options?: CacheItemOptions): any {
369
+ logger.log(`Get item: key is ${key} with options ${options}`);
370
+ let ret: string | null = null;
371
+ const prefixedKey: string = this.cacheConfig.keyPrefix + key;
372
+
373
+ if (
374
+ prefixedKey === this.cacheConfig.keyPrefix ||
375
+ prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)
376
+ ) {
377
+ logger.warn(`Invalid key: should not be empty or 'CurSize'`);
378
+ return null;
379
+ }
380
+
381
+ try {
382
+ ret = this.getStorage().getItem(prefixedKey);
383
+ if (ret != null) {
384
+ if (this._isExpired(prefixedKey)) {
385
+ // if expired, remove that item and return null
386
+ this._removeItem(prefixedKey, JSON.parse(ret).byteSize);
387
+ ret = null;
388
+ } else {
389
+ // if not expired, great, return the value and refresh it
390
+ let item: CacheItem = JSON.parse(ret);
391
+ item = this._refreshItem(item, prefixedKey);
392
+ return item.data;
393
+ }
394
+ }
395
+
396
+ if (options && options.callback !== undefined) {
397
+ const val: object | string | number | boolean = options.callback();
398
+ if (val !== null) {
399
+ this.setItem(key, val, options);
400
+ }
401
+ return val;
402
+ }
403
+ return null;
404
+ } catch (e) {
405
+ logger.warn(`getItem failed! ${e}`);
406
+ return null;
407
+ }
408
+ }
409
+
410
+ /**
411
+ * remove item from the cache
412
+ * The cache will abort output a warning:
413
+ * If error happened with browser storage
414
+ * @param key - the key of the item
415
+ */
416
+ public removeItem(key: string): void {
417
+ logger.log(`Remove item: key is ${key}`);
418
+ const prefixedKey: string = this.cacheConfig.keyPrefix + key;
419
+
420
+ if (
421
+ prefixedKey === this.cacheConfig.keyPrefix ||
422
+ prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)
423
+ ) {
424
+ return;
425
+ }
426
+
427
+ try {
428
+ const val: string | null = this.getStorage().getItem(prefixedKey);
429
+ if (val) {
430
+ this._removeItem(prefixedKey, JSON.parse(val).byteSize);
431
+ }
432
+ } catch (e) {
433
+ logger.warn(`removeItem failed! ${e}`);
434
+ }
435
+ }
436
+
437
+ /**
438
+ * clear the entire cache
439
+ * The cache will abort output a warning:
440
+ * If error happened with browser storage
441
+ */
442
+ public clear(): void {
443
+ logger.log(`Clear Cache`);
444
+ const keysToRemove: string[] = [];
445
+
446
+ for (let i = 0; i < this.getStorage().length; i += 1) {
447
+ const key = this.getStorage().key(i);
448
+ if (key?.indexOf(this.cacheConfig.keyPrefix) === 0) {
449
+ keysToRemove.push(key);
450
+ }
451
+ }
452
+
453
+ try {
454
+ for (let i = 0; i < keysToRemove.length; i += 1) {
455
+ this.getStorage().removeItem(keysToRemove[i]);
456
+ }
457
+ } catch (e) {
458
+ logger.warn(`clear failed! ${e}`);
459
+ }
460
+ }
461
+
462
+ /**
463
+ * Return all the keys in the cache.
464
+ *
465
+ * @return - all keys in the cache
466
+ */
467
+ public getAllKeys(): string[] {
468
+ const keys: string[] = [];
469
+ for (let i = 0; i < this.getStorage().length; i += 1) {
470
+ const key = this.getStorage().key(i);
471
+ if (
472
+ key &&
473
+ key.indexOf(this.cacheConfig.keyPrefix) === 0 &&
474
+ key !== getCurrSizeKey(this.cacheConfig.keyPrefix)
475
+ ) {
476
+ keys.push(key.substring(this.cacheConfig.keyPrefix.length));
477
+ }
478
+ }
479
+ return keys;
480
+ }
481
+
482
+ /**
483
+ * return the current size of the cache
484
+ *
485
+ * @return - current size of the cache
486
+ */
487
+ public getCacheCurSize(): number {
488
+ let ret: string | null = this.getStorage().getItem(
489
+ getCurrSizeKey(this.cacheConfig.keyPrefix)
490
+ );
491
+ if (!ret) {
492
+ this.getStorage().setItem(
493
+ getCurrSizeKey(this.cacheConfig.keyPrefix),
494
+ '0'
495
+ );
496
+ ret = '0';
497
+ }
498
+ return Number(ret);
499
+ }
500
+
501
+ /**
502
+ * Return a new instance of cache with customized configuration.
503
+ * @param config - the customized configuration
504
+ *
505
+ * @return - new instance of Cache
506
+ */
507
+ public createInstance(config: CacheConfig): ICache {
508
+ if (!config.keyPrefix || config.keyPrefix === defaultConfig.keyPrefix) {
509
+ logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
510
+ config.keyPrefix = getCurrTime.toString();
511
+ }
512
+
513
+ return new BrowserStorageCacheClass(config);
514
+ }
515
+ }
516
+
517
+ export const BrowserStorageCache: ICache = new BrowserStorageCacheClass();