index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('deepmerge')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'deepmerge'], factory) :
  4. (global = global || self, factory(global.VuexPersistence = {}, global.deepmerge));
  5. }(this, (function (exports, deepmerge) { 'use strict';
  6. deepmerge = deepmerge && deepmerge.hasOwnProperty('default') ? deepmerge['default'] : deepmerge;
  7. /**
  8. * Created by championswimmer on 22/07/17.
  9. */
  10. // tslint:disable: variable-name
  11. var SimplePromiseQueue = /** @class */ (function () {
  12. function SimplePromiseQueue() {
  13. this._queue = [];
  14. this._flushing = false;
  15. }
  16. SimplePromiseQueue.prototype.enqueue = function (promise) {
  17. this._queue.push(promise);
  18. if (!this._flushing) {
  19. return this.flushQueue();
  20. }
  21. return Promise.resolve();
  22. };
  23. SimplePromiseQueue.prototype.flushQueue = function () {
  24. var _this = this;
  25. this._flushing = true;
  26. var chain = function () {
  27. var nextTask = _this._queue.shift();
  28. if (nextTask) {
  29. return nextTask.then(chain);
  30. }
  31. else {
  32. _this._flushing = false;
  33. }
  34. };
  35. return Promise.resolve(chain());
  36. };
  37. return SimplePromiseQueue;
  38. }());
  39. var options = {
  40. replaceArrays: {
  41. arrayMerge: function (destinationArray, sourceArray, options) { return sourceArray; }
  42. },
  43. concatArrays: {
  44. arrayMerge: function (target, source, options) { return target.concat.apply(target, source); }
  45. }
  46. };
  47. function merge(into, from, mergeOption) {
  48. return deepmerge(into, from, options[mergeOption]);
  49. }
  50. var FlattedJSON = JSON;
  51. /**
  52. * A class that implements the vuex persistence.
  53. * @type S type of the 'state' inside the store (default: any)
  54. */
  55. var VuexPersistence = /** @class */ (function () {
  56. /**
  57. * Create a {@link VuexPersistence} object.
  58. * Use the <code>plugin</code> function of this class as a
  59. * Vuex plugin.
  60. * @param {PersistOptions} options
  61. */
  62. function VuexPersistence(options) {
  63. var _this = this;
  64. // tslint:disable-next-line:variable-name
  65. this._mutex = new SimplePromiseQueue();
  66. /**
  67. * Creates a subscriber on the store. automatically is used
  68. * when this is used a vuex plugin. Not for manual usage.
  69. * @param store
  70. */
  71. this.subscriber = function (store) {
  72. return function (handler) { return store.subscribe(handler); };
  73. };
  74. if (typeof options === 'undefined')
  75. options = {};
  76. this.key = ((options.key != null) ? options.key : 'vuex');
  77. this.subscribed = false;
  78. this.supportCircular = options.supportCircular || false;
  79. if (this.supportCircular) {
  80. FlattedJSON = require('flatted');
  81. }
  82. this.mergeOption = options.mergeOption || 'replaceArrays';
  83. var localStorageLitmus = true;
  84. try {
  85. window.localStorage.getItem('');
  86. }
  87. catch (err) {
  88. localStorageLitmus = false;
  89. }
  90. /**
  91. * 1. First, prefer storage sent in optinos
  92. * 2. Otherwise, use window.localStorage if available
  93. * 3. Finally, try to use MockStorage
  94. * 4. None of above? Well we gotta fail.
  95. */
  96. if (options.storage) {
  97. this.storage = options.storage;
  98. }
  99. else if (localStorageLitmus) {
  100. this.storage = window.localStorage;
  101. }
  102. else if (exports.MockStorage) {
  103. this.storage = new exports.MockStorage();
  104. }
  105. else {
  106. throw new Error("Neither 'window' is defined, nor 'MockStorage' is available");
  107. }
  108. /**
  109. * How this works is -
  110. * 1. If there is options.reducer function, we use that, if not;
  111. * 2. We check options.modules;
  112. * 1. If there is no options.modules array, we use entire state in reducer
  113. * 2. Otherwise, we create a reducer that merges all those state modules that are
  114. * defined in the options.modules[] array
  115. * @type {((state: S) => {}) | ((state: S) => S) | ((state: any) => {})}
  116. */
  117. this.reducer = ((options.reducer != null)
  118. ? options.reducer
  119. : ((options.modules == null)
  120. ? (function (state) { return state; })
  121. : (function (state) {
  122. return options.modules.reduce(function (a, i) {
  123. var _a;
  124. return merge(a, (_a = {}, _a[i] = state[i], _a), _this.mergeOption);
  125. }, { /* start empty accumulator*/});
  126. })));
  127. this.filter = options.filter || (function (mutation) { return true; });
  128. this.strictMode = options.strictMode || false;
  129. this.RESTORE_MUTATION = function RESTORE_MUTATION(state, savedState) {
  130. var mergedState = merge(state, savedState || {}, this.mergeOption);
  131. for (var _i = 0, _a = Object.keys(mergedState); _i < _a.length; _i++) {
  132. var propertyName = _a[_i];
  133. this._vm.$set(state, propertyName, mergedState[propertyName]);
  134. }
  135. };
  136. this.asyncStorage = options.asyncStorage || false;
  137. if (this.asyncStorage) {
  138. /**
  139. * Async {@link #VuexPersistence.restoreState} implementation
  140. * @type {((key: string, storage?: Storage) =>
  141. * (Promise<S> | S)) | ((key: string, storage: AsyncStorage) => Promise<any>)}
  142. */
  143. this.restoreState = ((options.restoreState != null)
  144. ? options.restoreState
  145. : (function (key, storage) {
  146. return (storage).getItem(key)
  147. .then(function (value) {
  148. return typeof value === 'string' // If string, parse, or else, just return
  149. ? (_this.supportCircular
  150. ? FlattedJSON.parse(value || '{}')
  151. : JSON.parse(value || '{}'))
  152. : (value || {});
  153. });
  154. }));
  155. /**
  156. * Async {@link #VuexPersistence.saveState} implementation
  157. * @type {((key: string, state: {}, storage?: Storage) =>
  158. * (Promise<void> | void)) | ((key: string, state: {}, storage?: Storage) => Promise<void>)}
  159. */
  160. this.saveState = ((options.saveState != null)
  161. ? options.saveState
  162. : (function (key, state, storage) {
  163. return (storage).setItem(key, // Second argument is state _object_ if asyc storage, stringified otherwise
  164. // do not stringify the state if the storage type is async
  165. (_this.asyncStorage
  166. ? merge({}, state || {}, _this.mergeOption)
  167. : (_this.supportCircular
  168. ? FlattedJSON.stringify(state)
  169. : JSON.stringify(state))));
  170. }));
  171. /**
  172. * Async version of plugin
  173. * @param {Store<S>} store
  174. */
  175. this.plugin = function (store) {
  176. /**
  177. * For async stores, we're capturing the Promise returned
  178. * by the `restoreState()` function in a `restored` property
  179. * on the store itself. This would allow app developers to
  180. * determine when and if the store's state has indeed been
  181. * refreshed. This approach was suggested by GitHub user @hotdogee.
  182. * See https://github.com/championswimmer/vuex-persist/pull/118#issuecomment-500914963
  183. * @since 2.1.0
  184. */
  185. store.restored = (_this.restoreState(_this.key, _this.storage)).then(function (savedState) {
  186. /**
  187. * If in strict mode, do only via mutation
  188. */
  189. if (_this.strictMode) {
  190. store.commit('RESTORE_MUTATION', savedState);
  191. }
  192. else {
  193. store.replaceState(merge(store.state, savedState || {}, _this.mergeOption));
  194. }
  195. _this.subscriber(store)(function (mutation, state) {
  196. if (_this.filter(mutation)) {
  197. _this._mutex.enqueue(_this.saveState(_this.key, _this.reducer(state), _this.storage));
  198. }
  199. });
  200. _this.subscribed = true;
  201. });
  202. };
  203. }
  204. else {
  205. /**
  206. * Sync {@link #VuexPersistence.restoreState} implementation
  207. * @type {((key: string, storage?: Storage) =>
  208. * (Promise<S> | S)) | ((key: string, storage: Storage) => (any | string | {}))}
  209. */
  210. this.restoreState = ((options.restoreState != null)
  211. ? options.restoreState
  212. : (function (key, storage) {
  213. var value = (storage).getItem(key);
  214. if (typeof value === 'string') { // If string, parse, or else, just return
  215. return (_this.supportCircular
  216. ? FlattedJSON.parse(value || '{}')
  217. : JSON.parse(value || '{}'));
  218. }
  219. else {
  220. return (value || {});
  221. }
  222. }));
  223. /**
  224. * Sync {@link #VuexPersistence.saveState} implementation
  225. * @type {((key: string, state: {}, storage?: Storage) =>
  226. * (Promise<void> | void)) | ((key: string, state: {}, storage?: Storage) => Promise<void>)}
  227. */
  228. this.saveState = ((options.saveState != null)
  229. ? options.saveState
  230. : (function (key, state, storage) {
  231. return (storage).setItem(key, // Second argument is state _object_ if localforage, stringified otherwise
  232. (_this.supportCircular
  233. ? FlattedJSON.stringify(state)
  234. : JSON.stringify(state)));
  235. }));
  236. /**
  237. * Sync version of plugin
  238. * @param {Store<S>} store
  239. */
  240. this.plugin = function (store) {
  241. var savedState = _this.restoreState(_this.key, _this.storage);
  242. if (_this.strictMode) {
  243. store.commit('RESTORE_MUTATION', savedState);
  244. }
  245. else {
  246. store.replaceState(merge(store.state, savedState || {}, _this.mergeOption));
  247. }
  248. _this.subscriber(store)(function (mutation, state) {
  249. if (_this.filter(mutation)) {
  250. _this.saveState(_this.key, _this.reducer(state), _this.storage);
  251. }
  252. });
  253. _this.subscribed = true;
  254. };
  255. }
  256. }
  257. return VuexPersistence;
  258. }());
  259. exports.VuexPersistence = VuexPersistence;
  260. exports.default = VuexPersistence;
  261. Object.defineProperty(exports, '__esModule', { value: true });
  262. })));
  263. //# sourceMappingURL=index.js.map