@aws-amplify/core 6.0.1-api-v6-models.9351bcf.0 → 6.0.1-api-v6-models.58f2536.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 (360) hide show
  1. package/lib/BackgroundProcessManager/BackgroundManagerNotOpenError.js +4 -21
  2. package/lib/BackgroundProcessManager/BackgroundProcessManager.js +126 -245
  3. package/lib/Cache/StorageCache.js +32 -92
  4. package/lib/Cache/StorageCache.native.js +38 -140
  5. package/lib/Cache/StorageCacheCommon.js +271 -600
  6. package/lib/Cache/index.js +1 -1
  7. package/lib/Cache/utils/CacheList.js +42 -66
  8. package/lib/Cache/utils/cacheHelpers.js +6 -8
  9. package/lib/Cache/utils/errorHelpers.js +6 -7
  10. package/lib/Hub/index.js +34 -74
  11. package/lib/I18n/I18n.js +24 -39
  12. package/lib/I18n/errorHelpers.js +4 -5
  13. package/lib/I18n/index.js +24 -27
  14. package/lib/I18n/types.js +3 -4
  15. package/lib/Logger/ConsoleLogger.js +53 -129
  16. package/lib/Mutex/Mutex.js +15 -19
  17. package/lib/Platform/customUserAgent.js +13 -26
  18. package/lib/Platform/detectFramework.js +12 -13
  19. package/lib/Platform/detection/Angular.js +4 -5
  20. package/lib/Platform/detection/Expo.js +1 -1
  21. package/lib/Platform/detection/Next.js +1 -1
  22. package/lib/Platform/detection/Nuxt.js +1 -1
  23. package/lib/Platform/detection/React.js +5 -5
  24. package/lib/Platform/detection/Svelte.js +2 -2
  25. package/lib/Platform/detection/Vue.js +1 -1
  26. package/lib/Platform/detection/Web.js +1 -1
  27. package/lib/Platform/detection/helpers.js +7 -7
  28. package/lib/Platform/detection/index.js +13 -13
  29. package/lib/Platform/index.js +26 -55
  30. package/lib/Platform/types.d.ts +1 -1
  31. package/lib/Platform/types.js +1 -1
  32. package/lib/Platform/version.d.ts +1 -1
  33. package/lib/Platform/version.js +1 -1
  34. package/lib/Reachability/Reachability.js +20 -48
  35. package/lib/Reachability/Reachability.native.js +12 -16
  36. package/lib/ServiceWorker/ServiceWorker.js +80 -136
  37. package/lib/ServiceWorker/errorHelpers.js +6 -7
  38. package/lib/Signer/DateUtils.d.ts +9 -0
  39. package/lib/Signer/DateUtils.js +19 -28
  40. package/lib/Signer/Signer.d.ts +9 -0
  41. package/lib/Signer/Signer.js +58 -54
  42. package/lib/adapterCore/error/AmplifyServerContextError.js +9 -27
  43. package/lib/adapterCore/serverContext/serverContext.js +8 -8
  44. package/lib/adapterCore/serverContext/serverContextRegistry.js +6 -6
  45. package/lib/awsClients/cognitoIdentity/base.js +25 -73
  46. package/lib/awsClients/cognitoIdentity/getCredentialsForIdentity.js +24 -68
  47. package/lib/awsClients/cognitoIdentity/getId.js +19 -62
  48. package/lib/awsClients/pinpoint/base.js +12 -15
  49. package/lib/awsClients/pinpoint/errorHelpers.js +4 -5
  50. package/lib/awsClients/pinpoint/getInAppMessages.js +24 -68
  51. package/lib/awsClients/pinpoint/putEvents.js +26 -70
  52. package/lib/awsClients/pinpoint/updateEndpoint.js +28 -72
  53. package/lib/clients/endpoints/getDnsSuffix.js +7 -29
  54. package/lib/clients/handlers/authenticated.js +5 -5
  55. package/lib/clients/handlers/fetch.js +41 -98
  56. package/lib/clients/handlers/unauthenticated.js +4 -4
  57. package/lib/clients/internal/composeServiceApi.js +17 -67
  58. package/lib/clients/internal/composeTransferHandler.js +9 -11
  59. package/lib/clients/middleware/retry/defaultRetryDecider.js +18 -75
  60. package/lib/clients/middleware/retry/isClockSkewError.js +2 -4
  61. package/lib/clients/middleware/retry/jitteredBackoff.js +5 -5
  62. package/lib/clients/middleware/retry/middleware.js +61 -125
  63. package/lib/clients/middleware/signing/middleware.js +24 -86
  64. package/lib/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  65. package/lib/clients/middleware/signing/signer/signatureV4/presignUrl.js +21 -56
  66. package/lib/clients/middleware/signing/signer/signatureV4/signRequest.js +14 -25
  67. package/lib/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +7 -7
  68. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.js +8 -30
  69. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.js +11 -38
  70. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.js +13 -17
  71. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.js +5 -8
  72. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.js +2 -2
  73. package/lib/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.js +3 -3
  74. package/lib/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.js +7 -11
  75. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSignature.js +9 -10
  76. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.js +4 -6
  77. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.js +8 -8
  78. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.js +15 -16
  79. package/lib/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.js +2 -4
  80. package/lib/clients/middleware/signing/utils/extendedEncodeURIComponent.js +3 -5
  81. package/lib/clients/middleware/signing/utils/getSkewCorrectedDate.js +1 -3
  82. package/lib/clients/middleware/signing/utils/getUpdatedSystemClockOffset.js +2 -2
  83. package/lib/clients/middleware/signing/utils/isClockSkewed.js +4 -6
  84. package/lib/clients/middleware/userAgent/middleware.js +14 -63
  85. package/lib/clients/serde/json.js +30 -96
  86. package/lib/clients/serde/responseInfo.js +12 -18
  87. package/lib/clients/utils/memoization.js +3 -3
  88. package/lib/constants.js +1 -1
  89. package/lib/errors/AmplifyError.js +9 -28
  90. package/lib/errors/PlatformNotSupportedError.js +7 -24
  91. package/lib/errors/createAssertionFunction.js +12 -15
  92. package/lib/errors/errorHelpers.js +7 -8
  93. package/lib/index.d.ts +1 -1
  94. package/lib/libraryUtils.d.ts +4 -0
  95. package/lib/libraryUtils.js +13 -3
  96. package/lib/parseAWSExports.js +109 -100
  97. package/lib/providers/kinesis/types/kinesis.d.ts +1 -1
  98. package/lib/providers/kinesis-firehose/types/kinesis-firehose.d.ts +1 -1
  99. package/lib/providers/personalize/types/personalize.d.ts +1 -1
  100. package/lib/providers/pinpoint/apis/flushEvents.js +8 -8
  101. package/lib/providers/pinpoint/apis/record.js +58 -93
  102. package/lib/providers/pinpoint/apis/updateEndpoint.js +65 -112
  103. package/lib/providers/pinpoint/types/pinpoint.d.ts +3 -1
  104. package/lib/providers/pinpoint/utils/PinpointEventBuffer.js +105 -196
  105. package/lib/providers/pinpoint/utils/cacheEndpointId.js +12 -49
  106. package/lib/providers/pinpoint/utils/getCacheKey.js +2 -2
  107. package/lib/providers/pinpoint/utils/getEndpointId.js +7 -51
  108. package/lib/providers/pinpoint/utils/getEventBuffer.js +19 -21
  109. package/lib/providers/pinpoint/utils/isAppInForeground.js +1 -1
  110. package/lib/providers/pinpoint/utils/isAppInForeground.native.js +2 -2
  111. package/lib/providers/pinpoint/utils/resolveEndpointId.js +20 -71
  112. package/lib/singleton/Amplify.d.ts +4 -0
  113. package/lib/singleton/Amplify.js +21 -103
  114. package/lib/singleton/Analytics/types.d.ts +5 -1
  115. package/lib/singleton/Auth/index.js +48 -115
  116. package/lib/singleton/Auth/types.d.ts +2 -2
  117. package/lib/singleton/Auth/utils/errorHelpers.js +7 -8
  118. package/lib/singleton/Auth/utils/index.js +18 -19
  119. package/lib/singleton/Predictions/types.d.ts +49 -0
  120. package/lib/singleton/Predictions/types.js +4 -0
  121. package/lib/singleton/apis/clearCredentials.js +1 -1
  122. package/lib/singleton/apis/fetchAuthSession.js +3 -3
  123. package/lib/singleton/apis/internal/fetchAuthSession.js +1 -1
  124. package/lib/singleton/apis/server/fetchAuthSession.js +3 -3
  125. package/lib/singleton/types.d.ts +3 -1
  126. package/lib/storage/CookieStorage.js +29 -99
  127. package/lib/storage/CookieStorage.native.js +5 -22
  128. package/lib/storage/DefaultStorage.js +6 -23
  129. package/lib/storage/DefaultStorage.native.js +18 -64
  130. package/lib/storage/InMemoryStorage.js +17 -23
  131. package/lib/storage/KeyValueStorage.js +24 -80
  132. package/lib/storage/SessionStorage.js +6 -23
  133. package/lib/storage/index.js +4 -4
  134. package/lib/storage/utils.js +7 -11
  135. package/lib/tsconfig.tsbuildinfo +1 -1
  136. package/lib/utils/WordArray.d.ts +7 -0
  137. package/lib/utils/WordArray.js +49 -0
  138. package/lib/utils/amplifyUrl/index.js +2 -2
  139. package/lib/utils/amplifyUrl/polyfill.native.js +1 -1
  140. package/lib/utils/amplifyUuid/index.d.ts +1 -1
  141. package/lib/utils/amplifyUuid/index.js +2 -2
  142. package/lib/utils/amplifyUuid/polyfill.native.js +1 -1
  143. package/lib/utils/convert/base64/base64Decoder.js +2 -2
  144. package/lib/utils/convert/base64/base64Encoder.js +5 -6
  145. package/lib/utils/convert/base64/bytesToString.js +1 -1
  146. package/lib/utils/cryptoSecureRandomInt.d.ts +1 -0
  147. package/lib/utils/cryptoSecureRandomInt.js +16 -0
  148. package/lib/utils/deepFreeze.js +6 -28
  149. package/lib/utils/generateRandomString.js +4 -4
  150. package/lib/utils/getClientInfo/getClientInfo.android.js +7 -7
  151. package/lib/utils/getClientInfo/getClientInfo.ios.js +12 -12
  152. package/lib/utils/getClientInfo/getClientInfo.js +16 -16
  153. package/lib/utils/globalHelpers/index.js +4 -4
  154. package/lib/utils/globalHelpers/index.native.js +6 -6
  155. package/lib/utils/isBrowser.js +1 -3
  156. package/lib/utils/isWebWorker.js +2 -2
  157. package/lib/utils/retry/NonRetryableError.js +5 -23
  158. package/lib/utils/retry/isNonRetryableError.js +2 -2
  159. package/lib/utils/retry/jitteredBackoff.js +6 -7
  160. package/lib/utils/retry/jitteredExponentialRetry.js +4 -7
  161. package/lib/utils/retry/retry.js +50 -140
  162. package/lib/utils/sessionListener/SessionListener.js +17 -19
  163. package/lib/utils/sessionListener/SessionListener.native.js +18 -22
  164. package/lib/utils/sessionListener/constants.d.ts +2 -0
  165. package/lib/utils/sessionListener/constants.js +8 -0
  166. package/lib/utils/sessionListener/index.d.ts +1 -0
  167. package/lib/utils/sessionListener/index.js +5 -2
  168. package/lib/utils/urlSafeDecode.js +2 -2
  169. package/lib/utils/urlSafeEncode.js +1 -1
  170. package/lib-esm/BackgroundProcessManager/BackgroundManagerNotOpenError.js +4 -22
  171. package/lib-esm/BackgroundProcessManager/BackgroundProcessManager.js +124 -244
  172. package/lib-esm/Cache/StorageCache.js +26 -87
  173. package/lib-esm/Cache/StorageCache.native.js +33 -136
  174. package/lib-esm/Cache/StorageCacheCommon.js +267 -597
  175. package/lib-esm/Cache/constants.js +2 -2
  176. package/lib-esm/Cache/index.js +1 -1
  177. package/lib-esm/Cache/utils/CacheList.js +41 -66
  178. package/lib-esm/Cache/utils/cacheHelpers.js +5 -7
  179. package/lib-esm/Cache/utils/errorHelpers.js +6 -7
  180. package/lib-esm/Hub/index.js +34 -75
  181. package/lib-esm/I18n/I18n.js +23 -39
  182. package/lib-esm/I18n/errorHelpers.js +4 -5
  183. package/lib-esm/I18n/index.js +21 -25
  184. package/lib-esm/I18n/types.js +3 -5
  185. package/lib-esm/Logger/ConsoleLogger.js +52 -128
  186. package/lib-esm/Mutex/Mutex.js +15 -20
  187. package/lib-esm/Platform/customUserAgent.js +13 -26
  188. package/lib-esm/Platform/detectFramework.js +11 -12
  189. package/lib-esm/Platform/detection/Angular.js +3 -4
  190. package/lib-esm/Platform/detection/React.js +4 -4
  191. package/lib-esm/Platform/detection/Svelte.js +1 -1
  192. package/lib-esm/Platform/detection/helpers.js +7 -7
  193. package/lib-esm/Platform/detection/index.js +3 -3
  194. package/lib-esm/Platform/index.js +23 -52
  195. package/lib-esm/Platform/types.d.ts +1 -1
  196. package/lib-esm/Platform/types.js +1 -1
  197. package/lib-esm/Platform/version.d.ts +1 -1
  198. package/lib-esm/Platform/version.js +1 -1
  199. package/lib-esm/Reachability/Reachability.js +18 -46
  200. package/lib-esm/Reachability/Reachability.native.js +10 -15
  201. package/lib-esm/ServiceWorker/ServiceWorker.js +74 -131
  202. package/lib-esm/ServiceWorker/errorHelpers.js +6 -7
  203. package/lib-esm/Signer/DateUtils.d.ts +9 -0
  204. package/lib-esm/Signer/DateUtils.js +20 -29
  205. package/lib-esm/Signer/Signer.d.ts +9 -0
  206. package/lib-esm/Signer/Signer.js +54 -51
  207. package/lib-esm/adapterCore/error/AmplifyServerContextError.js +8 -27
  208. package/lib-esm/adapterCore/serverContext/serverContext.js +6 -6
  209. package/lib-esm/adapterCore/serverContext/serverContextRegistry.js +7 -7
  210. package/lib-esm/awsClients/cognitoIdentity/base.js +21 -69
  211. package/lib-esm/awsClients/cognitoIdentity/getCredentialsForIdentity.js +22 -66
  212. package/lib-esm/awsClients/cognitoIdentity/getId.js +17 -60
  213. package/lib-esm/awsClients/pinpoint/base.js +8 -11
  214. package/lib-esm/awsClients/pinpoint/errorHelpers.js +4 -5
  215. package/lib-esm/awsClients/pinpoint/getInAppMessages.js +19 -63
  216. package/lib-esm/awsClients/pinpoint/putEvents.js +20 -64
  217. package/lib-esm/awsClients/pinpoint/updateEndpoint.js +23 -67
  218. package/lib-esm/clients/endpoints/getDnsSuffix.js +6 -28
  219. package/lib-esm/clients/endpoints/partitions.js +2 -2
  220. package/lib-esm/clients/handlers/authenticated.js +1 -1
  221. package/lib-esm/clients/handlers/fetch.js +40 -97
  222. package/lib-esm/clients/handlers/unauthenticated.js +1 -1
  223. package/lib-esm/clients/internal/composeServiceApi.js +17 -67
  224. package/lib-esm/clients/internal/composeTransferHandler.js +9 -11
  225. package/lib-esm/clients/middleware/retry/defaultRetryDecider.js +17 -74
  226. package/lib-esm/clients/middleware/retry/isClockSkewError.js +2 -4
  227. package/lib-esm/clients/middleware/retry/jitteredBackoff.js +4 -4
  228. package/lib-esm/clients/middleware/retry/middleware.js +61 -125
  229. package/lib-esm/clients/middleware/signing/middleware.js +21 -83
  230. package/lib-esm/clients/middleware/signing/signer/signatureV4/constants.js +17 -17
  231. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  232. package/lib-esm/clients/middleware/signing/signer/signatureV4/presignUrl.js +17 -52
  233. package/lib-esm/clients/middleware/signing/signer/signatureV4/signRequest.js +10 -21
  234. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +5 -5
  235. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.js +8 -30
  236. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.js +11 -38
  237. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.js +8 -12
  238. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.js +5 -8
  239. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.js +1 -1
  240. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.js +3 -3
  241. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.js +5 -9
  242. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSignature.js +5 -6
  243. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.js +4 -6
  244. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.js +6 -6
  245. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.js +13 -14
  246. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.js +1 -3
  247. package/lib-esm/clients/middleware/signing/utils/extendedEncodeURIComponent.js +3 -5
  248. package/lib-esm/clients/middleware/signing/utils/getSkewCorrectedDate.js +1 -3
  249. package/lib-esm/clients/middleware/signing/utils/getUpdatedSystemClockOffset.js +1 -1
  250. package/lib-esm/clients/middleware/signing/utils/isClockSkewed.js +3 -5
  251. package/lib-esm/clients/middleware/userAgent/middleware.js +14 -63
  252. package/lib-esm/clients/serde/json.js +29 -95
  253. package/lib-esm/clients/serde/responseInfo.js +11 -17
  254. package/lib-esm/clients/utils/memoization.js +3 -3
  255. package/lib-esm/constants.js +5 -5
  256. package/lib-esm/errors/AmplifyError.js +9 -29
  257. package/lib-esm/errors/PlatformNotSupportedError.js +5 -23
  258. package/lib-esm/errors/createAssertionFunction.js +11 -14
  259. package/lib-esm/errors/errorHelpers.js +6 -7
  260. package/lib-esm/index.d.ts +1 -1
  261. package/lib-esm/libraryUtils.d.ts +4 -0
  262. package/lib-esm/libraryUtils.js +4 -0
  263. package/lib-esm/parseAWSExports.js +108 -99
  264. package/lib-esm/providers/kinesis/types/kinesis.d.ts +1 -1
  265. package/lib-esm/providers/kinesis-firehose/types/kinesis-firehose.d.ts +1 -1
  266. package/lib-esm/providers/personalize/types/personalize.d.ts +1 -1
  267. package/lib-esm/providers/pinpoint/apis/flushEvents.js +6 -6
  268. package/lib-esm/providers/pinpoint/apis/record.js +54 -89
  269. package/lib-esm/providers/pinpoint/apis/updateEndpoint.js +61 -108
  270. package/lib-esm/providers/pinpoint/types/pinpoint.d.ts +3 -1
  271. package/lib-esm/providers/pinpoint/utils/PinpointEventBuffer.js +102 -194
  272. package/lib-esm/providers/pinpoint/utils/cacheEndpointId.js +10 -47
  273. package/lib-esm/providers/pinpoint/utils/constants.js +4 -4
  274. package/lib-esm/providers/pinpoint/utils/getCacheKey.js +2 -2
  275. package/lib-esm/providers/pinpoint/utils/getEndpointId.js +5 -49
  276. package/lib-esm/providers/pinpoint/utils/getEventBuffer.js +17 -19
  277. package/lib-esm/providers/pinpoint/utils/isAppInForeground.js +1 -1
  278. package/lib-esm/providers/pinpoint/utils/isAppInForeground.native.js +1 -1
  279. package/lib-esm/providers/pinpoint/utils/resolveEndpointId.js +16 -67
  280. package/lib-esm/singleton/Amplify.d.ts +4 -0
  281. package/lib-esm/singleton/Amplify.js +18 -101
  282. package/lib-esm/singleton/Analytics/types.d.ts +5 -1
  283. package/lib-esm/singleton/Auth/index.js +48 -116
  284. package/lib-esm/singleton/Auth/types.d.ts +2 -2
  285. package/lib-esm/singleton/Auth/utils/errorHelpers.js +7 -8
  286. package/lib-esm/singleton/Auth/utils/index.js +16 -17
  287. package/lib-esm/singleton/Predictions/types.d.ts +49 -0
  288. package/lib-esm/singleton/Predictions/types.js +3 -0
  289. package/lib-esm/singleton/apis/fetchAuthSession.js +1 -1
  290. package/lib-esm/singleton/apis/internal/fetchAuthSession.js +1 -1
  291. package/lib-esm/singleton/apis/server/fetchAuthSession.js +1 -1
  292. package/lib-esm/singleton/types.d.ts +3 -1
  293. package/lib-esm/storage/CookieStorage.js +28 -99
  294. package/lib-esm/storage/CookieStorage.native.js +4 -22
  295. package/lib-esm/storage/DefaultStorage.js +4 -22
  296. package/lib-esm/storage/DefaultStorage.native.js +17 -64
  297. package/lib-esm/storage/InMemoryStorage.js +17 -24
  298. package/lib-esm/storage/KeyValueStorage.js +23 -80
  299. package/lib-esm/storage/SessionStorage.js +4 -22
  300. package/lib-esm/storage/index.js +3 -3
  301. package/lib-esm/storage/utils.js +6 -10
  302. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  303. package/lib-esm/utils/WordArray.d.ts +7 -0
  304. package/lib-esm/utils/WordArray.js +46 -0
  305. package/lib-esm/utils/amplifyUrl/index.js +2 -2
  306. package/lib-esm/utils/amplifyUuid/index.d.ts +1 -1
  307. package/lib-esm/utils/amplifyUuid/index.js +1 -1
  308. package/lib-esm/utils/convert/base64/base64Decoder.js +2 -2
  309. package/lib-esm/utils/convert/base64/base64Encoder.js +4 -5
  310. package/lib-esm/utils/convert/base64/bytesToString.js +1 -1
  311. package/lib-esm/utils/cryptoSecureRandomInt.d.ts +1 -0
  312. package/lib-esm/utils/cryptoSecureRandomInt.js +12 -0
  313. package/lib-esm/utils/deepFreeze.js +6 -28
  314. package/lib-esm/utils/generateRandomString.js +4 -4
  315. package/lib-esm/utils/getClientInfo/getClientInfo.android.js +5 -5
  316. package/lib-esm/utils/getClientInfo/getClientInfo.ios.js +10 -10
  317. package/lib-esm/utils/getClientInfo/getClientInfo.js +15 -15
  318. package/lib-esm/utils/globalHelpers/index.js +3 -3
  319. package/lib-esm/utils/globalHelpers/index.native.js +4 -4
  320. package/lib-esm/utils/isBrowser.js +1 -3
  321. package/lib-esm/utils/isWebWorker.js +2 -2
  322. package/lib-esm/utils/retry/NonRetryableError.js +5 -24
  323. package/lib-esm/utils/retry/constants.js +1 -1
  324. package/lib-esm/utils/retry/isNonRetryableError.js +2 -2
  325. package/lib-esm/utils/retry/jitteredBackoff.js +5 -6
  326. package/lib-esm/utils/retry/jitteredExponentialRetry.js +1 -4
  327. package/lib-esm/utils/retry/retry.js +48 -138
  328. package/lib-esm/utils/sessionListener/SessionListener.js +16 -19
  329. package/lib-esm/utils/sessionListener/SessionListener.native.js +17 -22
  330. package/lib-esm/utils/sessionListener/constants.d.ts +2 -0
  331. package/lib-esm/utils/sessionListener/constants.js +5 -0
  332. package/lib-esm/utils/sessionListener/index.d.ts +1 -0
  333. package/lib-esm/utils/sessionListener/index.js +2 -1
  334. package/lib-esm/utils/urlSafeDecode.js +2 -2
  335. package/lib-esm/utils/urlSafeEncode.js +1 -1
  336. package/package.json +11 -24
  337. package/src/Cache/types/index.ts +4 -4
  338. package/src/Platform/types.ts +1 -1
  339. package/src/Platform/version.ts +1 -1
  340. package/src/Signer/DateUtils.ts +10 -2
  341. package/src/Signer/Signer.ts +9 -2
  342. package/src/clients/middleware/signing/signer/signatureV4/index.ts +0 -1
  343. package/src/index.ts +1 -0
  344. package/src/libraryUtils.ts +7 -1
  345. package/src/parseAWSExports.ts +45 -6
  346. package/src/providers/kinesis/types/kinesis.ts +1 -1
  347. package/src/providers/kinesis-firehose/types/kinesis-firehose.ts +1 -1
  348. package/src/providers/personalize/types/personalize.ts +1 -1
  349. package/src/providers/pinpoint/apis/record.ts +22 -5
  350. package/src/providers/pinpoint/types/pinpoint.ts +3 -1
  351. package/src/singleton/Amplify.ts +9 -52
  352. package/src/singleton/Analytics/types.ts +9 -4
  353. package/src/singleton/Auth/types.ts +2 -2
  354. package/src/singleton/Predictions/types.ts +61 -0
  355. package/src/singleton/types.ts +3 -1
  356. package/src/utils/WordArray.ts +57 -0
  357. package/src/utils/amplifyUuid/index.ts +1 -1
  358. package/src/utils/cryptoSecureRandomInt.ts +14 -0
  359. package/src/utils/sessionListener/constants.ts +6 -0
  360. package/src/utils/sessionListener/index.ts +1 -0
