ngx-webstorage
Version:
This library provides an easy to use service to manage the web storages (local and session) from your Angular application. It provides also two decorators to synchronize the component attributes and the web storages.
973 lines (939 loc) • 41.8 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('rxjs/operators'), require('@angular/core'), require('rxjs'), require('@angular/common')) :
typeof define === 'function' && define.amd ? define('ngx-webstorage', ['exports', 'rxjs/operators', '@angular/core', 'rxjs', '@angular/common'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['ngx-webstorage'] = {}, global.rxjs.operators, global.ng.core, global.rxjs, global.ng.common));
}(this, (function (exports, operators, i0, rxjs, common) { 'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var i0__namespace = /*#__PURE__*/_interopNamespace(i0);
exports.StorageStrategies = void 0;
(function (StorageStrategies) {
StorageStrategies["Local"] = "local_strategy";
StorageStrategies["Session"] = "session_strategy";
StorageStrategies["InMemory"] = "in_memory_strategy";
})(exports.StorageStrategies || (exports.StorageStrategies = {}));
var CompatHelper = /** @class */ (function () {
function CompatHelper() {
}
CompatHelper.isStorageAvailable = function (storage) {
var available = true;
try {
if (typeof storage === 'object') {
storage.setItem('test-storage', 'foobar');
storage.removeItem('test-storage');
}
else
available = false;
}
catch (e) {
available = false;
}
return available;
};
return CompatHelper;
}());
function noop() { }
var DefaultPrefix = 'ngx-webstorage';
var DefaultSeparator = '|';
var DefaultIsCaseSensitive = false;
var StorageKeyManager = /** @class */ (function () {
function StorageKeyManager() {
}
StorageKeyManager.normalize = function (raw) {
raw = StorageKeyManager.isCaseSensitive ? raw : raw.toLowerCase();
return "" + StorageKeyManager.prefix + StorageKeyManager.separator + raw;
};
StorageKeyManager.isNormalizedKey = function (key) {
return key.indexOf(StorageKeyManager.prefix + StorageKeyManager.separator) === 0;
};
StorageKeyManager.setPrefix = function (prefix) {
StorageKeyManager.prefix = prefix;
};
StorageKeyManager.setSeparator = function (separator) {
StorageKeyManager.separator = separator;
};
StorageKeyManager.setCaseSensitive = function (enable) {
StorageKeyManager.isCaseSensitive = enable;
};
StorageKeyManager.consumeConfiguration = function (config) {
if ('prefix' in config)
this.setPrefix(config.prefix);
if ('separator' in config)
this.setSeparator(config.separator);
if ('caseSensitive' in config)
this.setCaseSensitive(config.caseSensitive);
};
return StorageKeyManager;
}());
StorageKeyManager.prefix = DefaultPrefix;
StorageKeyManager.separator = DefaultSeparator;
StorageKeyManager.isCaseSensitive = DefaultIsCaseSensitive;
var SyncStorage = /** @class */ (function () {
function SyncStorage(strategy) {
this.strategy = strategy;
}
SyncStorage.prototype.retrieve = function (key) {
var value;
this.strategy.get(StorageKeyManager.normalize(key)).subscribe(function (result) { return value = typeof result === 'undefined' ? null : result; });
return value;
};
SyncStorage.prototype.store = function (key, value) {
this.strategy.set(StorageKeyManager.normalize(key), value).subscribe(noop);
return value;
};
SyncStorage.prototype.clear = function (key) {
if (key !== undefined)
this.strategy.del(StorageKeyManager.normalize(key)).subscribe(noop);
else
this.strategy.clear().subscribe(noop);
};
SyncStorage.prototype.getStrategyName = function () { return this.strategy.name; };
SyncStorage.prototype.observe = function (key) {
var _this = this;
key = StorageKeyManager.normalize(key);
return this.strategy.keyChanges.pipe(operators.filter(function (changed) { return changed === null || changed === key; }), operators.switchMap(function () { return _this.strategy.get(key); }), operators.distinctUntilChanged(), operators.shareReplay());
};
return SyncStorage;
}());
var AsyncStorage = /** @class */ (function () {
function AsyncStorage(strategy) {
this.strategy = strategy;
}
AsyncStorage.prototype.retrieve = function (key) {
return this.strategy.get(StorageKeyManager.normalize(key)).pipe(operators.map(function (value) { return typeof value === 'undefined' ? null : value; }));
};
AsyncStorage.prototype.store = function (key, value) {
return this.strategy.set(StorageKeyManager.normalize(key), value);
};
AsyncStorage.prototype.clear = function (key) {
return key !== undefined ? this.strategy.del(StorageKeyManager.normalize(key)) : this.strategy.clear();
};
AsyncStorage.prototype.getStrategyName = function () { return this.strategy.name; };
AsyncStorage.prototype.observe = function (key) {
var _this = this;
key = StorageKeyManager.normalize(key);
return this.strategy.keyChanges.pipe(operators.filter(function (changed) { return changed === null || changed === key; }), operators.switchMap(function () { return _this.strategy.get(key); }), operators.distinctUntilChanged(), operators.shareReplay());
};
return AsyncStorage;
}());
var StrategyCacheService = /** @class */ (function () {
function StrategyCacheService() {
this.caches = {};
}
StrategyCacheService.prototype.get = function (strategyName, key) {
return this.getCacheStore(strategyName)[key];
};
StrategyCacheService.prototype.set = function (strategyName, key, value) {
this.getCacheStore(strategyName)[key] = value;
};
StrategyCacheService.prototype.del = function (strategyName, key) {
delete this.getCacheStore(strategyName)[key];
};
StrategyCacheService.prototype.clear = function (strategyName) {
this.caches[strategyName] = {};
};
StrategyCacheService.prototype.getCacheStore = function (strategyName) {
if (strategyName in this.caches)
return this.caches[strategyName];
return this.caches[strategyName] = {};
};
return StrategyCacheService;
}());
StrategyCacheService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function StrategyCacheService_Factory() { return new StrategyCacheService(); }, token: StrategyCacheService, providedIn: "root" });
StrategyCacheService.decorators = [
{ type: i0.Injectable, args: [{ providedIn: 'root' },] }
];
var LOCAL_STORAGE = new i0.InjectionToken('window_local_storage');
function getLocalStorage() {
return (typeof window !== 'undefined') ? window.localStorage : null;
}
var LocalStorageProvider = { provide: LOCAL_STORAGE, useFactory: getLocalStorage };
var SESSION_STORAGE = new i0.InjectionToken('window_session_storage');
function getSessionStorage() {
return (typeof window !== 'undefined') ? window.sessionStorage : null;
}
var SessionStorageProvider = { provide: SESSION_STORAGE, useFactory: getSessionStorage };
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
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;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
}) : (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
__createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
var __setModuleDefault = Object.create ? (function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function (o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m")
throw new TypeError("Private method is not writable");
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
var BaseSyncStorageStrategy = /** @class */ (function () {
function BaseSyncStorageStrategy(storage, cache) {
this.storage = storage;
this.cache = cache;
this.keyChanges = new rxjs.Subject();
}
Object.defineProperty(BaseSyncStorageStrategy.prototype, "isAvailable", {
get: function () {
if (this._isAvailable === undefined)
this._isAvailable = CompatHelper.isStorageAvailable(this.storage);
return this._isAvailable;
},
enumerable: false,
configurable: true
});
BaseSyncStorageStrategy.prototype.get = function (key) {
var data = this.cache.get(this.name, key);
if (data !== undefined)
return rxjs.of(data);
try {
var item = this.storage.getItem(key);
if (item !== null) {
data = JSON.parse(item);
this.cache.set(this.name, key, data);
}
}
catch (err) {
console.warn(err);
}
return rxjs.of(data);
};
BaseSyncStorageStrategy.prototype.set = function (key, value) {
var data = JSON.stringify(value);
this.storage.setItem(key, data);
this.cache.set(this.name, key, value);
this.keyChanges.next(key);
return rxjs.of(value);
};
BaseSyncStorageStrategy.prototype.del = function (key) {
this.storage.removeItem(key);
this.cache.del(this.name, key);
this.keyChanges.next(key);
return rxjs.of(null);
};
BaseSyncStorageStrategy.prototype.clear = function () {
this.storage.clear();
this.cache.clear(this.name);
this.keyChanges.next(null);
return rxjs.of(null);
};
return BaseSyncStorageStrategy;
}());
var LocalStorageStrategy = /** @class */ (function (_super) {
__extends(LocalStorageStrategy, _super);
function LocalStorageStrategy(storage, cache, platformId, zone) {
var _this = _super.call(this, storage, cache) || this;
_this.storage = storage;
_this.cache = cache;
_this.platformId = platformId;
_this.zone = zone;
_this.name = LocalStorageStrategy.strategyName;
if (common.isPlatformBrowser(_this.platformId))
_this.listenExternalChanges();
return _this;
}
LocalStorageStrategy.prototype.listenExternalChanges = function () {
var _this = this;
window.addEventListener('storage', function (event) { return _this.zone.run(function () {
if (event.storageArea !== _this.storage)
return;
var key = event.key;
if (key !== null)
_this.cache.del(_this.name, event.key);
else
_this.cache.clear(_this.name);
_this.keyChanges.next(key);
}); });
};
return LocalStorageStrategy;
}(BaseSyncStorageStrategy));
LocalStorageStrategy.strategyName = exports.StorageStrategies.Local;
LocalStorageStrategy.decorators = [
{ type: i0.Injectable }
];
LocalStorageStrategy.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: i0.Inject, args: [LOCAL_STORAGE,] }] },
{ type: StrategyCacheService },
{ type: undefined, decorators: [{ type: i0.Inject, args: [i0.PLATFORM_ID,] }] },
{ type: i0.NgZone }
]; };
var SessionStorageStrategy = /** @class */ (function (_super) {
__extends(SessionStorageStrategy, _super);
function SessionStorageStrategy(storage, cache, platformId, zone) {
var _this = _super.call(this, storage, cache) || this;
_this.storage = storage;
_this.cache = cache;
_this.platformId = platformId;
_this.zone = zone;
_this.name = SessionStorageStrategy.strategyName;
if (common.isPlatformBrowser(_this.platformId))
_this.listenExternalChanges();
return _this;
}
SessionStorageStrategy.prototype.listenExternalChanges = function () {
var _this = this;
window.addEventListener('storage', function (event) { return _this.zone.run(function () {
if (event.storageArea !== _this.storage)
return;
var key = event.key;
if (event.key !== null)
_this.cache.del(_this.name, event.key);
else
_this.cache.clear(_this.name);
_this.keyChanges.next(key);
}); });
};
return SessionStorageStrategy;
}(BaseSyncStorageStrategy));
SessionStorageStrategy.strategyName = exports.StorageStrategies.Session;
SessionStorageStrategy.decorators = [
{ type: i0.Injectable }
];
SessionStorageStrategy.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: i0.Inject, args: [SESSION_STORAGE,] }] },
{ type: StrategyCacheService },
{ type: undefined, decorators: [{ type: i0.Inject, args: [i0.PLATFORM_ID,] }] },
{ type: i0.NgZone }
]; };
var InMemoryStorageStrategy = /** @class */ (function () {
function InMemoryStorageStrategy(cache) {
this.cache = cache;
this.keyChanges = new rxjs.Subject();
this.isAvailable = true;
this.name = InMemoryStorageStrategy.strategyName;
}
InMemoryStorageStrategy.prototype.get = function (key) {
return rxjs.of(this.cache.get(this.name, key));
};
InMemoryStorageStrategy.prototype.set = function (key, value) {
this.cache.set(this.name, key, value);
this.keyChanges.next(key);
return rxjs.of(value);
};
InMemoryStorageStrategy.prototype.del = function (key) {
this.cache.del(this.name, key);
this.keyChanges.next(key);
return rxjs.of(null);
};
InMemoryStorageStrategy.prototype.clear = function () {
this.cache.clear(this.name);
this.keyChanges.next(null);
return rxjs.of(null);
};
return InMemoryStorageStrategy;
}());
InMemoryStorageStrategy.strategyName = exports.StorageStrategies.InMemory;
InMemoryStorageStrategy.decorators = [
{ type: i0.Injectable }
];
InMemoryStorageStrategy.ctorParameters = function () { return [
{ type: StrategyCacheService, decorators: [{ type: i0.Inject, args: [StrategyCacheService,] }] }
]; };
var STORAGE_STRATEGIES = new i0.InjectionToken('STORAGE_STRATEGIES');
var Strategies = [
{ provide: STORAGE_STRATEGIES, useClass: InMemoryStorageStrategy, multi: true },
{ provide: STORAGE_STRATEGIES, useClass: LocalStorageStrategy, multi: true },
{ provide: STORAGE_STRATEGIES, useClass: SessionStorageStrategy, multi: true },
];
var StorageStrategyStubName = 'stub_strategy';
var StorageStrategyStub = /** @class */ (function () {
function StorageStrategyStub(name) {
this.keyChanges = new rxjs.Subject();
this.store = {};
this._available = true;
this.name = name || StorageStrategyStubName;
}
Object.defineProperty(StorageStrategyStub.prototype, "isAvailable", {
get: function () {
return this._available;
},
enumerable: false,
configurable: true
});
StorageStrategyStub.prototype.get = function (key) {
return rxjs.of(this.store[key]);
};
StorageStrategyStub.prototype.set = function (key, value) {
this.store[key] = value;
this.keyChanges.next(key);
return rxjs.of(value);
};
StorageStrategyStub.prototype.del = function (key) {
delete this.store[key];
this.keyChanges.next(key);
return rxjs.of(null);
};
StorageStrategyStub.prototype.clear = function () {
this.store = {};
this.keyChanges.next(null);
return rxjs.of(null);
};
return StorageStrategyStub;
}());
var StorageStub = /** @class */ (function () {
function StorageStub() {
this.store = {};
}
Object.defineProperty(StorageStub.prototype, "length", {
get: function () {
return Object.keys(this.store).length;
},
enumerable: false,
configurable: true
});
StorageStub.prototype.clear = function () {
this.store = {};
};
StorageStub.prototype.getItem = function (key) {
return this.store[key] || null;
};
StorageStub.prototype.key = function (index) {
return Object.keys(this.store)[index];
};
StorageStub.prototype.removeItem = function (key) {
delete this.store[key];
};
StorageStub.prototype.setItem = function (key, value) {
this.store[key] = value;
};
return StorageStub;
}());
var InvalidStrategyError = 'invalid_strategy';
var StrategyIndex = /** @class */ (function () {
function StrategyIndex(strategies) {
this.strategies = strategies;
this.registration$ = new rxjs.Subject();
if (!strategies)
strategies = [];
this.strategies = strategies.reverse()
.map(function (strategy, index, arr) { return strategy.name; })
.map(function (name, index, arr) { return arr.indexOf(name) === index ? index : null; })
.filter(function (index) { return index !== null; })
.map(function (index) { return strategies[index]; });
}
StrategyIndex.get = function (name) {
if (!this.isStrategyRegistered(name))
throw Error(InvalidStrategyError);
var strategy = this.index[name];
if (!strategy.isAvailable) {
strategy = this.index[exports.StorageStrategies.InMemory];
}
return strategy;
};
StrategyIndex.set = function (name, strategy) {
this.index[name] = strategy;
};
StrategyIndex.clear = function (name) {
if (name !== undefined)
delete this.index[name];
else
this.index = {};
};
StrategyIndex.isStrategyRegistered = function (name) {
return name in this.index;
};
StrategyIndex.hasRegistredStrategies = function () {
return Object.keys(this.index).length > 0;
};
StrategyIndex.prototype.getStrategy = function (name) {
return StrategyIndex.get(name);
};
StrategyIndex.prototype.indexStrategies = function () {
var _this = this;
this.strategies.forEach(function (strategy) { return _this.register(strategy.name, strategy); });
};
StrategyIndex.prototype.indexStrategy = function (name, overrideIfExists) {
if (overrideIfExists === void 0) { overrideIfExists = false; }
if (StrategyIndex.isStrategyRegistered(name) && !overrideIfExists)
return StrategyIndex.get(name);
var strategy = this.strategies.find(function (strategy) { return strategy.name === name; });
if (!strategy)
throw new Error(InvalidStrategyError);
this.register(name, strategy, overrideIfExists);
return strategy;
};
StrategyIndex.prototype.register = function (name, strategy, overrideIfExists) {
if (overrideIfExists === void 0) { overrideIfExists = false; }
if (!StrategyIndex.isStrategyRegistered(name) || overrideIfExists) {
StrategyIndex.set(name, strategy);
this.registration$.next(name);
}
};
return StrategyIndex;
}());
StrategyIndex.index = {};
StrategyIndex.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function StrategyIndex_Factory() { return new StrategyIndex(i0__namespace.ɵɵinject(STORAGE_STRATEGIES, 8)); }, token: StrategyIndex, providedIn: "root" });
StrategyIndex.decorators = [
{ type: i0.Injectable, args: [{ providedIn: 'root' },] }
];
StrategyIndex.ctorParameters = function () { return [
{ type: Array, decorators: [{ type: i0.Optional }, { type: i0.Inject, args: [STORAGE_STRATEGIES,] }] }
]; };
var LocalStorageService = /** @class */ (function (_super) {
__extends(LocalStorageService, _super);
function LocalStorageService() {
return _super !== null && _super.apply(this, arguments) || this;
}
return LocalStorageService;
}(SyncStorage));
function buildService$1(index) {
var strategy = index.indexStrategy(exports.StorageStrategies.Local);
return new SyncStorage(strategy);
}
var LocalStorageServiceProvider = {
provide: LocalStorageService,
useFactory: buildService$1,
deps: [StrategyIndex]
};
var SessionStorageService = /** @class */ (function (_super) {
__extends(SessionStorageService, _super);
function SessionStorageService() {
return _super !== null && _super.apply(this, arguments) || this;
}
return SessionStorageService;
}(SyncStorage));
function buildService(index) {
var strategy = index.indexStrategy(exports.StorageStrategies.Session);
return new SyncStorage(strategy);
}
var SessionStorageServiceProvider = {
provide: SessionStorageService,
useFactory: buildService,
deps: [StrategyIndex]
};
var DecoratorBuilder = /** @class */ (function () {
function DecoratorBuilder() {
}
DecoratorBuilder.buildSyncStrategyDecorator = function (strategyName, prototype, propName, key, defaultValue) {
if (defaultValue === void 0) { defaultValue = null; }
var rawKey = key || propName;
var storageKey;
Object.defineProperty(prototype, propName, {
get: function () {
var value;
StrategyIndex.get(strategyName).get(getKey()).subscribe(function (result) { return value = result; });
return value === undefined ? defaultValue : value;
},
set: function (value) {
StrategyIndex.get(strategyName).set(getKey(), value).subscribe(noop);
}
});
function getKey() {
if (storageKey !== undefined)
return storageKey;
return storageKey = StorageKeyManager.normalize(rawKey);
}
};
return DecoratorBuilder;
}());
function LocalStorage(key, defaultValue) {
return function (prototype, propName) {
DecoratorBuilder.buildSyncStrategyDecorator(exports.StorageStrategies.Local, prototype, propName, key, defaultValue);
};
}
function SessionStorage(key, defaultValue) {
return function (prototype, propName) {
DecoratorBuilder.buildSyncStrategyDecorator(exports.StorageStrategies.Session, prototype, propName, key, defaultValue);
};
}
var Services = [
LocalStorageServiceProvider,
SessionStorageServiceProvider
];
var LIB_CONFIG = new i0.InjectionToken('ngx_webstorage_config');
function appInit(index) {
index.indexStrategies();
return function () { return StrategyIndex.index; };
}
var NgxWebstorageModule = /** @class */ (function () {
function NgxWebstorageModule(index, config) {
if (config)
StorageKeyManager.consumeConfiguration(config);
else
console.error('NgxWebstorage : Possible misconfiguration (The forRoot method usage is mandatory since the 3.0.0)');
}
NgxWebstorageModule.forRoot = function (config) {
if (config === void 0) { config = {}; }
return {
ngModule: NgxWebstorageModule,
providers: __spreadArray(__spreadArray(__spreadArray([
{
provide: LIB_CONFIG,
useValue: config,
},
LocalStorageProvider,
SessionStorageProvider
], __read(Services)), __read(Strategies)), [
{
provide: i0.APP_INITIALIZER,
useFactory: appInit,
deps: [StrategyIndex],
multi: true
}
])
};
};
return NgxWebstorageModule;
}());
NgxWebstorageModule.decorators = [
{ type: i0.NgModule, args: [{},] }
];
NgxWebstorageModule.ctorParameters = function () { return [
{ type: StrategyIndex },
{ type: undefined, decorators: [{ type: i0.Optional }, { type: i0.Inject, args: [LIB_CONFIG,] }] }
]; };
/*
* Public API Surface of ngx-webstorage
*/
/**
* Generated bundle index. Do not edit.
*/
exports.AsyncStorage = AsyncStorage;
exports.CompatHelper = CompatHelper;
exports.InMemoryStorageStrategy = InMemoryStorageStrategy;
exports.InvalidStrategyError = InvalidStrategyError;
exports.LIB_CONFIG = LIB_CONFIG;
exports.LOCAL_STORAGE = LOCAL_STORAGE;
exports.LocalStorage = LocalStorage;
exports.LocalStorageService = LocalStorageService;
exports.LocalStorageStrategy = LocalStorageStrategy;
exports.NgxWebstorageModule = NgxWebstorageModule;
exports.SESSION_STORAGE = SESSION_STORAGE;
exports.STORAGE_STRATEGIES = STORAGE_STRATEGIES;
exports.SessionStorage = SessionStorage;
exports.SessionStorageService = SessionStorageService;
exports.SessionStorageStrategy = SessionStorageStrategy;
exports.StorageStrategyStub = StorageStrategyStub;
exports.StorageStrategyStubName = StorageStrategyStubName;
exports.StorageStub = StorageStub;
exports.StrategyCacheService = StrategyCacheService;
exports.StrategyIndex = StrategyIndex;
exports.SyncStorage = SyncStorage;
exports.appInit = appInit;
exports.ɵa = getLocalStorage;
exports.ɵb = LocalStorageProvider;
exports.ɵc = getSessionStorage;
exports.ɵd = SessionStorageProvider;
exports.ɵe = Strategies;
exports.ɵf = buildService$1;
exports.ɵg = LocalStorageServiceProvider;
exports.ɵh = buildService;
exports.ɵi = SessionStorageServiceProvider;
exports.ɵj = BaseSyncStorageStrategy;
exports.ɵl = STORAGE_STRATEGIES;
exports.ɵn = Services;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=ngx-webstorage.umd.js.map