index.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. // src/normalize.ts
  2. function isObject(v) {
  3. return typeof v === "object" && v !== null;
  4. }
  5. function normalizeOptions(options, factoryOptions) {
  6. options = isObject(options) ? options : /* @__PURE__ */ Object.create(null);
  7. return new Proxy(options, {
  8. get(target, key, receiver) {
  9. if (key === "key")
  10. return Reflect.get(target, key, receiver);
  11. return Reflect.get(target, key, receiver) || Reflect.get(factoryOptions, key, receiver);
  12. }
  13. });
  14. }
  15. // src/pick.ts
  16. function get(state, path) {
  17. return path.reduce((obj, p) => {
  18. return obj == null ? void 0 : obj[p];
  19. }, state);
  20. }
  21. function set(state, path, val) {
  22. return path.slice(0, -1).reduce((obj, p) => {
  23. if (/^(__proto__)$/.test(p))
  24. return {};
  25. else
  26. return obj[p] = obj[p] || {};
  27. }, state)[path[path.length - 1]] = val, state;
  28. }
  29. function pick(baseState, paths) {
  30. return paths.reduce((substate, path) => {
  31. const pathArray = path.split(".");
  32. return set(substate, pathArray, get(baseState, pathArray));
  33. }, {});
  34. }
  35. // src/plugin.ts
  36. function parsePersistence(factoryOptions, store) {
  37. return (o) => {
  38. var _a;
  39. try {
  40. const {
  41. storage = localStorage,
  42. beforeRestore = void 0,
  43. afterRestore = void 0,
  44. serializer = {
  45. serialize: JSON.stringify,
  46. deserialize: JSON.parse
  47. },
  48. key = store.$id,
  49. paths = null,
  50. debug = false
  51. } = o;
  52. return {
  53. storage,
  54. beforeRestore,
  55. afterRestore,
  56. serializer,
  57. key: ((_a = factoryOptions.key) != null ? _a : (k) => k)(typeof key == "string" ? key : key(store.$id)),
  58. paths,
  59. debug
  60. };
  61. } catch (e) {
  62. if (o.debug)
  63. console.error("[pinia-plugin-persistedstate]", e);
  64. return null;
  65. }
  66. };
  67. }
  68. function hydrateStore(store, { storage, serializer, key, debug }) {
  69. try {
  70. const fromStorage = storage == null ? void 0 : storage.getItem(key);
  71. if (fromStorage)
  72. store.$patch(serializer == null ? void 0 : serializer.deserialize(fromStorage));
  73. } catch (e) {
  74. if (debug)
  75. console.error("[pinia-plugin-persistedstate]", e);
  76. }
  77. }
  78. function persistState(state, { storage, serializer, key, paths, debug }) {
  79. try {
  80. const toStore = Array.isArray(paths) ? pick(state, paths) : state;
  81. storage.setItem(key, serializer.serialize(toStore));
  82. } catch (e) {
  83. if (debug)
  84. console.error("[pinia-plugin-persistedstate]", e);
  85. }
  86. }
  87. function createPersistedState(factoryOptions = {}) {
  88. return (context) => {
  89. const { auto = false } = factoryOptions;
  90. const {
  91. options: { persist = auto },
  92. store,
  93. pinia
  94. } = context;
  95. if (!persist)
  96. return;
  97. if (!(store.$id in pinia.state.value)) {
  98. const original_store = pinia._s.get(store.$id.replace("__hot:", ""));
  99. if (original_store)
  100. Promise.resolve().then(() => original_store.$persist());
  101. return;
  102. }
  103. const persistences = (Array.isArray(persist) ? persist.map((p) => normalizeOptions(p, factoryOptions)) : [normalizeOptions(persist, factoryOptions)]).map(parsePersistence(factoryOptions, store)).filter(Boolean);
  104. store.$persist = () => {
  105. persistences.forEach((persistence) => {
  106. persistState(store.$state, persistence);
  107. });
  108. };
  109. store.$hydrate = ({ runHooks = true } = {}) => {
  110. persistences.forEach((persistence) => {
  111. const { beforeRestore, afterRestore } = persistence;
  112. if (runHooks)
  113. beforeRestore == null ? void 0 : beforeRestore(context);
  114. hydrateStore(store, persistence);
  115. if (runHooks)
  116. afterRestore == null ? void 0 : afterRestore(context);
  117. });
  118. };
  119. persistences.forEach((persistence) => {
  120. const { beforeRestore, afterRestore } = persistence;
  121. beforeRestore == null ? void 0 : beforeRestore(context);
  122. hydrateStore(store, persistence);
  123. afterRestore == null ? void 0 : afterRestore(context);
  124. store.$subscribe(
  125. (_mutation, state) => {
  126. persistState(state, persistence);
  127. },
  128. {
  129. detached: true
  130. }
  131. );
  132. });
  133. };
  134. }
  135. function createUnistorage(globalOptions = {}) {
  136. const persistedState = createPersistedState({
  137. storage: {
  138. getItem(key) {
  139. return uni.getStorageSync(key);
  140. },
  141. setItem(key, value) {
  142. uni.setStorageSync(key, value);
  143. }
  144. },
  145. serializer: {
  146. deserialize: JSON.parse,
  147. serialize: JSON.stringify
  148. },
  149. ...globalOptions
  150. });
  151. return (ctx) => {
  152. if (ctx.options.unistorage) {
  153. ctx.options.persist = ctx.options.unistorage;
  154. }
  155. return persistedState(ctx);
  156. };
  157. }
  158. export { createPersistedState, createUnistorage };