@@ -1,87 +1,31 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- var __assign = (this && this.__assign) || function () {
4
- __assign = Object.assign || function(t) {
5
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6
- s = arguments[i];
7
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
- t[p] = s[p];
9
- }
10
- return t;
11
- };
12
- return __assign.apply(this, arguments);
13
- };
14
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
- return new (P || (P = Promise))(function (resolve, reject) {
17
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
- step((generator = generator.apply(thisArg, _arguments || [])).next());
21
- });
22
- };
23
- var __generator = (this && this.__generator) || function (thisArg, body) {
24
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
25
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
26
- function verb(n) { return function (v) { return step([n, v]); }; }
27
- function step(op) {
28
- if (f) throw new TypeError("Generator is already executing.");
29
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
30
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
31
- if (y = 0, t) op = [op[0] & 2, t.value];
32
- switch (op[0]) {
33
- case 0: case 1: t = op; break;
34
- case 4: _.label++; return { value: op[1], done: false };
35
- case 5: _.label++; y = op[1]; op = [0]; continue;
36
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
37
- default:
38
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
39
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
40
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
41
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
42
- if (t[2]) _.ops.pop();
43
- _.trys.pop(); continue;
44
- }
45
- op = body.call(thisArg, _);
46
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
47
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
48
- }
49
- };
50
- var __values = (this && this.__values) || function(o) {
51
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
52
- if (m) return m.call(o);
53
- if (o && typeof o.length === "number") return {
54
- next: function () {
55
- if (o && i >= o.length) o = void 0;
56
- return { value: o && o[i++], done: !o };
57
- }
58
- };
59
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
60
- };
61
3
  import { ConsoleLogger as Logger } from '../Logger';
