UNPKG

ngx-store

Version:

Angular decorators to automagically keep variables in HTML5 LocalStorage, SessionStorage, cookies; injectable services for managing and listening to data changes and a bit more.

1,176 lines (1,161 loc) 66 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('ts-debug'), require('rxjs/operators'), require('lodash.merge'), require('rxjs'), require('@angular/core')) : typeof define === 'function' && define.amd ? define('ngx-store', ['exports', 'ts-debug', 'rxjs/operators', 'lodash.merge', 'rxjs', '@angular/core'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['ngx-store'] = {}, global.tsDebug, global.rxjs.operators, global.merge, global.rxjs, global.ng.core)); }(this, (function (exports, tsDebug, operators, merge, rxjs, core) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge); /*! ***************************************************************************** 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, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } var CONFIG_PREFIX = 'NGX-STORE_'; var ConfigHelper = /** @class */ (function () { function ConfigHelper() { } ConfigHelper.getItem = function (key) { return localStorage.getItem(CONFIG_PREFIX + key); }; ConfigHelper.setItem = function (key, item) { return localStorage.setItem(CONFIG_PREFIX + key, item); }; return ConfigHelper; }()); var DefaultConfig = { prefix: 'ngx_', previousPrefix: 'angular2ws_', clearType: 'prefix', mutateObjects: true, cookiesScope: '', cookiesCheckInterval: 0, debugMode: false, }; var ConfigFills = {}; var localStoragePrefix = ConfigHelper.getItem('prefix'); if (typeof NGXSTORE_CONFIG === 'object') { ConfigFills = Object.assign({}, NGXSTORE_CONFIG); } if (localStoragePrefix !== undefined && localStoragePrefix !== null) { ConfigFills.previousPrefix = localStoragePrefix; } else if (ConfigFills.previousPrefix === undefined) { ConfigFills.previousPrefix = DefaultConfig.previousPrefix; } // merge default config, deprecated config and global config all together var Config = Object.assign({}, DefaultConfig, ConfigFills); var debug = new tsDebug.Debugger(console, Config.debugMode, '[ngx-store] '); ConfigHelper.setItem('prefix', Config.prefix); var isEqual = require('lodash.isequal'); var Cache = /** @class */ (function () { function Cache() { } Cache.getCacheFor = function (cacheCandidate) { var cacheItem = Cache.get(cacheCandidate.key); if (!cacheItem) { cacheItem = new CacheItem(cacheCandidate); debug.log("Created new CacheItem for " + cacheCandidate.name + " for " + cacheItem.utilities[0].utility.getStorageName()); Cache.set(cacheItem); return cacheItem; } debug.log("Loaded prior CacheItem of " + cacheItem.name + "\n for " + cacheCandidate.utilities[0].utility.getStorageName()); cacheItem.addTargets(cacheCandidate.targets); cacheItem.addServices(cacheCandidate.services); cacheItem.addUtilities(cacheCandidate.utilities); Cache.set(cacheItem); return cacheItem; }; Cache.remove = function (cacheItem) { return Cache.items.delete(cacheItem.key); }; Cache.get = function (key) { return Cache.items.get(key); }; Cache.set = function (cacheItem) { if (!Cache.get(cacheItem.key)) { debug.log('CacheItem for ' + cacheItem.key, cacheItem); } Cache.items.set(cacheItem.key, cacheItem); }; return Cache; }()); Cache.items = new Map(); // tslint:disable:only-arrow-functions var CacheItem = /** @class */ (function () { function CacheItem(cacheItem) { this.name = ''; this.targets = []; this.services = []; this.utilities = []; this.currentTarget = {}; this.proxy = null; this._key = ''; this.initializedTargets = new Set(); this._key = cacheItem.key; this.name = cacheItem.name; this.addTargets(cacheItem.targets); this.addServices(cacheItem.services); this.addUtilities(cacheItem.utilities); } Object.defineProperty(CacheItem.prototype, "key", { get: function () { return this._key; }, enumerable: false, configurable: true }); CacheItem.prototype.saveValue = function (value, config) { if (config === void 0) { config = {}; } debug.groupCollapsed('CacheItem#saveValue for ' + this.key + ' in ' + this.currentTarget.constructor.name); debug.log('new value: ', value); // if (value === false && this.readValue() === true) debugger; debug.log('previous value: ', this.readValue()); debug.log('targets.length: ', this.targets.length); debug.log('currentTarget:', this.currentTarget); debug.groupEnd(); // prevent overwriting value by initializators if (!this.initializedTargets.has(this.currentTarget)) { this.initializedTargets.add(this.currentTarget); var readValue = this.readValue(); if (config.migrateKey) { this.migrate(config, this.utilities[0].utility); readValue = this.readValue(); } var savedValue = (readValue !== null && readValue !== undefined) ? readValue : value; var proxy = this.getProxy(savedValue, config); proxy = (proxy !== null) ? proxy : value; debug.log('initial value for ' + this.key + ' in ' + this.currentTarget.constructor.name, proxy); this.propagateChange(savedValue); return proxy; } this.propagateChange(value); return this.getProxy(value, config); }; CacheItem.prototype.getProxy = function (value, config) { var e_1, _a; if (config === void 0) { config = {}; } if (value === undefined && this.proxy) { return this.proxy; } // return cached proxy if value hasn't changed value = (value === undefined) ? this.readValue() : value; if (typeof value !== 'object' || value === null) { this.proxy = value; return value; } if ((!Config.mutateObjects && !config.mutate) || config.mutate === false) { return value; } var _self = this; // alias to use in standard function expressions var prototype = Object.assign(new value.constructor(), value.__proto__); prototype.save = function () { _self.saveValue(value, config); }; // TODO set prototype for Array.prototype or something if (Array.isArray(value)) { // handle methods that could change value of array var methodsToOverwrite = [ 'pop', 'push', 'reverse', 'shift', 'unshift', 'splice', 'filter', 'forEach', 'map', 'fill', 'sort', 'copyWithin', ]; var _loop_1 = function (method) { prototype[method] = function () { var readValue = _self.readValue(); // @ts-ignore var result = Array.prototype[method].apply(readValue, arguments); debug.log('Saving value for ' + _self.key + ' by method ' + prototype.constructor.name + '.' + method); _self.saveValue(readValue, config); return result; }; }; try { for (var methodsToOverwrite_1 = __values(methodsToOverwrite), methodsToOverwrite_1_1 = methodsToOverwrite_1.next(); !methodsToOverwrite_1_1.done; methodsToOverwrite_1_1 = methodsToOverwrite_1.next()) { var method = methodsToOverwrite_1_1.value; _loop_1(method); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (methodsToOverwrite_1_1 && !methodsToOverwrite_1_1.done && (_a = methodsToOverwrite_1.return)) _a.call(methodsToOverwrite_1); } finally { if (e_1) throw e_1.error; } } } Object.setPrototypeOf(value, prototype); this.proxy = value; return value; }; CacheItem.prototype.readValue = function (config) { if (config === void 0) { config = {}; } var entry = this.utilities[0]; var value = entry ? entry.utility.get(this.key, entry.config) : null; return (typeof value !== 'object') ? value : JSON.parse(JSON.stringify(this.getProxy(value, entry.config))); }; CacheItem.prototype.addTargets = function (targets) { var _this = this; targets.forEach(function (target) { if (_this.targets.indexOf(target) === -1) { if (typeof target === 'object') { // handle Angular Component destruction var originalFunction_1 = target.ngOnDestroy; var _self_1 = _this; target.ngOnDestroy = function () { if (typeof originalFunction_1 === 'function') { originalFunction_1.apply(this, arguments); } target.ngOnDestroy = originalFunction_1 || function () { }; _self_1.initializedTargets.delete(target); _self_1.targets = _self_1.targets.filter(function (t) { return t !== target; }); if (!_self_1.targets.length) { _self_1.services.forEach(function (service) { service.keys = service.keys.filter(function (key) { return key !== _self_1._key; }); }); _self_1.resetProxy(); Cache.remove(_self_1); } debug.groupCollapsed(_self_1.key + " OnDestroy handler:"); debug.log('removed target:', target.constructor.name); debug.log('remaining targets:', _self_1.targets); debug.log('cacheItem:', Cache.get(_self_1.key)); debug.groupEnd(); }; _this.targets.push(target); } } }); }; CacheItem.prototype.addServices = function (services) { var _this = this; services.forEach(function (service) { if (_this.services.indexOf(service) === -1) { service.keys.push(_this._key); _this.services.push(service); } }); }; CacheItem.prototype.addUtilities = function (utilityEntries) { var _this = this; utilityEntries.forEach(function (entry) { if (_this.utilities.findIndex(function (e) { return e.utility === entry.utility; }) === -1) { _this.utilities.push(entry); entry.utility.set(_this.key, _this.readValue()); } }); }; CacheItem.prototype.resetProxy = function () { this.proxy = null; }; CacheItem.prototype.propagateChange = function (value, source) { var _this = this; if (isEqual(value, this.readValue())) { return; } this.utilities.forEach(function (entry) { var utility = entry.utility; // updating service which the change came from would affect in a cycle if (utility === source) { return; } debug.log("propagating change on " + _this.key + " to:", utility); utility.set(_this._key, value, entry.config); }); }; CacheItem.prototype.migrate = function (config, utility) { var prefix = (config.prefix || Config.prefix) || ''; var keyExists = function (key) { return key in utility.getStorage(); }; var migrateKey = keyExists(prefix + config.migrateKey) ? prefix + config.migrateKey : config.migrateKey; if (!keyExists(migrateKey)) { return; } debug.log('Migrating', migrateKey, 'to', config.key, 'in', utility.getStorageName()); var value = utility.get(migrateKey, Object.assign(Object.assign({}, config), { prefix: '' })); utility.set(this._key, value); utility.remove(migrateKey, { prefix: '' }); }; return CacheItem; }()); var NgxStorageEvent = /** @class */ (function () { function NgxStorageEvent(type, key, storageArea) { this.type = type; this.key = key; this.storageArea = storageArea; this.timeStamp = (Date.now() - NgxStorageEvent.initTimeStamp); this.bubbles = false; this.cancelBubble = false; this.cancelable = false; this.composed = false; this.currentTarget = window; this.defaultPrevented = false; this.eventPhase = 2; this.isTrusted = true; this.path = [window]; this.returnValue = true; this.srcElement = window; this.target = window; this.url = window.location.href; this.isInternal = true; } Object.defineProperty(NgxStorageEvent.prototype, "initEvent", { /** * Methods below exist only to satisfy TypeScript compiler */ // tslint:disable:typedef get: function () { return StorageEvent.prototype.initEvent.bind(this); }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "preventDefault", { get: function () { return StorageEvent.prototype.preventDefault.bind(this); }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "stopImmediatePropagation", { get: function () { return StorageEvent.prototype.stopImmediatePropagation.bind(this); }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "stopPropagation", { get: function () { return StorageEvent.prototype.stopPropagation.bind(this); }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "composedPath", { get: function () { return StorageEvent.prototype.composedPath.bind(this); }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "AT_TARGET", { get: function () { return StorageEvent.prototype.AT_TARGET; }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "BUBBLING_PHASE", { get: function () { return StorageEvent.prototype.BUBBLING_PHASE; }, enumerable: false, configurable: true }); Object.defineProperty(NgxStorageEvent.prototype, "CAPTURING_PHASE", { get: function () { return StorageEvent.prototype.BUBBLING_PHASE; }, enumerable: false, configurable: true }); return NgxStorageEvent; }()); NgxStorageEvent.initTimeStamp = Date.now(); var _get = require('lodash.get'); var _set = require('lodash.set'); var _merge = require('lodash.merge'); var Resource = /** @class */ (function () { function Resource(service, key) { this.service = service; this.key = key; this._defaultValue = null; this._path = []; this._prefix = Config.prefix; } Object.defineProperty(Resource.prototype, "defaultValue", { /** * Returns default value * @returns {T} */ get: function () { return this._defaultValue; }, enumerable: false, configurable: true }); Object.defineProperty(Resource.prototype, "path", { /** * Returns current path as a string * @returns {string} */ get: function () { return this.pathString; }, enumerable: false, configurable: true }); Object.defineProperty(Resource.prototype, "prefix", { /** * Returns currently set prefix * @returns {string} */ get: function () { return this._prefix || ''; }, enumerable: false, configurable: true }); Object.defineProperty(Resource.prototype, "value", { /** * Returns value taking path into account * @returns {T} */ get: function () { return this.considerDefault(this.readValue()); }, enumerable: false, configurable: true }); Object.defineProperty(Resource.prototype, "fullValue", { get: function () { return this.considerDefault(this.service.utility.get(this.key, { prefix: this._prefix })); }, enumerable: false, configurable: true }); Object.defineProperty(Resource.prototype, "pathString", { get: function () { return this._path.join('.'); }, enumerable: false, configurable: true }); /** * Sets path of object property * @param {string} path * @returns {this} */ Resource.prototype.setPath = function (path) { this._path = path.split('.'); return this; }; /** * Appends current path * e.g. if path('key') and appendPath('nested'), the path will be "key.nested" * @param {string} path * @returns {this} */ Resource.prototype.appendPath = function (path) { this._path.push(path); return this; }; /** * Removes last item of path * e.g. if path('key.nested') and truncatePath(), the path will be "key" * @returns {this} */ Resource.prototype.truncatePath = function () { this._path.pop(); return this; }; /** * Resets set path * @returns {this} */ Resource.prototype.resetPath = function () { this._path = []; return this; }; /** * Sets prefix * @param {string} prefix * @returns {this} */ Resource.prototype.setPrefix = function (prefix) { this._prefix = prefix; return this; }; /** * Moves storage item to new key using given prefix * @param {string} prefix * @returns {this} */ Resource.prototype.changePrefix = function (prefix) { this.service.utility.set(this.key, this.fullValue, { prefix: prefix }); this.service.utility.remove(this.key, { prefix: this._prefix }); return this.setPrefix(prefix); }; /** * Sets default value for both reading and saving operations * @param defaultValue * @returns {this} */ Resource.prototype.setDefaultValue = function (defaultValue) { this._defaultValue = defaultValue; var value = this.readValue(); if (this.isNullOrUndefined(value)) { this.save(defaultValue); } return this; }; /** * Creates or overrides value as a new entry or existing object property depending on path * @param value * @returns {this} */ Resource.prototype.save = function (value) { if (this.pathString) { value = _set(this.fullValue, this.pathString, this.considerDefault(value)); } this.service.utility.set(this.key, this.considerDefault(value), { prefix: this._prefix }); return this; }; /** * Updates existing object property using current path * @param {T} value * @returns {this} */ Resource.prototype.update = function (value) { return this.save(_merge(this.readValue(), value)); }; /** * Removes item stored under current key * @returns {this} */ Resource.prototype.remove = function () { this.service.utility.remove(this.key); return this; }; Resource.prototype.considerDefault = function (value) { return this.isNullOrUndefined(value) ? this._defaultValue : value; }; Resource.prototype.isNullOrUndefined = function (value) { return (value === null || value === undefined); }; Resource.prototype.readValue = function () { var value = this.service.utility.get(this.key, { prefix: this._prefix }); if (this.pathString) { return _get(value, this.pathString); } return value; }; return Resource; }()); // const merge = require('lodash.merge'); var WebStorageService = /** @class */ (function () { function WebStorageService(utility) { this.utility = utility; } Object.defineProperty(WebStorageService.prototype, "keys", { /** * Gets keys for stored variables created by ngx-store, * ignores keys that have not been created by decorators and have no prefix at once */ get: function () { var _this = this; // get prefixed key if prefix is defined var prefixKeys = this.utility.keys.filter(function (key) { if (_this.utility.prefix && _this.utility.prefix.length) { return key.startsWith(_this.utility.prefix); } return true; }); var decoratorKeys = this.constructor.keys; return prefixKeys.concat(decoratorKeys); }, enumerable: false, configurable: true }); Object.defineProperty(WebStorageService.prototype, "config", { get: function () { return Config; }, enumerable: false, configurable: true }); WebStorageService.prototype.get = function (key) { return this.utility.get(key); }; /** * Returns new data Resource for given key exposing builder design pattern * designed for complex nested data structures */ WebStorageService.prototype.load = function (key) { return new Resource(this, key); }; WebStorageService.prototype.set = function (key, value) { return this.utility.set(key, value); }; WebStorageService.prototype.update = function (key, changes) { var value = this.get(key); if (value !== undefined && typeof value !== 'object') { debug.throw(new Error("Value stored under \"" + key + "\" key is not an object and tried to be updated.")); return value; } return this.set(key, merge__default['default']({}, value, changes)); }; // TODO return true if item existed and false otherwise (?) WebStorageService.prototype.remove = function (key) { return this.utility.remove(key); }; WebStorageService.prototype.observe = function (key, exactMatch) { return this._changes.pipe(operators.filter(function (event) { var _a; if (!key) { return true; } if (exactMatch) { if (Config.prefix && key.startsWith(Config.prefix)) { return event.key === key; } return event.key === Config.prefix + key; } else { return ((_a = event.key) === null || _a === void 0 ? void 0 : _a.indexOf(key)) !== -1; } }), operators.delay(30)); }; /** * Clears chosen data from Storage * @param clearType 'prefix' | 'decorators' | 'all' * @param prefixOrClass defines the prefix or class (not its instance) whose decorators should be cleared */ WebStorageService.prototype.clear = function (clearType, prefixOrClass) { var _this = this; clearType = clearType || Config.clearType; if (clearType === 'decorators') { var keys = []; if (typeof prefixOrClass === 'object') { keys = this.keys.filter(function (key) { return Cache.get(key).targets.includes(prefixOrClass); }); debug.log(this.utility.getStorageName() + ' > Removing decorated data from ' + prefixOrClass.constructor.name + ':', keys); } else { keys = this.keys; debug.log(this.utility.getStorageName() + ' > Removing decorated data:', keys); } keys.forEach(function (key) { return _this.remove(key); }); } else if (clearType === 'prefix') { prefixOrClass = prefixOrClass || this.utility.prefix; this.utility.forEach(function (value, key) { if (key.startsWith(prefixOrClass)) { _this.remove(_this.utility.trimPrefix(key)); } }); } else if (clearType === 'all') { this.utility.clear(); } }; WebStorageService.prototype.generateEvent = function (key, newValue, oldValue) { var type = this.utility.getStorageName().charAt(0).toLowerCase() + this.utility.getStorageName().slice(1); var event = new NgxStorageEvent(type, key, this.utility.getStorage()); event.oldValue = (oldValue !== undefined) ? oldValue : this.get(key); event.newValue = newValue; return event; }; WebStorageService.prototype.mapNativeEvent = function (ev) { var event = this.generateEvent(ev.key, this.utility.getGettable(ev.newValue), this.utility.getGettable(ev.oldValue)); event.isInternal = false; return event; }; return WebStorageService; }()); WebStorageService.keys = []; var WebStorageUtility = /** @class */ (function () { function WebStorageUtility(storage, prefix, previousPrefix) { var _this = this; if (prefix === void 0) { prefix = ''; } this._prefix = ''; this._changes = new rxjs.Subject(); this._storage = storage; this._prefix = prefix; // handle previousPrefix for backward-compatibility and safe config changes below if (prefix === previousPrefix) { return; } if (previousPrefix === null) { return; } if (previousPrefix === undefined) { return; } debug.log(this.getStorageName() + ' > Detected prefix change from ' + previousPrefix + ' to ' + prefix); this.forEach(function (value, key) { // ignore config settings when previousPrefix = '' if (key.startsWith(previousPrefix) && !key.startsWith(CONFIG_PREFIX)) { var nameWithoutPrefix = _this.trimPrefix(key); _this.set(nameWithoutPrefix, _this._storage.getItem(key)); if (previousPrefix !== '') { _this._storage.removeItem(key); } } }); } Object.defineProperty(WebStorageUtility.prototype, "prefix", { get: function () { return this._prefix; }, enumerable: false, configurable: true }); Object.defineProperty(WebStorageUtility.prototype, "changes", { get: function () { return this._changes.asObservable(); }, enumerable: false, configurable: true }); Object.defineProperty(WebStorageUtility.prototype, "keys", { get: function () { var keys = []; this.forEach(function (value, key) { return keys.push(key); }); return keys; }, enumerable: false, configurable: true }); WebStorageUtility.getSettable = function (value) { return JSON.stringify(value); }; WebStorageUtility.getGettable = function (value) { if (value === 'undefined') { return null; } try { return JSON.parse(value); } catch (e) { return value; } }; WebStorageUtility.prototype.getStorage = function () { return this._storage; }; WebStorageUtility.prototype.getStorageKey = function (key, prefix) { prefix = (typeof prefix === 'string') ? prefix : this.prefix; return "" + prefix + key; }; WebStorageUtility.prototype.getStorageName = function () { return this._storage.type || ((this._storage === localStorage) ? 'localStorage' : 'sessionStorage'); }; WebStorageUtility.prototype.get = function (key, config) { if (config === void 0) { config = {}; } var storageKey = this.getStorageKey(key, config.prefix); var value = this._storage.getItem(storageKey); // TODO return undefined if no key /*if (value === null && !(storageKey in this._storage)) { return undefined; }*/ return this.getGettable(value); }; WebStorageUtility.prototype.set = function (key, value, config) { if (config === void 0) { config = {}; } if (value === null || value === undefined) { this.remove(key); return null; } try { var storageKey = this.getStorageKey(key, config.prefix); var storable = this.getSettable(value); this.emitEvent(key, value); this._storage.setItem(storageKey, storable, config.expires); var cacheItem = Cache.get(key); if (cacheItem) { debug.log("updating following CacheItem from " + this.constructor.name + ":", cacheItem); cacheItem.resetProxy(); cacheItem.propagateChange(value, this); } } catch (error) { console.warn("[ngx-store] " + this.getStorageName() + ":\n following error occurred while trying to save " + key + " =", value); console.error(error); } return value; }; // TODO return true if item existed and false otherwise (?) WebStorageUtility.prototype.remove = function (key, config) { if (config === void 0) { config = {}; } var storageKey = this.getStorageKey(key, config.prefix); this._storage.removeItem(storageKey); var cacheItem = Cache.get(key); if (cacheItem) { cacheItem.resetProxy(); } }; WebStorageUtility.prototype.clear = function () { var _this = this; this.emitEvent(null, null, null); this.forEach(function (value, key) { if (key.startsWith(CONFIG_PREFIX)) { return; } _this.remove(key, { prefix: '' }); }); }; WebStorageUtility.prototype.forEach = function (callbackFn) { var _this = this; if (typeof this._storage.forEach === 'function') { return this._storage.forEach(function (value, key) { callbackFn(_this.getGettable(value), key); }); } Object.keys(this._storage).forEach(function (key) { callbackFn(_this.getGettable(_this._storage[key]), key); }); }; WebStorageUtility.prototype.getSettable = function (value) { return WebStorageUtility.getSettable(value); }; WebStorageUtility.prototype.getGettable = function (value) { return WebStorageUtility.getGettable(value); }; WebStorageUtility.prototype.trimPrefix = function (key) { return key.replace(this.prefix, ''); }; WebStorageUtility.prototype.emitEvent = function (key, newValue, oldValue) { var event = new NgxStorageEvent(this.getStorageName(), key, this._storage); event.oldValue = (oldValue !== undefined) ? oldValue : this.get(key); event.newValue = newValue; this._changes.next(event); }; return WebStorageUtility; }()); // TODO: in the future use ES6 Proxy to handle indexers var NgxStorage = /** @class */ (function () { function NgxStorage() { this.externalChanges = new rxjs.Subject(); } NgxStorage.prototype.emitEvent = function (key, newValue, oldValue) { var _a; var event = new NgxStorageEvent(this.type, key, this); event.oldValue = (oldValue !== undefined) ? oldValue : this.getItem(key); event.newValue = newValue; event.isInternal = false; (_a = this.externalChanges) === null || _a === void 0 ? void 0 : _a.next(event); }; return NgxStorage; }()); var CookiesStorage = /** @class */ (function (_super) { __extends(CookiesStorage, _super); function CookiesStorage() { var _this = _super.call(this) || this; _this.cachedCookieString = ''; _this.cachedItemsMap = new Map(); _this.getAllItems(); if (Config.cookiesCheckInterval) { rxjs.interval(Config.cookiesCheckInterval) .subscribe(function () { var _a; if (!((_a = _this.externalChanges) === null || _a === void 0 ? void 0 : _a.observers.length)) { return; // don't run if there are no set subscriptions } _this.getAllItems(); }); } return _this; } Object.defineProperty(CookiesStorage.prototype, "type", { get: function () { return 'cookiesStorage'; },