UNPKG

storage-manager-js

Version:

A little way to control Cookies, LocalStorage and SessionStorage without tears

3 lines (2 loc) 2.63 kB
(function(s,i){typeof exports=="object"&&typeof module<"u"?i(exports):typeof define=="function"&&define.amd?define(["exports"],i):(s=typeof globalThis<"u"?globalThis:s||self,i(s.storageManagerJs={}))})(this,function(s){"use strict";const i=(e,t)=>{try{Object.keys(e).forEach(t)}catch(o){window.console.log(o)}},l=e=>e==null,y=e=>{const t=typeof e;return t==="string"||t==="number"||t==="boolean"||l(e)},d=(e,t)=>{const o=t.getItem(e);try{return JSON.parse(o)}catch{return o??null}},p=e=>Object.keys(e).reduce((t,o)=>({...t,[o]:d(o,e)}),{}),f=e=>e instanceof Date?e:typeof e=="number"?new Date(new Date*1+e*864e5):e,h="1969-12-31T23:59:59.000Z",S=()=>document.cookie===""?{}:document.cookie.split("; ").map(t=>t.split("=")).reduce((t,o)=>(t[decodeURIComponent(o[0].trim())]=decodeURIComponent(o[1].trim()),t),{}),a=new Set,m=()=>{const e=S();a.forEach(t=>t(e))},w=[{name:"expires",parse:e=>`expires=${f(e.expires??h)}`},{name:"maxAge",parse:e=>e.maxAge?`max-age=${f(e.expires??h)}`:""},{name:"path",parse:e=>`path=${e.path??"/"}`},{name:"sameSite",parse:e=>`samesite=${e.sameSite??"strict"}`},{name:"useSecure",parse:e=>`${e.useSecure??!0?"secure":""}`},{name:"domain",parse:e=>{const t=e.domain??"";return t===""?"":`domain=${e.multiDomain?".":""}${t}`}},{name:"partitioned",parse:e=>e.partitioned?"Partitioned":""}],$={json:S,listener:e=>(a.add(e),()=>a.delete(e)),clearListeners:()=>a.clear(),has:e=>document.cookie.split(";").some(t=>t.trim().startsWith(`${e}=`)),deleteAll:()=>{document.cookie.split(";").forEach(e=>{document.cookie=e.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}),m()},get:e=>{const t=$.json()[e];if(l(t))return null;try{return JSON.parse(decodeURIComponent(t))}catch{return t}},delete:e=>{document.cookie=`${encodeURIComponent(e)}=;expires=${new Date().toUTCString()}`,m()},set:(e,t,o={})=>{const n=y(t)?t:encodeURIComponent(JSON.stringify(t)),r=w.reduce((c,g)=>{const k=g.parse(o);return k===""?c:c.concat(k)},[`${encodeURIComponent(e)}=${n}`]).join(";");document.cookie=r,m()}},u=e=>{const t=new Set,o=n=>{e().removeItem(n);const r=p(e());t.forEach(c=>c(r))};return{delete:o,listener:n=>(t.add(n),()=>t.delete(n)),clearListeners:()=>t.clear(),json:(n=!1)=>n?p(e()):e(),has:n=>{const r=e().getItem(n);return!l(r)},deleteAll:()=>{i(e(),o),t.forEach(n=>n(e()))},get:n=>d(n,e()),set:(n,r)=>{e().setItem(n,JSON.stringify(r)),t.forEach(c=>c(e()))}}},I=u(()=>window.sessionStorage),C=u(()=>window.localStorage);s.Cookie=$,s.LocalStorage=C,s.SessionStorage=I,s.createStorage=u,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=index.umd.js.map