62
4
  import { currentSizeKey, defaultConfig } from './constants';
63
5
  import { getCurrentSizeKey, getCurrentTime, getByteLength } from './utils';
64
6
  import { assert, CacheErrorCode } from './utils/errorHelpers';
65
- var logger = new Logger('StorageCache');
7
+ const logger = new Logger('StorageCache');
66
8
  /**
67
9
  * Initialization of the cache
68
10
  *
69
11
  */
70
- var StorageCacheCommon = /** @class */ (function () {
12
+ export class StorageCacheCommon {
71
13
  /**
72
14
  * Initialize the cache
73
15
  *
74
16
  * @param config - Custom configuration for this instance.
75
17
  */
76
- function StorageCacheCommon(_a) {
77
- var config = _a.config, keyValueStorage = _a.keyValueStorage;
78
- this.config = __assign(__assign({}, defaultConfig), config);
18
+ constructor({ config, keyValueStorage, }) {
19
+ this.config = {
20
+ ...defaultConfig,
21
+ ...config,
22
+ };
79
23
  this.keyValueStorage = keyValueStorage;
80
24
  this.sanitizeConfig();
81
25
  }
82
- StorageCacheCommon.prototype.getModuleName = function () {
26
+ getModuleName() {
83
27
  return 'Cache';
84
- };
28
+ }
85
29
  /**
86
30
  * Set custom configuration for the cache instance.
87
31
  *
@@ -89,39 +33,31 @@ var StorageCacheCommon = /** @class */ (function () {
89
33
  *
90
34
  * @return - the current configuration
91
35
  */
92
- StorageCacheCommon.prototype.configure = function (config) {
36
+ configure(config) {
93
37
  if (config) {
94
38
  if (config.keyPrefix) {
95
39
  logger.warn('keyPrefix can not be re-configured on an existing Cache instance.');
96
40
  }
97
- this.config = __assign(__assign({}, this.config), config);
41
+ this.config = {
42
+ ...this.config,
43
+ ...config,
44
+ };
98
45
  }
99
46
  this.sanitizeConfig();
100
47
  return this.config;
101
- };
48
+ }
102
49
  /**
103
50
  * return the current size of the cache
104
51
  * @return {Promise}
105
52
  */
106
- StorageCacheCommon.prototype.getCurrentCacheSize = function () {
107
- return __awaiter(this, void 0, void 0, function () {
108
- var size;
109
- return __generator(this, function (_a) {
110
- switch (_a.label) {
111
- case 0: return [4 /*yield*/, this.getStorage().getItem(getCurrentSizeKey(this.config.keyPrefix))];
112
- case 1:
113
- size = _a.sent();
114
- if (!!size) return [3 /*break*/, 3];
115
- return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), '0')];
116
- case 2:
117
- _a.sent();
118
- size = '0';
119
- _a.label = 3;
120
- case 3: return [2 /*return*/, Number(size)];
121
- }
122
- });
123
- });
124
- };
53
+ async getCurrentCacheSize() {
54
+ let size = await this.getStorage().getItem(getCurrentSizeKey(this.config.keyPrefix));
55
+ if (!size) {
56
+ await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), '0');
57
+ size = '0';
58
+ }
59
+ return Number(size);
60
+ }
125
61
  /**
126
62
  * Set item into cache. You can put number, string, boolean or object.
127
63
  * The cache will first check whether has the same key.
@@ -140,79 +76,56 @@ var StorageCacheCommon = /** @class */ (function () {
140
76
  *
141
77
  * @return {Promise}
142
78
  */
143
- StorageCacheCommon.prototype.setItem = function (key, value, options) {
144
- return __awaiter(this, void 0, void 0, function () {
145
- var cacheItemOptions, prefixedKey, item, val, validKeys, sizeToPop, e_1;
146
- return __generator(this, function (_a) {
147
- switch (_a.label) {
148
- case 0:
149
- logger.debug("Set item: key is ".concat(key, ", value is ").concat(value, " with options: ").concat(options));
150
- if (!key || key === currentSizeKey) {
151
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
152
- return [2 /*return*/];
153
- }
154
- if (typeof value === 'undefined') {
155
- logger.warn("The value of item should not be undefined!");
156
- return [2 /*return*/];
157
- }
158
- cacheItemOptions = {
159
- priority: (options === null || options === void 0 ? void 0 : options.priority) !== undefined
160
- ? options.priority
161
- : this.config.defaultPriority,
162
- expires: (options === null || options === void 0 ? void 0 : options.expires) !== undefined
163
- ? options.expires
164
- : this.config.defaultTTL + getCurrentTime(),
165
- };
166
- if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
167
- logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
168
- return [2 /*return*/];
169
- }
170
- prefixedKey = "".concat(this.config.keyPrefix).concat(key);
171
- item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
172
- // check whether this item is too big;
173
- if (item.byteSize > this.config.itemMaxSize) {
174
- logger.warn("Item with key: ".concat(key, " you are trying to put into is too big!"));
175
- return [2 /*return*/];
176
- }
177
- _a.label = 1;
178
- case 1:
179
- _a.trys.push([1, 11, , 12]);
180
- return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
181
- case 2:
182
- val = _a.sent();
183
- if (!val) return [3 /*break*/, 4];
184
- return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize)];
185
- case 3:
186
- _a.sent();
187
- _a.label = 4;
188
- case 4: return [4 /*yield*/, this.isCacheFull(item.byteSize)];
189
- case 5:
190
- if (!_a.sent()) return [3 /*break*/, 10];
191
- return [4 /*yield*/, this.clearInvalidAndGetRemainingKeys()];
192
- case 6:
193
- validKeys = _a.sent();
194
- return [4 /*yield*/, this.isCacheFull(item.byteSize)];
195
- case 7:
196
- if (!_a.sent()) return [3 /*break*/, 10];
197
- return [4 /*yield*/, this.sizeToPop(item.byteSize)];
198
- case 8:
199
- sizeToPop = _a.sent();
200
- return [4 /*yield*/, this.popOutItems(validKeys, sizeToPop)];
201
- case 9:
202
- _a.sent();
203
- _a.label = 10;
204
- case 10:
205
- // put item in the cache
206
- return [2 /*return*/, this.setCacheItem(prefixedKey, item)];
207
- case 11:
208
- e_1 = _a.sent();
209
- logger.warn("setItem failed! ".concat(e_1));
210
- return [3 /*break*/, 12];
211
- case 12: return [2 /*return*/];
79
+ async setItem(key, value, options) {
80
+ logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);
81
+ if (!key || key === currentSizeKey) {
82
+ logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);
83
+ return;
84
+ }
85
+ if (typeof value === 'undefined') {
86
+ logger.warn(`The value of item should not be undefined!`);
87
+ return;
88
+ }
89
+ const cacheItemOptions = {
90
+ priority: options?.priority !== undefined
91
+ ? options.priority
92
+ : this.config.defaultPriority,
93
+ expires: options?.expires !== undefined
94
+ ? options.expires
95
+ : this.config.defaultTTL + getCurrentTime(),
96
+ };
97
+ if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
98
+ logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);
99
+ return;
100
+ }
101
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
102
+ const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
103
+ // check whether this item is too big;
104
+ if (item.byteSize > this.config.itemMaxSize) {
105
+ logger.warn(`Item with key: ${key} you are trying to put into is too big!`);
106
+ return;
107
+ }
108
+ try {
109
+ // first look into the storage, if it exists, delete it.
110
+ const val = await this.getStorage().getItem(prefixedKey);
111
+ if (val) {
112
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
113
+ }
114
+ // check whether the cache is full
115
+ if (await this.isCacheFull(item.byteSize)) {
116
+ const validKeys = await this.clearInvalidAndGetRemainingKeys();
117
+ if (await this.isCacheFull(item.byteSize)) {
118
+ const sizeToPop = await this.sizeToPop(item.byteSize);
119
+ await this.popOutItems(validKeys, sizeToPop);
212
120
  }
213
- });
214
- });
215
- };
121
+ }
122
+ // put item in the cache
123
+ return this.setCacheItem(prefixedKey, item);
124
+ }
125
+ catch (e) {
126
+ logger.warn(`setItem failed! ${e}`);
127
+ }
128
+ }
216
129
  /**
217
130
  * Get item from cache. It will return null if item doesn’t exist or it has been expired.
218
131
  * If you specified callback function in the options,
@@ -228,57 +141,41 @@ var StorageCacheCommon = /** @class */ (function () {
228
141
  *
229
142
  * @return {Promise} - return a promise resolves to be the value of the item
230
143
  */
231
- StorageCacheCommon.prototype.getItem = function (key, options) {
232
- return __awaiter(this, void 0, void 0, function () {
233
- var cached, prefixedKey, item, val, e_2;
234
- return __generator(this, function (_a) {
235
- switch (_a.label) {
236
- case 0:
237
- logger.debug("Get item: key is ".concat(key, " with options ").concat(options));
238
- if (!key || key === currentSizeKey) {
239
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
240
- return [2 /*return*/, null];
241
- }
242
- prefixedKey = "".concat(this.config.keyPrefix).concat(key);
243
- _a.label = 1;
244
- case 1:
245
- _a.trys.push([1, 11, , 12]);
246
- return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
247
- case 2:
248
- cached = _a.sent();
249
- if (!(cached != null)) return [3 /*break*/, 7];
250
- return [4 /*yield*/, this.isExpired(prefixedKey)];
251
- case 3:
252
- if (!_a.sent()) return [3 /*break*/, 5];
253
- // if expired, remove that item and return null
254
- return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize)];
255
- case 4:
256
- // if expired, remove that item and return null
257
- _a.sent();
258
- return [3 /*break*/, 7];
259
- case 5: return [4 /*yield*/, this.updateVisitedTime(JSON.parse(cached), prefixedKey)];
260
- case 6:
261
- item = _a.sent();
262
- return [2 /*return*/, item.data];
263
- case 7:
264
- if (!(options === null || options === void 0 ? void 0 : options.callback)) return [3 /*break*/, 10];
265
- val = options.callback();
266
- if (!(val !== null)) return [3 /*break*/, 9];
267
- return [4 /*yield*/, this.setItem(key, val, options)];
268
- case 8:
269
- _a.sent();
270
- _a.label = 9;
271
- case 9: return [2 /*return*/, val];
272
- case 10: return [2 /*return*/, null];
273
- case 11:
274
- e_2 = _a.sent();
275
- logger.warn("getItem failed! ".concat(e_2));
276
- return [2 /*return*/, null];
277
- case 12: return [2 /*return*/];
144
+ async getItem(key, options) {
145
+ logger.debug(`Get item: key is ${key} with options ${options}`);
146
+ let cached;
147
+ if (!key || key === currentSizeKey) {
148
+ logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);
149
+ return null;
150
+ }
151
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
152
+ try {
153
+ cached = await this.getStorage().getItem(prefixedKey);
154
+ if (cached != null) {
155
+ if (await this.isExpired(prefixedKey)) {
156
+ // if expired, remove that item and return null
157
+ await this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize);
278
158
  }
279
- });
280
- });
281
- };
159
+ else {
160
+ // if not expired, update its visitedTime and return the value
161
+ const item = await this.updateVisitedTime(JSON.parse(cached), prefixedKey);
162
+ return item.data;
163
+ }
164
+ }
165
+ if (options?.callback) {
166
+ const val = options.callback();
167
+ if (val !== null) {
168
+ await this.setItem(key, val, options);
169
+ }
170
+ return val;
171
+ }
172
+ return null;
173
+ }
174
+ catch (e) {
175
+ logger.warn(`getItem failed! ${e}`);
176
+ return null;
177
+ }
178
+ }
282
179
  /**
283
180
  * remove item from the cache
284
181
  * The cache will abort output a warning:
@@ -286,66 +183,41 @@ var StorageCacheCommon = /** @class */ (function () {
286
183
  * @param {String} key - the key of the item
287
184
  * @return {Promise}
288
185
  */
289
- StorageCacheCommon.prototype.removeItem = function (key) {
290
- return __awaiter(this, void 0, void 0, function () {
291
- var prefixedKey, val, e_3;
292
- return __generator(this, function (_a) {
293
- switch (_a.label) {
294
- case 0:
295
- logger.debug("Remove item: key is ".concat(key));
296
- if (!key || key === currentSizeKey) {
297
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
298
- return [2 /*return*/];
299
- }
300
- prefixedKey = "".concat(this.config.keyPrefix).concat(key);
301
- _a.label = 1;
302
- case 1:
303
- _a.trys.push([1, 5, , 6]);
304
- return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
305
- case 2:
306
- val = _a.sent();
307
- if (!val) return [3 /*break*/, 4];
308
- return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize)];
309
- case 3:
310
- _a.sent();
311
- _a.label = 4;
312
- case 4: return [3 /*break*/, 6];
313
- case 5:
314
- e_3 = _a.sent();
315
- logger.warn("removeItem failed! ".concat(e_3));
316
- return [3 /*break*/, 6];
317
- case 6: return [2 /*return*/];
318
- }
319
- });
320
- });
321
- };
186
+ async removeItem(key) {
187
+ logger.debug(`Remove item: key is ${key}`);
188
+ if (!key || key === currentSizeKey) {
189
+ logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);
190
+ return;
191
+ }
192
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
193
+ try {
194
+ const val = await this.getStorage().getItem(prefixedKey);
195
+ if (val) {
196
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
197
+ }
198
+ }
199
+ catch (e) {
200
+ logger.warn(`removeItem failed! ${e}`);
201
+ }
202
+ }
322
203
  /**
323
204
  * Return all the keys owned by this cache.
324
205
  * Will return an empty array if error occurred.
325
206
  *
326
207
  * @return {Promise}
327
208
  */
