UNPKG

55.6 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory(require("aws_amplify_core"));
4 else if(typeof define === 'function' && define.amd)
5 define("aws_amplify_cache", ["aws_amplify_core"], factory);
6 else if(typeof exports === 'object')
7 exports["aws_amplify_cache"] = factory(require("aws_amplify_core"));
8 else
9 root["aws_amplify_cache"] = factory(root["aws_amplify_core"]);
10})(this, function(__WEBPACK_EXTERNAL_MODULE__aws_amplify_core__) {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14/******/
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17/******/
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId]) {
20/******/ return installedModules[moduleId].exports;
21/******/ }
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ i: moduleId,
25/******/ l: false,
26/******/ exports: {}
27/******/ };
28/******/
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31/******/
32/******/ // Flag the module as loaded
33/******/ module.l = true;
34/******/
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38/******/
39/******/
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42/******/
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45/******/
46/******/ // define getter function for harmony exports
47/******/ __webpack_require__.d = function(exports, name, getter) {
48/******/ if(!__webpack_require__.o(exports, name)) {
49/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
50/******/ }
51/******/ };
52/******/
53/******/ // define __esModule on exports
54/******/ __webpack_require__.r = function(exports) {
55/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
56/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
57/******/ }
58/******/ Object.defineProperty(exports, '__esModule', { value: true });
59/******/ };
60/******/
61/******/ // create a fake namespace object
62/******/ // mode & 1: value is a module id, require it
63/******/ // mode & 2: merge all properties of value into the ns
64/******/ // mode & 4: return value when already ns object
65/******/ // mode & 8|1: behave like require
66/******/ __webpack_require__.t = function(value, mode) {
67/******/ if(mode & 1) value = __webpack_require__(value);
68/******/ if(mode & 8) return value;
69/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
70/******/ var ns = Object.create(null);
71/******/ __webpack_require__.r(ns);
72/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
73/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
74/******/ return ns;
75/******/ };
76/******/
77/******/ // getDefaultExport function for compatibility with non-harmony modules
78/******/ __webpack_require__.n = function(module) {
79/******/ var getter = module && module.__esModule ?
80/******/ function getDefault() { return module['default']; } :
81/******/ function getModuleExports() { return module; };
82/******/ __webpack_require__.d(getter, 'a', getter);
83/******/ return getter;
84/******/ };
85/******/
86/******/ // Object.prototype.hasOwnProperty.call
87/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
88/******/
89/******/ // __webpack_public_path__
90/******/ __webpack_require__.p = "";
91/******/
92/******/
93/******/ // Load entry module and return exports
94/******/ return __webpack_require__(__webpack_require__.s = "./lib-esm/index.js");
95/******/ })
96/************************************************************************/
97/******/ ({
98
99/***/ "./lib-esm/BrowserStorageCache.js":
100/*!****************************************!*\
101 !*** ./lib-esm/BrowserStorageCache.js ***!
102 \****************************************/
103/*! exports provided: BrowserStorageCacheClass, BrowserStorageCache, default */
104/***/ (function(module, __webpack_exports__, __webpack_require__) {
105
106"use strict";
107__webpack_require__.r(__webpack_exports__);
108/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCacheClass", function() { return BrowserStorageCacheClass; });
109/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCache", function() { return BrowserStorageCache; });
110/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
111/* harmony import */ var _StorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./StorageCache */ "./lib-esm/StorageCache.js");
112/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
113/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__);
114/*
115 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
116 *
117 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
118 * the License. A copy of the License is located at
119 *
120 * http://aws.amazon.com/apache2.0/
121 *
122 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
123 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
124 * and limitations under the License.
125 */
126var __extends = undefined && undefined.__extends || function () {
127 var _extendStatics = function extendStatics(d, b) {
128 _extendStatics = Object.setPrototypeOf || {
129 __proto__: []
130 } instanceof Array && function (d, b) {
131 d.__proto__ = b;
132 } || function (d, b) {
133 for (var p in b) {
134 if (b.hasOwnProperty(p)) d[p] = b[p];
135 }
136 };
137
138 return _extendStatics(d, b);
139 };
140
141 return function (d, b) {
142 _extendStatics(d, b);
143
144 function __() {
145 this.constructor = d;
146 }
147
148 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
149 };
150}();
151
152
153
154
155var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__["ConsoleLogger"]('Cache');
156/**
157 * Customized storage based on the SessionStorage or LocalStorage with LRU implemented
158 */
159
160var BrowserStorageCacheClass =
161/** @class */
162function (_super) {
163 __extends(BrowserStorageCacheClass, _super);
164 /**
165 * initialize the cache
166 * @param config - the configuration of the cache
167 */
168
169
170 function BrowserStorageCacheClass(config) {
171 var _this = this;
172
173 var cacheConfig = config ? Object.assign({}, _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"], config) : _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"];
174 _this = _super.call(this, cacheConfig) || this;
175 _this.config.storage = cacheConfig.storage;
176 _this.getItem = _this.getItem.bind(_this);
177 _this.setItem = _this.setItem.bind(_this);
178 _this.removeItem = _this.removeItem.bind(_this);
179 return _this;
180 }
181 /**
182 * decrease current size of the cache
183 *
184 * @private
185 * @param amount - the amount of the cache size which needs to be decreased
186 */
187
188
189 BrowserStorageCacheClass.prototype._decreaseCurSizeInBytes = function (amount) {
190 var curSize = this.getCacheCurSize();
191 this.config.storage.setItem(this.cacheCurSizeKey, (curSize - amount).toString());
192 };
193 /**
194 * increase current size of the cache
195 *
196 * @private
197 * @param amount - the amount of the cache szie which need to be increased
198 */
199
200
201 BrowserStorageCacheClass.prototype._increaseCurSizeInBytes = function (amount) {
202 var curSize = this.getCacheCurSize();
203 this.config.storage.setItem(this.cacheCurSizeKey, (curSize + amount).toString());
204 };
205 /**
206 * update the visited time if item has been visited
207 *
208 * @private
209 * @param item - the item which need to be refreshed
210 * @param prefixedKey - the key of the item
211 *
212 * @return the refreshed item
213 */
214
215
216 BrowserStorageCacheClass.prototype._refreshItem = function (item, prefixedKey) {
217 item.visitedTime = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])();
218 this.config.storage.setItem(prefixedKey, JSON.stringify(item));
219 return item;
220 };
221 /**
222 * check wether item is expired
223 *
224 * @private
225 * @param key - the key of the item
226 *
227 * @return true if the item is expired.
228 */
229
230
231 BrowserStorageCacheClass.prototype._isExpired = function (key) {
232 var text = this.config.storage.getItem(key);
233 var item = JSON.parse(text);
234
235 if (Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])() >= item.expires) {
236 return true;
237 }
238
239 return false;
240 };
241 /**
242 * delete item from cache
243 *
244 * @private
245 * @param prefixedKey - the key of the item
246 * @param size - optional, the byte size of the item
247 */
248
249
250 BrowserStorageCacheClass.prototype._removeItem = function (prefixedKey, size) {
251 var itemSize = size ? size : JSON.parse(this.config.storage.getItem(prefixedKey)).byteSize;
252
253 this._decreaseCurSizeInBytes(itemSize); // remove the cache item
254
255
256 this.config.storage.removeItem(prefixedKey);
257 };
258 /**
259 * put item into cache
260 *
261 * @private
262 * @param prefixedKey - the key of the item
263 * @param itemData - the value of the item
264 * @param itemSizeInBytes - the byte size of the item
265 */
266
267
268 BrowserStorageCacheClass.prototype._setItem = function (prefixedKey, item) {
269 // update the cache size
270 this._increaseCurSizeInBytes(item.byteSize);
271
272 try {
273 this.config.storage.setItem(prefixedKey, JSON.stringify(item));
274 } catch (setItemErr) {
275 // if failed, we need to rollback the cache size
276 this._decreaseCurSizeInBytes(item.byteSize);
277
278 logger.error("Failed to set item " + setItemErr);
279 }
280 };
281 /**
282 * total space needed when poping out items
283 *
284 * @private
285 * @param itemSize
286 *
287 * @return total space needed
288 */
289
290
291 BrowserStorageCacheClass.prototype._sizeToPop = function (itemSize) {
292 var spaceItemNeed = this.getCacheCurSize() + itemSize - this.config.capacityInBytes;
293 var cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
294 return spaceItemNeed > cacheThresholdSpace ? spaceItemNeed : cacheThresholdSpace;
295 };
296 /**
297 * see whether cache is full
298 *
299 * @private
300 * @param itemSize
301 *
302 * @return true if cache is full
303 */
304
305
306 BrowserStorageCacheClass.prototype._isCacheFull = function (itemSize) {
307 return itemSize + this.getCacheCurSize() > this.config.capacityInBytes;
308 };
309 /**
310 * scan the storage and find out all the keys owned by this cache
311 * also clean the expired keys while scanning
312 *
313 * @private
314 *
315 * @return array of keys
316 */
317
318
319 BrowserStorageCacheClass.prototype._findValidKeys = function () {
320 var keys = [];
321 var keyInCache = []; // get all keys in Storage
322
323 for (var i = 0; i < this.config.storage.length; i += 1) {
324 keyInCache.push(this.config.storage.key(i));
325 } // find those items which belong to our cache and also clean those expired items
326
327
328 for (var i = 0; i < keyInCache.length; i += 1) {
329 var key = keyInCache[i];
330
331 if (key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey) {
332 if (this._isExpired(key)) {
333 this._removeItem(key);
334 } else {
335 keys.push(key);
336 }
337 }
338 }
339
340 return keys;
341 };
342 /**
343 * get all the items we have, sort them by their priority,
344 * if priority is same, sort them by their last visited time
345 * pop out items from the low priority (5 is the lowest)
346 *
347 * @private
348 * @param keys - all the keys in this cache
349 * @param sizeToPop - the total size of the items which needed to be poped out
350 */
351
352
353 BrowserStorageCacheClass.prototype._popOutItems = function (keys, sizeToPop) {
354 var items = [];
355 var remainedSize = sizeToPop; // get the items from Storage
356
357 for (var i = 0; i < keys.length; i += 1) {
358 var val = this.config.storage.getItem(keys[i]);
359
360 if (val != null) {
361 var item = JSON.parse(val);
362 items.push(item);
363 }
364 } // first compare priority
365 // then compare visited time
366
367
368 items.sort(function (a, b) {
369 if (a.priority > b.priority) {
370 return -1;
371 } else if (a.priority < b.priority) {
372 return 1;
373 } else {
374 if (a.visitedTime < b.visitedTime) {
375 return -1;
376 } else return 1;
377 }
378 });
379
380 for (var i = 0; i < items.length; i += 1) {
381 // pop out items until we have enough room for new item
382 this._removeItem(items[i].key, items[i].byteSize);
383
384 remainedSize -= items[i].byteSize;
385
386 if (remainedSize <= 0) {
387 return;
388 }
389 }
390 };
391 /**
392 * Set item into cache. You can put number, string, boolean or object.
393 * The cache will first check whether has the same key.
394 * If it has, it will delete the old item and then put the new item in
395 * The cache will pop out items if it is full
396 * You can specify the cache item options. The cache will abort and output a warning:
397 * If the key is invalid
398 * If the size of the item exceeds itemMaxSize.
399 * If the value is undefined
400 * If incorrect cache item configuration
401 * If error happened with browser storage
402 *
403 * @param key - the key of the item
404 * @param value - the value of the item
405 * @param {Object} [options] - optional, the specified meta-data
406 */
407
408
409 BrowserStorageCacheClass.prototype.setItem = function (key, value, options) {
410 logger.log("Set item: key is " + key + ", value is " + value + " with options: " + options);
411 var prefixedKey = this.config.keyPrefix + key; // invalid keys
412
413 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
414 logger.warn("Invalid key: should not be empty or 'CurSize'");
415 return;
416 }
417
418 if (typeof value === 'undefined') {
419 logger.warn("The value of item should not be undefined!");
420 return;
421 }
422
423 var cacheItemOptions = {
424 priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
425 expires: options && options.expires !== undefined ? options.expires : this.config.defaultTTL + Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])()
426 };
427
428 if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
429 logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
430 return;
431 }
432
433 var item = this.fillCacheItem(prefixedKey, value, cacheItemOptions); // check wether this item is too big;
434
435 if (item.byteSize > this.config.itemMaxSize) {
436 logger.warn("Item with key: " + key + " you are trying to put into is too big!");
437 return;
438 }
439
440 try {
441 // first look into the storage, if it exists, delete it.
442 var val = this.config.storage.getItem(prefixedKey);
443
444 if (val) {
445 this._removeItem(prefixedKey, JSON.parse(val).byteSize);
446 } // check whether the cache is full
447
448
449 if (this._isCacheFull(item.byteSize)) {
450 var validKeys = this._findValidKeys(); // check again and then pop out items
451
452
453 if (this._isCacheFull(item.byteSize)) {
454 var sizeToPop = this._sizeToPop(item.byteSize);
455
456 this._popOutItems(validKeys, sizeToPop);
457 }
458 } // put item in the cache
459 // may failed due to storage full
460
461
462 this._setItem(prefixedKey, item);
463 } catch (e) {
464 logger.warn("setItem failed! " + e);
465 }
466 };
467 /**
468 * Get item from cache. It will return null if item doesn’t exist or it has been expired.
469 * If you specified callback function in the options,
470 * then the function will be executed if no such item in the cache
471 * and finally put the return value into cache.
472 * Please make sure the callback function will return the value you want to put into the cache.
473 * The cache will abort output a warning:
474 * If the key is invalid
475 * If error happened with browser storage
476 *
477 * @param key - the key of the item
478 * @param {Object} [options] - the options of callback function
479 *
480 * @return - return the value of the item
481 */
482
483
484 BrowserStorageCacheClass.prototype.getItem = function (key, options) {
485 logger.log("Get item: key is " + key + " with options " + options);
486 var ret = null;
487 var prefixedKey = this.config.keyPrefix + key;
488
489 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
490 logger.warn("Invalid key: should not be empty or 'CurSize'");
491 return null;
492 }
493
494 try {
495 ret = this.config.storage.getItem(prefixedKey);
496
497 if (ret != null) {
498 if (this._isExpired(prefixedKey)) {
499 // if expired, remove that item and return null
500 this._removeItem(prefixedKey, JSON.parse(ret).byteSize);
501
502 ret = null;
503 } else {
504 // if not expired, great, return the value and refresh it
505 var item = JSON.parse(ret);
506 item = this._refreshItem(item, prefixedKey);
507 return item.data;
508 }
509 }
510
511 if (options && options.callback !== undefined) {
512 var val = options.callback();
513
514 if (val !== null) {
515 this.setItem(key, val, options);
516 }
517
518 return val;
519 }
520
521 return null;
522 } catch (e) {
523 logger.warn("getItem failed! " + e);
524 return null;
525 }
526 };
527 /**
528 * remove item from the cache
529 * The cache will abort output a warning:
530 * If error happened with browser storage
531 * @param key - the key of the item
532 */
533
534
535 BrowserStorageCacheClass.prototype.removeItem = function (key) {
536 logger.log("Remove item: key is " + key);
537 var prefixedKey = this.config.keyPrefix + key;
538
539 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
540 return;
541 }
542
543 try {
544 var val = this.config.storage.getItem(prefixedKey);
545
546 if (val) {
547 this._removeItem(prefixedKey, JSON.parse(val).byteSize);
548 }
549 } catch (e) {
550 logger.warn("removeItem failed! " + e);
551 }
552 };
553 /**
554 * clear the entire cache
555 * The cache will abort output a warning:
556 * If error happened with browser storage
557 */
558
559
560 BrowserStorageCacheClass.prototype.clear = function () {
561 logger.log("Clear Cache");
562 var keysToRemove = [];
563
564 for (var i = 0; i < this.config.storage.length; i += 1) {
565 var key = this.config.storage.key(i);
566
567 if (key.indexOf(this.config.keyPrefix) === 0) {
568 keysToRemove.push(key);
569 }
570 }
571
572 try {
573 for (var i = 0; i < keysToRemove.length; i += 1) {
574 this.config.storage.removeItem(keysToRemove[i]);
575 }
576 } catch (e) {
577 logger.warn("clear failed! " + e);
578 }
579 };
580 /**
581 * Return all the keys in the cache.
582 *
583 * @return - all keys in the cache
584 */
585
586
587 BrowserStorageCacheClass.prototype.getAllKeys = function () {
588 var keys = [];
589
590 for (var i = 0; i < this.config.storage.length; i += 1) {
591 var key = this.config.storage.key(i);
592
593 if (key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey) {
594 keys.push(key.substring(this.config.keyPrefix.length));
595 }
596 }
597
598 return keys;
599 };
600 /**
601 * return the current size of the cache
602 *
603 * @return - current size of the cache
604 */
605
606
607 BrowserStorageCacheClass.prototype.getCacheCurSize = function () {
608 var ret = this.config.storage.getItem(this.cacheCurSizeKey);
609
610 if (!ret) {
611 this.config.storage.setItem(this.cacheCurSizeKey, '0');
612 ret = '0';
613 }
614
615 return Number(ret);
616 };
617 /**
618 * Return a new instance of cache with customized configuration.
619 * @param config - the customized configuration
620 *
621 * @return - new instance of Cache
622 */
623
624
625 BrowserStorageCacheClass.prototype.createInstance = function (config) {
626 if (!config.keyPrefix || config.keyPrefix === _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].keyPrefix) {
627 logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
628 config.keyPrefix = _Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"].toString();
629 }
630
631 return new BrowserStorageCacheClass(config);
632 };
633
634 return BrowserStorageCacheClass;
635}(_StorageCache__WEBPACK_IMPORTED_MODULE_1__["StorageCache"]);
636
637
638var BrowserStorageCache = new BrowserStorageCacheClass();
639/**
640 * @deprecated use named import
641 */
642
643/* harmony default export */ __webpack_exports__["default"] = (BrowserStorageCache);
644
645/***/ }),
646
647/***/ "./lib-esm/InMemoryCache.js":
648/*!**********************************!*\
649 !*** ./lib-esm/InMemoryCache.js ***!
650 \**********************************/
651/*! exports provided: InMemoryCacheClass, InMemoryCache, default */
652/***/ (function(module, __webpack_exports__, __webpack_require__) {
653
654"use strict";
655__webpack_require__.r(__webpack_exports__);
656/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InMemoryCacheClass", function() { return InMemoryCacheClass; });
657/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InMemoryCache", function() { return InMemoryCache; });
658/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
659/* harmony import */ var _StorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./StorageCache */ "./lib-esm/StorageCache.js");
660/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
661/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__);
662/*
663 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
664 *
665 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
666 * the License. A copy of the License is located at
667 *
668 * http://aws.amazon.com/apache2.0/
669 *
670 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
671 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
672 * and limitations under the License.
673 */
674var __extends = undefined && undefined.__extends || function () {
675 var _extendStatics = function extendStatics(d, b) {
676 _extendStatics = Object.setPrototypeOf || {
677 __proto__: []
678 } instanceof Array && function (d, b) {
679 d.__proto__ = b;
680 } || function (d, b) {
681 for (var p in b) {
682 if (b.hasOwnProperty(p)) d[p] = b[p];
683 }
684 };
685
686 return _extendStatics(d, b);
687 };
688
689 return function (d, b) {
690 _extendStatics(d, b);
691
692 function __() {
693 this.constructor = d;
694 }
695
696 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
697 };
698}();
699
700var __values = undefined && undefined.__values || function (o) {
701 var s = typeof Symbol === "function" && Symbol.iterator,
702 m = s && o[s],
703 i = 0;
704 if (m) return m.call(o);
705 if (o && typeof o.length === "number") return {
706 next: function next() {
707 if (o && i >= o.length) o = void 0;
708 return {
709 value: o && o[i++],
710 done: !o
711 };
712 }
713 };
714 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
715};
716
717
718
719
720var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__["ConsoleLogger"]('InMemoryCache');
721/**
722 * Customized in-memory cache with LRU implemented
723 * @member cacheObj - object which store items
724 * @member cacheList - list of keys in the cache with LRU
725 * @member curSizeInBytes - current size of the cache
726 * @member maxPriority - max of the priority
727 * @member cacheSizeLimit - the limit of cache size
728 */
729
730var InMemoryCacheClass =
731/** @class */
732function (_super) {
733 __extends(InMemoryCacheClass, _super);
734 /**
735 * initialize the cache
736 *
737 * @param config - the configuration of the cache
738 */
739
740
741 function InMemoryCacheClass(config) {
742 var _this = this;
743
744 var cacheConfig = config ? Object.assign({}, _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"], config) : _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"];
745 _this = _super.call(this, cacheConfig) || this;
746 logger.debug('now we start!');
747 _this.cacheList = [];
748 _this.curSizeInBytes = 0;
749 _this.maxPriority = 5;
750 _this.getItem = _this.getItem.bind(_this);
751 _this.setItem = _this.setItem.bind(_this);
752 _this.removeItem = _this.removeItem.bind(_this); // initialize list for every priority
753
754 for (var i = 0; i < _this.maxPriority; i += 1) {
755 _this.cacheList[i] = new _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheList"]();
756 }
757
758 return _this;
759 }
760 /**
761 * decrease current size of the cache
762 *
763 * @param amount - the amount of the cache size which needs to be decreased
764 */
765
766
767 InMemoryCacheClass.prototype._decreaseCurSizeInBytes = function (amount) {
768 this.curSizeInBytes -= amount;
769 };
770 /**
771 * increase current size of the cache
772 *
773 * @param amount - the amount of the cache szie which need to be increased
774 */
775
776
777 InMemoryCacheClass.prototype._increaseCurSizeInBytes = function (amount) {
778 this.curSizeInBytes += amount;
779 };
780 /**
781 * check whether item is expired
782 *
783 * @param key - the key of the item
784 *
785 * @return true if the item is expired.
786 */
787
788
789 InMemoryCacheClass.prototype._isExpired = function (key) {
790 var text = _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(key);
791 var item = JSON.parse(text);
792
793 if (Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])() >= item.expires) {
794 return true;
795 }
796
797 return false;
798 };
799 /**
800 * delete item from cache
801 *
802 * @param prefixedKey - the key of the item
803 * @param listIdx - indicates which cache list the key belongs to
804 */
805
806
807 InMemoryCacheClass.prototype._removeItem = function (prefixedKey, listIdx) {
808 // delete the key from the list
809 this.cacheList[listIdx].removeItem(prefixedKey); // decrease the current size of the cache
810
811 this._decreaseCurSizeInBytes(JSON.parse(_Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(prefixedKey)).byteSize); // finally remove the item from memory
812
813
814 _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].removeItem(prefixedKey);
815 };
816 /**
817 * put item into cache
818 *
819 * @param prefixedKey - the key of the item
820 * @param itemData - the value of the item
821 * @param itemSizeInBytes - the byte size of the item
822 * @param listIdx - indicates which cache list the key belongs to
823 */
824
825
826 InMemoryCacheClass.prototype._setItem = function (prefixedKey, item, listIdx) {
827 // insert the key into the list
828 this.cacheList[listIdx].insertItem(prefixedKey); // increase the current size of the cache
829
830 this._increaseCurSizeInBytes(item.byteSize); // finally add the item into memory
831
832
833 _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].setItem(prefixedKey, JSON.stringify(item));
834 };
835 /**
836 * see whether cache is full
837 *
838 * @param itemSize
839 *
840 * @return true if cache is full
841 */
842
843
844 InMemoryCacheClass.prototype._isCacheFull = function (itemSize) {
845 return this.curSizeInBytes + itemSize > this.config.capacityInBytes;
846 };
847 /**
848 * check whether the cache contains the key
849 *
850 * @param key
851 */
852
853
854 InMemoryCacheClass.prototype.containsKey = function (key) {
855 var prefixedKey = this.config.keyPrefix + key;
856
857 for (var i = 0; i < this.maxPriority; i += 1) {
858 if (this.cacheList[i].containsKey(prefixedKey)) {
859 return i + 1;
860 }
861 }
862
863 return -1;
864 };
865 /**
866 * * Set item into cache. You can put number, string, boolean or object.
867 * The cache will first check whether has the same key.
868 * If it has, it will delete the old item and then put the new item in
869 * The cache will pop out items if it is full
870 * You can specify the cache item options. The cache will abort and output a warning:
871 * If the key is invalid
872 * If the size of the item exceeds itemMaxSize.
873 * If the value is undefined
874 * If incorrect cache item configuration
875 * If error happened with browser storage
876 *
877 * @param key - the key of the item
878 * @param value - the value of the item
879 * @param options - optional, the specified meta-data
880 *
881 * @throws if the item is too big which exceeds the limit of single item size
882 * @throws if the key is invalid
883 */
884
885
886 InMemoryCacheClass.prototype.setItem = function (key, value, options) {
887 var prefixedKey = this.config.keyPrefix + key; // invalid keys
888
889 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
890 logger.warn("Invalid key: should not be empty or 'CurSize'");
891 return;
892 }
893
894 if (typeof value === 'undefined') {
895 logger.warn("The value of item should not be undefined!");
896 return;
897 }
898
899 var cacheItemOptions = {
900 priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
901 expires: options && options.expires !== undefined ? options.expires : this.config.defaultTTL + Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])()
902 };
903
904 if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
905 logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
906 return;
907 }
908
909 var item = this.fillCacheItem(prefixedKey, value, cacheItemOptions); // check wether this item is too big;
910
911 if (item.byteSize > this.config.itemMaxSize) {
912 logger.warn("Item with key: " + key + " you are trying to put into is too big!");
913 return;
914 } // if key already in the cache, then delete it.
915
916
917 var presentKeyPrio = this.containsKey(key);
918
919 if (presentKeyPrio !== -1) {
920 this._removeItem(prefixedKey, presentKeyPrio - 1);
921 } // pop out items in the cache when cache is full based on LRU
922 // first start from lowest priority cache list
923
924
925 var cacheListIdx = this.maxPriority - 1;
926
927 while (this._isCacheFull(item.byteSize) && cacheListIdx >= 0) {
928 if (!this.cacheList[cacheListIdx].isEmpty()) {
929 var popedItemKey = this.cacheList[cacheListIdx].getLastItem();
930
931 this._removeItem(popedItemKey, cacheListIdx);
932 } else {
933 cacheListIdx -= 1;
934 }
935 }
936
937 this._setItem(prefixedKey, item, Number(item.priority) - 1);
938 };
939 /**
940 * Get item from cache. It will return null if item doesn’t exist or it has been expired.
941 * If you specified callback function in the options,
942 * then the function will be executed if no such item in the cache
943 * and finally put the return value into cache.
944 * Please make sure the callback function will return the value you want to put into the cache.
945 * The cache will abort output a warning:
946 * If the key is invalid
947 *
948 * @param key - the key of the item
949 * @param options - the options of callback function
950 */
951
952
953 InMemoryCacheClass.prototype.getItem = function (key, options) {
954 var ret = null;
955 var prefixedKey = this.config.keyPrefix + key;
956
957 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
958 logger.warn("Invalid key: should not be empty or 'CurSize'");
959 return null;
960 } // check whether it's in the cachelist
961
962
963 var presentKeyPrio = this.containsKey(key);
964
965 if (presentKeyPrio !== -1) {
966 if (this._isExpired(prefixedKey)) {
967 // if expired, remove that item and return null
968 this._removeItem(prefixedKey, presentKeyPrio - 1);
969 } else {
970 // if not expired, great, return the value and refresh it
971 ret = _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(prefixedKey);
972 var item = JSON.parse(ret);
973 this.cacheList[item.priority - 1].refresh(prefixedKey);
974 return item.data;
975 }
976 }
977
978 if (options && options.callback !== undefined) {
979 var val = options.callback();
980
981 if (val !== null) {
982 this.setItem(key, val, options);
983 }
984
985 return val;
986 }
987
988 return null;
989 };
990 /**
991 * remove item from the cache
992 *
993 * @param key - the key of the item
994 */
995
996
997 InMemoryCacheClass.prototype.removeItem = function (key) {
998 var prefixedKey = this.config.keyPrefix + key; // check if the key is in the cache
999
1000 var presentKeyPrio = this.containsKey(key);
1001
1002 if (presentKeyPrio !== -1) {
1003 this._removeItem(prefixedKey, presentKeyPrio - 1);
1004 }
1005 };
1006 /**
1007 * clear the entire cache
1008 */
1009
1010
1011 InMemoryCacheClass.prototype.clear = function () {
1012 var e_1, _a;
1013
1014 for (var i = 0; i < this.maxPriority; i += 1) {
1015 try {
1016 for (var _b = (e_1 = void 0, __values(this.cacheList[i].getKeys())), _c = _b.next(); !_c.done; _c = _b.next()) {
1017 var key = _c.value;
1018
1019 this._removeItem(key, i);
1020 }
1021 } catch (e_1_1) {
1022 e_1 = {
1023 error: e_1_1
1024 };
1025 } finally {
1026 try {
1027 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1028 } finally {
1029 if (e_1) throw e_1.error;
1030 }
1031 }
1032 }
1033 };
1034 /**
1035 * Return all the keys in the cache.
1036 */
1037
1038
1039 InMemoryCacheClass.prototype.getAllKeys = function () {
1040 var e_2, _a;
1041
1042 var keys = [];
1043
1044 for (var i = 0; i < this.maxPriority; i += 1) {
1045 try {
1046 for (var _b = (e_2 = void 0, __values(this.cacheList[i].getKeys())), _c = _b.next(); !_c.done; _c = _b.next()) {
1047 var key = _c.value;
1048 keys.push(key.substring(this.config.keyPrefix.length));
1049 }
1050 } catch (e_2_1) {
1051 e_2 = {
1052 error: e_2_1
1053 };
1054 } finally {
1055 try {
1056 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1057 } finally {
1058 if (e_2) throw e_2.error;
1059 }
1060 }
1061 }
1062
1063 return keys;
1064 };
1065 /**
1066 * return the current size of the cache
1067 *
1068 * @return the current size of the cache
1069 */
1070
1071
1072 InMemoryCacheClass.prototype.getCacheCurSize = function () {
1073 return this.curSizeInBytes;
1074 };
1075 /**
1076 * Return a new instance of cache with customized configuration.
1077 * @param config - the customized configuration
1078 */
1079
1080
1081 InMemoryCacheClass.prototype.createInstance = function (config) {
1082 return new InMemoryCacheClass(config);
1083 };
1084
1085 return InMemoryCacheClass;
1086}(_StorageCache__WEBPACK_IMPORTED_MODULE_1__["StorageCache"]);
1087
1088
1089var InMemoryCache = new InMemoryCacheClass();
1090/**
1091 * @deprecated use named import
1092 */
1093
1094/* harmony default export */ __webpack_exports__["default"] = (InMemoryCache);
1095
1096/***/ }),
1097
1098/***/ "./lib-esm/StorageCache.js":
1099/*!*********************************!*\
1100 !*** ./lib-esm/StorageCache.js ***!
1101 \*********************************/
1102/*! exports provided: StorageCache, default */
1103/***/ (function(module, __webpack_exports__, __webpack_require__) {
1104
1105"use strict";
1106__webpack_require__.r(__webpack_exports__);
1107/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StorageCache", function() { return StorageCache; });
1108/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
1109/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1110/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__);
1111function _typeof(obj) {
1112 "@babel/helpers - typeof";
1113
1114 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
1115 return typeof obj;
1116 } : function (obj) {
1117 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1118 }, _typeof(obj);
1119}
1120/*
1121 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1122 *
1123 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1124 * the License. A copy of the License is located at
1125 *
1126 * http://aws.amazon.com/apache2.0/
1127 *
1128 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1129 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1130 * and limitations under the License.
1131 */
1132
1133
1134
1135
1136var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["ConsoleLogger"]('StorageCache');
1137/**
1138 * Initialization of the cache
1139 *
1140 */
1141
1142var StorageCache =
1143/** @class */
1144function () {
1145 /**
1146 * Initialize the cache
1147 * @param config - the configuration of the cache
1148 */
1149 function StorageCache(config) {
1150 this.config = Object.assign({}, config);
1151 this.cacheCurSizeKey = this.config.keyPrefix + 'CurSize';
1152 this.checkConfig();
1153 }
1154
1155 StorageCache.prototype.getModuleName = function () {
1156 return 'Cache';
1157 };
1158
1159 StorageCache.prototype.checkConfig = function () {
1160 // check configuration
1161 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.capacityInBytes)) {
1162 logger.error('Invalid parameter: capacityInBytes. It should be an Integer. Setting back to default.');
1163 this.config.capacityInBytes = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].capacityInBytes;
1164 }
1165
1166 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.itemMaxSize)) {
1167 logger.error('Invalid parameter: itemMaxSize. It should be an Integer. Setting back to default.');
1168 this.config.itemMaxSize = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].itemMaxSize;
1169 }
1170
1171 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.defaultTTL)) {
1172 logger.error('Invalid parameter: defaultTTL. It should be an Integer. Setting back to default.');
1173 this.config.defaultTTL = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultTTL;
1174 }
1175
1176 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.defaultPriority)) {
1177 logger.error('Invalid parameter: defaultPriority. It should be an Integer. Setting back to default.');
1178 this.config.defaultPriority = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultPriority;
1179 }
1180
1181 if (this.config.itemMaxSize > this.config.capacityInBytes) {
1182 logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');
1183 this.config.itemMaxSize = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].itemMaxSize;
1184 }
1185
1186 if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {
1187 logger.error('Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.');
1188 this.config.defaultPriority = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultPriority;
1189 }
1190
1191 if (Number(this.config.warningThreshold) > 1 || Number(this.config.warningThreshold) < 0) {
1192 logger.error('Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.');
1193 this.config.warningThreshold = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].warningThreshold;
1194 } // set 5MB limit
1195
1196
1197 var cacheLimit = 5 * 1024 * 1024;
1198
1199 if (this.config.capacityInBytes > cacheLimit) {
1200 logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');
1201 this.config.capacityInBytes = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].capacityInBytes;
1202 }
1203 };
1204 /**
1205 * produce a JSON object with meta-data and data value
1206 * @param value - the value of the item
1207 * @param options - optional, the specified meta-data
1208 *
1209 * @return - the item which has the meta-data and the value
1210 */
1211
1212
1213 StorageCache.prototype.fillCacheItem = function (key, value, options) {
1214 var ret = {
1215 key: key,
1216 data: value,
1217 timestamp: Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])(),
1218 visitedTime: Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])(),
1219 priority: options.priority,
1220 expires: options.expires,
1221 type: _typeof(value),
1222 byteSize: 0
1223 };
1224 ret.byteSize = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"])(JSON.stringify(ret)); // for accurate size
1225
1226 ret.byteSize = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"])(JSON.stringify(ret));
1227 return ret;
1228 };
1229 /**
1230 * set cache with customized configuration
1231 * @param config - customized configuration
1232 *
1233 * @return - the current configuration
1234 */
1235
1236
1237 StorageCache.prototype.configure = function (config) {
1238 if (!config) {
1239 return this.config;
1240 }
1241
1242 if (config.keyPrefix) {
1243 logger.warn("Don't try to configure keyPrefix!");
1244 }
1245
1246 this.config = Object.assign({}, this.config, config, config.Cache);
1247 this.checkConfig();
1248 return this.config;
1249 };
1250
1251 return StorageCache;
1252}();
1253
1254
1255/**
1256 * @deprecated use named import
1257 */
1258
1259/* harmony default export */ __webpack_exports__["default"] = (StorageCache);
1260
1261/***/ }),
1262
1263/***/ "./lib-esm/Utils/CacheList.js":
1264/*!************************************!*\
1265 !*** ./lib-esm/Utils/CacheList.js ***!
1266 \************************************/
1267/*! exports provided: default */
1268/***/ (function(module, __webpack_exports__, __webpack_require__) {
1269
1270"use strict";
1271__webpack_require__.r(__webpack_exports__);
1272/*
1273 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1274 *
1275 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1276 * the License. A copy of the License is located at
1277 *
1278 * http://aws.amazon.com/apache2.0/
1279 *
1280 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1281 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1282 * and limitations under the License.
1283 */
1284var __values = undefined && undefined.__values || function (o) {
1285 var s = typeof Symbol === "function" && Symbol.iterator,
1286 m = s && o[s],
1287 i = 0;
1288 if (m) return m.call(o);
1289 if (o && typeof o.length === "number") return {
1290 next: function next() {
1291 if (o && i >= o.length) o = void 0;
1292 return {
1293 value: o && o[i++],
1294 done: !o
1295 };
1296 }
1297 };
1298 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1299};
1300
1301var DoubleLinkedNode =
1302/** @class */
1303function () {
1304 function DoubleLinkedNode(keyVal) {
1305 this.key = keyVal ? keyVal : '';
1306 this.prevNode = null;
1307 this.nextNode = null;
1308 }
1309
1310 return DoubleLinkedNode;
1311}();
1312/**
1313 * double linked list plus a hash table inside
1314 * each key in the cache stored as a node in the list
1315 * recently visited node will be rotated to the head
1316 * so the Last Recently Visited node will be at the tail
1317 *
1318 * @member head - dummy head of the linked list
1319 * @member tail - dummy tail of the linked list
1320 * @member hashtable - the hashtable which maps cache key to list node
1321 * @member length - length of the list
1322 */
1323
1324
1325var CacheList =
1326/** @class */
1327function () {
1328 /**
1329 * initialization
1330 */
1331 function CacheList() {
1332 this.head = new DoubleLinkedNode();
1333 this.tail = new DoubleLinkedNode();
1334 this.hashtable = {};
1335 this.length = 0;
1336 this.head.nextNode = this.tail;
1337 this.tail.prevNode = this.head;
1338 }
1339 /**
1340 * insert node to the head of the list
1341 *
1342 * @param node
1343 */
1344
1345
1346 CacheList.prototype.insertNodeToHead = function (node) {
1347 var tmp = this.head.nextNode;
1348 this.head.nextNode = node;
1349 node.nextNode = tmp;
1350 node.prevNode = this.head;
1351 tmp.prevNode = node;
1352 this.length = this.length + 1;
1353 };
1354 /**
1355 * remove node
1356 *
1357 * @param node
1358 */
1359
1360
1361 CacheList.prototype.removeNode = function (node) {
1362 node.prevNode.nextNode = node.nextNode;
1363 node.nextNode.prevNode = node.prevNode;
1364 node.prevNode = null;
1365 node.nextNode = null;
1366 this.length = this.length - 1;
1367 };
1368 /**
1369 * @return true if list is empty
1370 */
1371
1372
1373 CacheList.prototype.isEmpty = function () {
1374 return this.length === 0;
1375 };
1376 /**
1377 * refresh node so it is rotated to the head
1378 *
1379 * @param key - key of the node
1380 */
1381
1382
1383 CacheList.prototype.refresh = function (key) {
1384 var node = this.hashtable[key];
1385 this.removeNode(node);
1386 this.insertNodeToHead(node);
1387 };
1388 /**
1389 * insert new node to the head and add it in the hashtable
1390 *
1391 * @param key - the key of the node
1392 */
1393
1394
1395 CacheList.prototype.insertItem = function (key) {
1396 var node = new DoubleLinkedNode(key);
1397 this.hashtable[key] = node;
1398 this.insertNodeToHead(node);
1399 };
1400 /**
1401 * @return the LAST Recently Visited key
1402 */
1403
1404
1405 CacheList.prototype.getLastItem = function () {
1406 return this.tail.prevNode.key;
1407 };
1408 /**
1409 * remove the cache key from the list and hashtable
1410 * @param key - the key of the node
1411 */
1412
1413
1414 CacheList.prototype.removeItem = function (key) {
1415 var removedItem = this.hashtable[key];
1416 this.removeNode(removedItem);
1417 delete this.hashtable[key];
1418 };
1419 /**
1420 * @return length of the list
1421 */
1422
1423
1424 CacheList.prototype.getSize = function () {
1425 return this.length;
1426 };
1427 /**
1428 * @return true if the key is in the hashtable
1429 * @param key
1430 */
1431
1432
1433 CacheList.prototype.containsKey = function (key) {
1434 return key in this.hashtable;
1435 };
1436 /**
1437 * clean up the list and hashtable
1438 */
1439
1440
1441 CacheList.prototype.clearList = function () {
1442 var e_1, _a;
1443
1444 try {
1445 for (var _b = __values(Object.keys(this.hashtable)), _c = _b.next(); !_c.done; _c = _b.next()) {
1446 var key = _c.value;
1447
1448 if (this.hashtable.hasOwnProperty(key)) {
1449 delete this.hashtable[key];
1450 }
1451 }
1452 } catch (e_1_1) {
1453 e_1 = {
1454 error: e_1_1
1455 };
1456 } finally {
1457 try {
1458 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1459 } finally {
1460 if (e_1) throw e_1.error;
1461 }
1462 }
1463
1464 this.head.nextNode = this.tail;
1465 this.tail.prevNode = this.head;
1466 this.length = 0;
1467 };
1468 /**
1469 * @return all keys in the hashtable
1470 */
1471
1472
1473 CacheList.prototype.getKeys = function () {
1474 return Object.keys(this.hashtable);
1475 };
1476 /**
1477 * mainly for test
1478 *
1479 * @param key
1480 * @return true if key is the head node
1481 */
1482
1483
1484 CacheList.prototype.isHeadNode = function (key) {
1485 var node = this.hashtable[key];
1486 return node.prevNode === this.head;
1487 };
1488 /**
1489 * mainly for test
1490 *
1491 * @param key
1492 * @return true if key is the tail node
1493 */
1494
1495
1496 CacheList.prototype.isTailNode = function (key) {
1497 var node = this.hashtable[key];
1498 return node.nextNode === this.tail;
1499 };
1500
1501 return CacheList;
1502}();
1503
1504/* harmony default export */ __webpack_exports__["default"] = (CacheList);
1505
1506/***/ }),
1507
1508/***/ "./lib-esm/Utils/CacheUtils.js":
1509/*!*************************************!*\
1510 !*** ./lib-esm/Utils/CacheUtils.js ***!
1511 \*************************************/
1512/*! exports provided: defaultConfig, getByteLength, getCurrTime, isInteger, CacheObject */
1513/***/ (function(module, __webpack_exports__, __webpack_require__) {
1514
1515"use strict";
1516__webpack_require__.r(__webpack_exports__);
1517/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultConfig", function() { return defaultConfig; });
1518/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getByteLength", function() { return getByteLength; });
1519/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCurrTime", function() { return getCurrTime; });
1520/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteger", function() { return isInteger; });
1521/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CacheObject", function() { return CacheObject; });
1522/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1523/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
1524/*
1525 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1526 *
1527 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1528 * the License. A copy of the License is located at
1529 *
1530 * http://aws.amazon.com/apache2.0/
1531 *
1532 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1533 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1534 * and limitations under the License.
1535 */
1536
1537/**
1538 * Default cache config
1539 */
1540
1541var defaultConfig = {
1542 keyPrefix: 'aws-amplify-cache',
1543 capacityInBytes: 1048576,
1544 itemMaxSize: 210000,
1545 defaultTTL: 259200000,
1546 defaultPriority: 5,
1547 warningThreshold: 0.8,
1548 // the storage helper will check if localStorage exists,
1549 // if not, will use a in-memory object instead
1550 storage: new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["StorageHelper"]().getStorage()
1551};
1552/**
1553 * return the byte size of the string
1554 * @param str
1555 */
1556
1557function getByteLength(str) {
1558 var ret = 0;
1559 ret = str.length;
1560
1561 for (var i = str.length; i >= 0; i -= 1) {
1562 var charCode = str.charCodeAt(i);
1563
1564 if (charCode > 0x7f && charCode <= 0x7ff) {
1565 ret += 1;
1566 } else if (charCode > 0x7ff && charCode <= 0xffff) {
1567 ret += 2;
1568 } // trail surrogate
1569
1570
1571 if (charCode >= 0xdc00 && charCode <= 0xdfff) {
1572 i -= 1;
1573 }
1574 }
1575
1576 return ret;
1577}
1578/**
1579 * get current time
1580 */
1581
1582function getCurrTime() {
1583 var currTime = new Date();
1584 return currTime.getTime();
1585}
1586/**
1587 * check if passed value is an integer
1588 */
1589
1590function isInteger(value) {
1591 if (Number.isInteger) {
1592 return Number.isInteger(value);
1593 }
1594
1595 return _isInteger(value);
1596}
1597
1598function _isInteger(value) {
1599 return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
1600}
1601/**
1602 * provide an object as the in-memory cache
1603 */
1604
1605
1606var store = {};
1607
1608var CacheObject =
1609/** @class */
1610function () {
1611 function CacheObject() {}
1612
1613 CacheObject.clear = function () {
1614 store = {};
1615 };
1616
1617 CacheObject.getItem = function (key) {
1618 return store[key] || null;
1619 };
1620
1621 CacheObject.setItem = function (key, value) {
1622 store[key] = value;
1623 };
1624
1625 CacheObject.removeItem = function (key) {
1626 delete store[key];
1627 };
1628
1629 return CacheObject;
1630}();
1631
1632
1633
1634/***/ }),
1635
1636/***/ "./lib-esm/Utils/index.js":
1637/*!********************************!*\
1638 !*** ./lib-esm/Utils/index.js ***!
1639 \********************************/
1640/*! exports provided: defaultConfig, getByteLength, getCurrTime, isInteger, CacheObject, CacheList */
1641/***/ (function(module, __webpack_exports__, __webpack_require__) {
1642
1643"use strict";
1644__webpack_require__.r(__webpack_exports__);
1645/* harmony import */ var _CacheUtils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CacheUtils */ "./lib-esm/Utils/CacheUtils.js");
1646/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultConfig", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"]; });
1647
1648/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getByteLength", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"]; });
1649
1650/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getCurrTime", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"]; });
1651
1652/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isInteger", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["isInteger"]; });
1653
1654/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CacheObject", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"]; });
1655
1656/* harmony import */ var _CacheList__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CacheList */ "./lib-esm/Utils/CacheList.js");
1657/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CacheList", function() { return _CacheList__WEBPACK_IMPORTED_MODULE_1__["default"]; });
1658
1659/*
1660 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1661 *
1662 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1663 * the License. A copy of the License is located at
1664 *
1665 * http://aws.amazon.com/apache2.0/
1666 *
1667 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1668 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1669 * and limitations under the License.
1670 */
1671
1672
1673
1674/***/ }),
1675
1676/***/ "./lib-esm/index.js":
1677/*!**************************!*\
1678 !*** ./lib-esm/index.js ***!
1679 \**************************/
1680/*! exports provided: BrowserStorageCache, InMemoryCache, default */
1681/***/ (function(module, __webpack_exports__, __webpack_require__) {
1682
1683"use strict";
1684__webpack_require__.r(__webpack_exports__);
1685/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1686/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
1687/* harmony import */ var _BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BrowserStorageCache */ "./lib-esm/BrowserStorageCache.js");
1688/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCache", function() { return _BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]; });
1689
1690/* harmony import */ var _InMemoryCache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./InMemoryCache */ "./lib-esm/InMemoryCache.js");
1691/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InMemoryCache", function() { return _InMemoryCache__WEBPACK_IMPORTED_MODULE_2__["InMemoryCache"]; });
1692
1693/*
1694 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1695 *
1696 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1697 * the License. A copy of the License is located at
1698 *
1699 * http://aws.amazon.com/apache2.0/
1700 *
1701 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1702 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1703 * and limitations under the License.
1704 */
1705
1706
1707
1708
1709/**
1710 * @deprecated use named import
1711 */
1712
1713/* harmony default export */ __webpack_exports__["default"] = (_BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]);
1714_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["Amplify"].register(_BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]);
1715
1716/***/ }),
1717
1718/***/ "@aws-amplify/core":
1719/*!***********************************!*\
1720 !*** external "aws_amplify_core" ***!
1721 \***********************************/
1722/*! no static exports found */
1723/***/ (function(module, exports) {
1724
1725module.exports = __WEBPACK_EXTERNAL_MODULE__aws_amplify_core__;
1726
1727/***/ })
1728
1729/******/ });
1730});
1731//# sourceMappingURL=aws-amplify-cache.js.map
\No newline at end of file