pinia-plugin-persistedstate-2
Version:
Persist and rehydrate your Pinia state between page reloads
155 lines (154 loc) • 3.53 kB
JavaScript
function A(s, e, f) {
return (s = (e.split ? e.split(".") : e).reduce(function(i, n) {
return i && i[n];
}, s)) === void 0 ? f : s;
}
function $(s, e, f, i) {
return (e = e.split ? e.split(".") : e.slice(0)).slice(0, -1).reduce(function(n, a) {
return /^(__proto__|constructor|prototype)$/.test(a) ? {} : n[a] = n[a] || {};
}, s)[e.pop()] = f, s;
}
function I(s, e) {
return s === void 0 || s === null ? e : s;
}
function c(s, e, f, i) {
return I(
I(f[e], i[e]),
s
);
}
function b(s) {
const e = s || {};
function f(i) {
const n = function() {
try {
return i.options.persistedState || {};
} catch {
return {};
}
}();
if (c(!0, "persist", n, e) === !1) return;
const a = c(i.store.$id, "key", n, {}), O = c(!1, "overwrite", n, e), p = c(
function() {
try {
return window.localStorage;
} catch {
return {
getItem: function() {
},
setItem: function() {
},
removeItem: function() {
}
};
}
}(),
"storage",
n,
e
), w = c(
function() {
return !0;
},
"filter",
n,
e
), h = c(
JSON.stringify,
"serialize",
n,
e
), y = c(
JSON.parse,
"deserialize",
n,
e
), _ = c(
function(t) {
return t;
},
"migrate",
n,
{}
), E = c(
function(t, r) {
return r;
},
"merge",
n,
{}
), N = c(
function(t) {
const r = "@@", o = t.setItem(r, "1"), u = function() {
t.removeItem(r);
};
o instanceof Promise ? o.then(u) : u();
},
"assertStorage",
n,
e
);
function P(t) {
(n.beforeHydrate || function() {
})(i.store.$state);
const r = E(i.store.$state, t);
O ? i.store.$patch((o) => {
Object.keys(o).forEach((u) => {
o[u] = r[u];
});
}) : i.store.$patch(r), l();
}
function S(t) {
if (t != null) {
const r = y(t), o = _(r);
o instanceof Promise ? o.then(P) : P(o);
} else
l();
}
let l;
const z = new Promise(function(t) {
l = t;
});
let d = 0;
i.store.$persistedState = {
isReady: function() {
return z;
},
pending: !1
};
try {
if (process.env.NODE_ENV !== "production") {
const t = N(p);
t instanceof Promise ? t.then(() => m()).catch((r) => console.warn(r)) : m();
} else
m();
} catch (t) {
process.env.NODE_ENV !== "production" && console.warn(t), l();
}
function m() {
const t = p.getItem(a);
t instanceof Promise ? t.then(S) : S(t);
}
i.store.$subscribe(function(t, r) {
if (w(t, r) === !1) return;
Array.isArray(n.includePaths) && (r = n.includePaths.reduce(function(g, v) {
return $(
g,
v,
A(r, v, void 0)
);
}, {})), Array.isArray(n.excludePaths) && (r = y(h(r)), n.excludePaths.forEach(function(g) {
return $(r, g, void 0);
}, {}));
const o = h(r), u = p.setItem(a, o);
u instanceof Promise && (++d, i.store.$persistedState.pending = d !== 0, u.catch(function() {
}).finally(function() {
--d, i.store.$persistedState.pending = d !== 0;
}));
});
}
return f;
}
export {
b as createPersistedStatePlugin
};