328
- StorageCacheCommon.prototype.getAllKeys = function () {
329
- return __awaiter(this, void 0, void 0, function () {
330
- var e_4;
331
- return __generator(this, function (_a) {
332
- switch (_a.label) {
333
- case 0:
334
- _a.trys.push([0, 2, , 3]);
335
- return [4 /*yield*/, this.getAllCacheKeys()];
336
- case 1: return [2 /*return*/, _a.sent()];
337
- case 2:
338
- e_4 = _a.sent();
339
- logger.warn("getAllkeys failed! ".concat(e_4));
340
- return [2 /*return*/, []];
341
- case 3: return [2 /*return*/];
342
- }
343
- });
344
- });
345
- };
346
- StorageCacheCommon.prototype.getStorage = function () {
209
+ async getAllKeys() {
210
+ try {
211
+ return await this.getAllCacheKeys();
212
+ }
213
+ catch (e) {
214
+ logger.warn(`getAllkeys failed! ${e}`);
215
+ return [];
216
+ }
217
+ }
218
+ getStorage() {
347
219
  return this.keyValueStorage;
348
- };
220
+ }
349
221
  /**
350
222
  * check whether item is expired
351
223
  *
@@ -353,66 +225,37 @@ var StorageCacheCommon = /** @class */ (function () {
353
225
  *
354
226
  * @return true if the item is expired.
355
227
  */
356
- StorageCacheCommon.prototype.isExpired = function (key) {
357
- return __awaiter(this, void 0, void 0, function () {
358
- var text, item;
359
- return __generator(this, function (_a) {
360
- switch (_a.label) {
361
- case 0: return [4 /*yield*/, this.getStorage().getItem(key)];
362
- case 1:
363
- text = _a.sent();
364
- assert(text !== null, CacheErrorCode.NoCacheItem, "Key: ".concat(key));
365
- item = JSON.parse(text);
366
- if (getCurrentTime() >= item.expires) {
367
- return [2 /*return*/, true];
368
- }
369
- return [2 /*return*/, false];
370
- }
371
- });
372
- });
373
- };
228
+ async isExpired(key) {
229
+ const text = await this.getStorage().getItem(key);
230
+ assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`);
231
+ const item = JSON.parse(text);
232
+ if (getCurrentTime() >= item.expires) {
233
+ return true;
234
+ }
235
+ return false;
236
+ }
374
237
  /**
375
238
  * delete item from cache
376
239
  *
377
240
  * @param prefixedKey - the key of the item
378
241
  * @param size - optional, the byte size of the item
379
242
  */
380
- StorageCacheCommon.prototype.removeCacheItem = function (prefixedKey, size) {
381
- return __awaiter(this, void 0, void 0, function () {
382
- var item, itemSize, removeItemError_1;
383
- return __generator(this, function (_a) {
384
- switch (_a.label) {
385
- case 0: return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
386
- case 1:
387
- item = _a.sent();
388
- assert(item !== null, CacheErrorCode.NoCacheItem, "Key: ".concat(prefixedKey));
389
- itemSize = size !== null && size !== void 0 ? size : JSON.parse(item).byteSize;
390
- // first try to update the current size of the cache
391
- return [4 /*yield*/, this.decreaseCurrentSizeInBytes(itemSize)];
392
- case 2:
393
- // first try to update the current size of the cache
394
- _a.sent();
395
- _a.label = 3;
396
- case 3:
397
- _a.trys.push([3, 5, , 7]);
398
- return [4 /*yield*/, this.getStorage().removeItem(prefixedKey)];
399
- case 4:
400
- _a.sent();
401
- return [3 /*break*/, 7];
402
- case 5:
403
- removeItemError_1 = _a.sent();
404
- // if some error happened, we need to rollback the current size
405
- return [4 /*yield*/, this.increaseCurrentSizeInBytes(itemSize)];
406
- case 6:
407
- // if some error happened, we need to rollback the current size
408
- _a.sent();
409
- logger.error("Failed to remove item: ".concat(removeItemError_1));
410
- return [3 /*break*/, 7];
411
- case 7: return [2 /*return*/];
412
- }
413
- });
414
- });
415
- };
243
+ async removeCacheItem(prefixedKey, size) {
244
+ const item = await this.getStorage().getItem(prefixedKey);
245
+ assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`);
246
+ const itemSize = size ?? JSON.parse(item).byteSize;
247
+ // first try to update the current size of the cache
248
+ await this.decreaseCurrentSizeInBytes(itemSize);
249
+ // try to remove the item from cache
250
+ try {
251
+ await this.getStorage().removeItem(prefixedKey);
252
+ }
253
+ catch (removeItemError) {
254
+ // if some error happened, we need to rollback the current size
255
+ await this.increaseCurrentSizeInBytes(itemSize);
256
+ logger.error(`Failed to remove item: ${removeItemError}`);
257
+ }
258
+ }
416
259
  /**
417
260
  * produce a JSON object with meta-data and data value
418
261
  * @param value - the value of the item
@@ -420,15 +263,14 @@ var StorageCacheCommon = /** @class */ (function () {
420
263
  *
421
264
  * @return - the item which has the meta-data and the value
422
265
  */
423
- StorageCacheCommon.prototype.fillCacheItem = function (key, value, options) {
424
- var _a, _b;
425
- var item = {
426
- key: key,
266
+ fillCacheItem(key, value, options) {
267
+ const item = {
268
+ key,
427
269
  data: value,
428
270
  timestamp: getCurrentTime(),
429
271
  visitedTime: getCurrentTime(),
430
- priority: (_a = options.priority) !== null && _a !== void 0 ? _a : 0,
431
- expires: (_b = options.expires) !== null && _b !== void 0 ? _b : 0,
272
+ priority: options.priority ?? 0,
273
+ expires: options.expires ?? 0,
432
274
  type: typeof value,
433
275
  byteSize: 0,
434
276
  };
@@ -437,8 +279,8 @@ var StorageCacheCommon = /** @class */ (function () {
437
279
  // re-calculate using cache item with updated byteSize property
438
280
  item.byteSize = getByteLength(JSON.stringify(item));
439
281
  return item;
440
- };
441
- StorageCacheCommon.prototype.sanitizeConfig = function () {
282
+ }
283
+ sanitizeConfig() {
442
284
  if (this.config.itemMaxSize > this.config.capacityInBytes) {
443
285
  logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');
444
286
  this.config.itemMaxSize = defaultConfig.itemMaxSize;
@@ -453,54 +295,30 @@ var StorageCacheCommon = /** @class */ (function () {
453
295
  this.config.warningThreshold = defaultConfig.warningThreshold;
454
296
  }
455
297
  // Set 5MB limit
456
- var cacheLimit = 5 * 1024 * 1024;
298
+ const cacheLimit = 5 * 1024 * 1024;
457
299
  if (this.config.capacityInBytes > cacheLimit) {
458
300
  logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');
459
301
  this.config.capacityInBytes = defaultConfig.capacityInBytes;
460
302
  }
461
- };
303
+ }
462
304
  /**
463
305
  * increase current size of the cache
464
306
  *
465
307
  * @param amount - the amount of the cache szie which need to be increased
466
308
  */
467
- StorageCacheCommon.prototype.increaseCurrentSizeInBytes = function (amount) {
468
- return __awaiter(this, void 0, void 0, function () {
469
- var size;
470
- return __generator(this, function (_a) {
471
- switch (_a.label) {
472
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
473
- case 1:
474
- size = _a.sent();
475
- return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size + amount).toString())];
476
- case 2:
477
- _a.sent();
478
- return [2 /*return*/];
479
- }
480
- });
481
- });
482
- };
309
+ async increaseCurrentSizeInBytes(amount) {
310
+ const size = await this.getCurrentCacheSize();
311
+ await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size + amount).toString());
312
+ }
483
313
  /**
484
314
  * decrease current size of the cache
485
315
  *
486
316
  * @param amount - the amount of the cache size which needs to be decreased
487
317
  */
488
- StorageCacheCommon.prototype.decreaseCurrentSizeInBytes = function (amount) {
489
- return __awaiter(this, void 0, void 0, function () {
490
- var size;
491
- return __generator(this, function (_a) {
492
- switch (_a.label) {
493
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
494
- case 1:
495
- size = _a.sent();
496
- return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size - amount).toString())];
497
- case 2:
498
- _a.sent();
499
- return [2 /*return*/];
500
- }
501
- });
502
- });
503
- };
318
+ async decreaseCurrentSizeInBytes(amount) {
319
+ const size = await this.getCurrentCacheSize();
320
+ await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size - amount).toString());
321
+ }
504
322
  /**
505
323
  * update the visited time if item has been visited
506
324
  *
@@ -509,20 +327,11 @@ var StorageCacheCommon = /** @class */ (function () {
509
327
  *
510
328
  * @return the updated item
511
329
  */
512
- StorageCacheCommon.prototype.updateVisitedTime = function (item, prefixedKey) {
513
- return __awaiter(this, void 0, void 0, function () {
514
- return __generator(this, function (_a) {
515
- switch (_a.label) {
516
- case 0:
517
- item.visitedTime = getCurrentTime();
518
- return [4 /*yield*/, this.getStorage().setItem(prefixedKey, JSON.stringify(item))];
519
- case 1:
520
- _a.sent();
521
- return [2 /*return*/, item];
522
- }
523
- });
524
- });
525
- };
330
+ async updateVisitedTime(item, prefixedKey) {
331
+ item.visitedTime = getCurrentTime();
332
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
333
+ return item;
334
+ }
526
335
  /**
527
336
  * put item into cache
528
337
  *
@@ -530,38 +339,19 @@ var StorageCacheCommon = /** @class */ (function () {
530
339
  * @param itemData - the value of the item
531
340
  * @param itemSizeInBytes - the byte size of the item
532
341
  */
533
- StorageCacheCommon.prototype.setCacheItem = function (prefixedKey, item) {
534
- return __awaiter(this, void 0, void 0, function () {
535
- var setItemErr_1;
536
- return __generator(this, function (_a) {
537
- switch (_a.label) {
538
- case 0:
539
- // first try to update the current size of the cache.
540
- return [4 /*yield*/, this.increaseCurrentSizeInBytes(item.byteSize)];
541
- case 1:
542
- // first try to update the current size of the cache.
543
- _a.sent();
544
- _a.label = 2;
545
- case 2:
546
- _a.trys.push([2, 4, , 6]);
547
- return [4 /*yield*/, this.getStorage().setItem(prefixedKey, JSON.stringify(item))];
548
- case 3:
549
- _a.sent();
550
- return [3 /*break*/, 6];
551
- case 4:
552
- setItemErr_1 = _a.sent();
553
- // if some error happened, we need to rollback the current size
554
- return [4 /*yield*/, this.decreaseCurrentSizeInBytes(item.byteSize)];
555
- case 5:
556
- // if some error happened, we need to rollback the current size
557
- _a.sent();
558
- logger.error("Failed to set item ".concat(setItemErr_1));
559
- return [3 /*break*/, 6];
560
- case 6: return [2 /*return*/];
561
- }
562
- });
563
- });
564
- };
342
+ async setCacheItem(prefixedKey, item) {
343
+ // first try to update the current size of the cache.
344
+ await this.increaseCurrentSizeInBytes(item.byteSize);
345
+ // try to add the item into cache
346
+ try {
347
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
348
+ }
349
+ catch (setItemErr) {
350
+ // if some error happened, we need to rollback the current size
351
+ await this.decreaseCurrentSizeInBytes(item.byteSize);
352
+ logger.error(`Failed to set item ${setItemErr}`);
353
+ }
354
+ }
565
355
  /**
566
356
  * total space needed when poping out items
567
357
  *
@@ -569,23 +359,14 @@ var StorageCacheCommon = /** @class */ (function () {
569
359
  *
570
360
  * @return total space needed
571
361
  */
572
- StorageCacheCommon.prototype.sizeToPop = function (itemSize) {
573
- return __awaiter(this, void 0, void 0, function () {
574
- var cur, spaceItemNeed, cacheThresholdSpace;
575
- return __generator(this, function (_a) {
576
- switch (_a.label) {
577
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
578
- case 1:
579
- cur = _a.sent();
580
- spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
581
- cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
582
- return [2 /*return*/, spaceItemNeed > cacheThresholdSpace
583
- ? spaceItemNeed
584
- : cacheThresholdSpace];
585
- }
586
- });
587
- });
588
- };
362
+ async sizeToPop(itemSize) {
363
+ const cur = await this.getCurrentCacheSize();
364
+ const spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
365
+ const cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
366
+ return spaceItemNeed > cacheThresholdSpace
367
+ ? spaceItemNeed
368
+ : cacheThresholdSpace;
369
+ }
589
370
  /**
590
371
  * see whether cache is full
591
372
  *
@@ -593,19 +374,10 @@ var StorageCacheCommon = /** @class */ (function () {
593
374
  *
594
375
  * @return true if cache is full
595
376
  */
596
- StorageCacheCommon.prototype.isCacheFull = function (itemSize) {
597
- return __awaiter(this, void 0, void 0, function () {
598
- var cur;
599
- return __generator(this, function (_a) {
600
- switch (_a.label) {
601
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
602
- case 1:
603
- cur = _a.sent();
604
- return [2 /*return*/, itemSize + cur > this.config.capacityInBytes];
605
- }
606
- });
607
- });
608
- };
377
+ async isCacheFull(itemSize) {
378
+ const cur = await this.getCurrentCacheSize();
379
+ return itemSize + cur > this.config.capacityInBytes;
380
+ }
609
381
  /**
610
382
  * get all the items we have, sort them by their priority,
611
383
  * if priority is same, sort them by their last visited time
@@ -614,69 +386,42 @@ var StorageCacheCommon = /** @class */ (function () {
614
386
  * @param keys - all the keys in this cache
615
387
  * @param sizeToPop - the total size of the items which needed to be poped out
616
388
  */
617
- StorageCacheCommon.prototype.popOutItems = function (keys, sizeToPop) {
618
- return __awaiter(this, void 0, void 0, function () {
619
- var items, remainedSize, i, val, item, i;
620
- return __generator(this, function (_a) {
621
- switch (_a.label) {
622
- case 0:
623
- items = [];
624
- remainedSize = sizeToPop;
625
- i = 0;
626
- _a.label = 1;
627
- case 1:
628
- if (!(i < keys.length)) return [3 /*break*/, 4];
629
- return [4 /*yield*/, this.getStorage().getItem(keys[i])];
630
- case 2:
631
- val = _a.sent();
632
- if (val != null) {
633
- item = JSON.parse(val);
634
- items.push(item);
635
- }
636
- _a.label = 3;
637
- case 3:
638
- i += 1;
639
- return [3 /*break*/, 1];
640
- case 4:
641
- // first compare priority
642
- // then compare visited time
643
- items.sort(function (a, b) {
644
- if (a.priority > b.priority) {
645
- return -1;
646
- }
647
- else if (a.priority < b.priority) {
648
- return 1;
649
- }
650
- else {
651
- if (a.visitedTime < b.visitedTime) {
652
- return -1;
653
- }
654
- else
655
- return 1;
656
- }
657
- });
658
- i = 0;
659
- _a.label = 5;
660
- case 5:
661
- if (!(i < items.length)) return [3 /*break*/, 8];
662
- // pop out items until we have enough room for new item
663
- return [4 /*yield*/, this.removeCacheItem(items[i].key, items[i].byteSize)];
664
- case 6:
665
- // pop out items until we have enough room for new item
666
- _a.sent();
667
- remainedSize -= items[i].byteSize;
668
- if (remainedSize <= 0) {
669
- return [2 /*return*/];
670
- }
671
- _a.label = 7;
672
- case 7:
673
- i += 1;
674
- return [3 /*break*/, 5];
675
- case 8: return [2 /*return*/];
389
+ async popOutItems(keys, sizeToPop) {
390
+ const items = [];
391
+ let remainedSize = sizeToPop;
392
+ for (let i = 0; i < keys.length; i += 1) {
393
+ const val = await this.getStorage().getItem(keys[i]);
394
+ if (val != null) {
395
+ const item = JSON.parse(val);
396
+ items.push(item);
397
+ }
398
+ }
399
+ // first compare priority
400
+ // then compare visited time
401
+ items.sort((a, b) => {
402
+ if (a.priority > b.priority) {
403
+ return -1;
404
+ }
405
+ else if (a.priority < b.priority) {
406
+ return 1;
407
+ }
408
+ else {
409
+ if (a.visitedTime < b.visitedTime) {
410
+ return -1;
676
411
  }
677
- });
412
+ else
413
+ return 1;
414
+ }
678
415
  });
679
- };
416
+ for (let i = 0; i < items.length; i += 1) {
417
+ // pop out items until we have enough room for new item
418
+ await this.removeCacheItem(items[i].key, items[i].byteSize);
419
+ remainedSize -= items[i].byteSize;
420
+ if (remainedSize <= 0) {
421
+ return;
422
+ }
423
+ }
424
+ }
680
425
  /**
681
426
  * Scan the storage and combine the following operations for efficiency
682
427
  * 1. Clear out all expired keys owned by this cache, not including the size key.
@@ -684,111 +429,36 @@ var StorageCacheCommon = /** @class */ (function () {
684
429
  *
685
430
  * @return The remaining valid keys
686
431
  */
687
- StorageCacheCommon.prototype.clearInvalidAndGetRemainingKeys = function () {
688
- return __awaiter(this, void 0, void 0, function () {
689
- var remainingKeys, keys, keys_1, keys_1_1, key, e_5_1;
690
- var e_5, _a;
691
- return __generator(this, function (_b) {
692
- switch (_b.label) {
693
- case 0:
694
- remainingKeys = [];
695
- return [4 /*yield*/, this.getAllCacheKeys({
696
- omitSizeKey: true,
697
- })];
698
- case 1:
699
- keys = _b.sent();
700
- _b.label = 2;
701
- case 2:
702
- _b.trys.push([2, 9, 10, 11]);
703
- keys_1 = __values(keys), keys_1_1 = keys_1.next();
704
- _b.label = 3;
705
- case 3:
706
- if (!!keys_1_1.done) return [3 /*break*/, 8];
707
- key = keys_1_1.value;
708
- return [4 /*yield*/, this.isExpired(key)];
709
- case 4:
710
- if (!_b.sent()) return [3 /*break*/, 6];
711
- return [4 /*yield*/, this.removeCacheItem(key)];
712
- case 5:
713
- _b.sent();
714
- return [3 /*break*/, 7];
715
- case 6:
716
- remainingKeys.push(key);
717
- _b.label = 7;
718
- case 7:
719
- keys_1_1 = keys_1.next();
720
- return [3 /*break*/, 3];
721
- case 8: return [3 /*break*/, 11];
722
- case 9:
723
- e_5_1 = _b.sent();
724
- e_5 = { error: e_5_1 };
725
- return [3 /*break*/, 11];
726
- case 10:
727
- try {
728
- if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
729
- }
730
- finally { if (e_5) throw e_5.error; }
731
- return [7 /*endfinally*/];
732
- case 11: return [2 /*return*/, remainingKeys];
733
- }
734
- });
432
+ async clearInvalidAndGetRemainingKeys() {
433
+ const remainingKeys = [];
434
+ const keys = await this.getAllCacheKeys({
435
+ omitSizeKey: true,
735
436
  });
736
- };
437
+ for (const key of keys) {
438
+ if (await this.isExpired(key)) {
439
+ await this.removeCacheItem(key);
440
+ }
441
+ else {
442
+ remainingKeys.push(key);
443
+ }
444
+ }
445
+ return remainingKeys;
446
+ }
737
447
  /**
738
448
  * clear the entire cache
739
449
  * The cache will abort and output a warning if error occurs
740
450
  * @return {Promise}
741
451
  */
742
- StorageCacheCommon.prototype.clear = function () {
743
- return __awaiter(this, void 0, void 0, function () {
744
- var keys, keys_2, keys_2_1, key, e_6_1, e_7;
745
- var e_6, _a;
746
- return __generator(this, function (_b) {
747
- switch (_b.label) {
748
- case 0:
749
- logger.debug("Clear Cache");
750
- _b.label = 1;
751
- case 1:
752
- _b.trys.push([1, 11, , 12]);
753
- return [4 /*yield*/, this.getAllKeys()];
754
- case 2:
755
- keys = _b.sent();
756
- _b.label = 3;
757
- case 3:
758
- _b.trys.push([3, 8, 9, 10]);
759
- keys_2 = __values(keys), keys_2_1 = keys_2.next();
760
- _b.label = 4;
761
- case 4:
762
- if (!!keys_2_1.done) return [3 /*break*/, 7];
763
- key = keys_2_1.value;
764
- return [4 /*yield*/, this.getStorage().removeItem(key)];
765
- case 5:
766
- _b.sent();
767
- _b.label = 6;
768
- case 6:
769
- keys_2_1 = keys_2.next();
770
- return [3 /*break*/, 4];
771
- case 7: return [3 /*break*/, 10];
772
- case 8:
773
- e_6_1 = _b.sent();
774
- e_6 = { error: e_6_1 };
775
- return [3 /*break*/, 10];
776
- case 9:
777
- try {
778
- if (keys_2_1 && !keys_2_1.done && (_a = keys_2.return)) _a.call(keys_2);
779
- }
780
- finally { if (e_6) throw e_6.error; }
781
- return [7 /*endfinally*/];
782
- case 10: return [3 /*break*/, 12];
783
- case 11:
784
- e_7 = _b.sent();
785
- logger.warn("clear failed! ".concat(e_7));
786
- return [3 /*break*/, 12];
787
- case 12: return [2 /*return*/];
788
- }
789
- });
790
- });
791
- };
792
- return StorageCacheCommon;
793
- }());
794
- export { StorageCacheCommon };
452
+ async clear() {
453
+ logger.debug(`Clear Cache`);
454
+ try {
455
+ const keys = await this.getAllKeys();
456
+ for (const key of keys) {
457
+ await this.getStorage().removeItem(key);
458
+ }
459
+ }
460
+ catch (e) {
461
+ logger.warn(`clear failed! ${e}`);
462
+ }
463
+ }
464
+ }