cookie-muncher
Version:
Effortless cookie management for server and browser
2 lines (1 loc) • 1.94 kB
JavaScript
var s=t=>t?t.split(";").filter(o=>/^\s*([\w!#$%&'*+\-.^_`|~]+)\s*=\s*([^;]*)\s*$/u.test(o)).map(o=>{let[r,m]=o.split("=");if(typeof r>"u"||typeof m>"u")throw Error("Invalid cookie format (this should not reachable, open an issue)");let l=r.trim(),C=decodeURIComponent(m.trim());return{name:l,value:C}}):[];var k=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,a=t=>new TextEncoder().encode(t).byteLength;var i=(t,o={})=>{let r=[`${t.name}=${encodeURIComponent(t.value)}`];return typeof o.maxAge<"u"&&r.push(`Max-Age=${String(o.maxAge)}`),typeof o.expires<"u"&&r.push(`Expires=${o.expires.toUTCString()}`),typeof o.domain<"u"&&r.push(`Domain=${encodeURIComponent(o.domain)}`),r.push(`Path=${o.path??"/"}`),typeof o.secure<"u"&&r.push("Secure"),typeof o.httpOnly<"u"&&r.push("HttpOnly"),typeof o.sameSite<"u"&&r.push(`SameSite=${k(o.sameSite)}`),r.join("; ")};var T={parse:s,serialize:i};var n=()=>{if(!navigator.cookieEnabled)throw Error("Cookies are disabled by the browser")};var p=()=>(n(),s(document.cookie));var f=t=>(n(),s(document.cookie).find(o=>o.name===t)??null);var c=(t,o={})=>{if(n(),document.cookie.split(";").length>=50)throw new Error("You have more than 50 cookies, most browsers limit the number of cookies to 50");let m=i(t,o);if(a(m)>4096)throw new Error("The size of this cookie is greater than 4096 bytes, most browsers limit the number of cookies to this size");document.cookie=i(t,o)};var d=(e=>(e[e.Now=-1]="Now",e[e.OneHour=3600]="OneHour",e[e.SixHours=21600]="SixHours",e[e.TwlveHours=43200]="TwlveHours",e[e.OneDay=86400]="OneDay",e[e.OneWeek=604800]="OneWeek",e[e.TwoWeeks=1209600]="TwoWeeks",e[e.OneMonth=2592e3]="OneMonth",e[e.ThreeMonths=7776e3]="ThreeMonths",e[e.SixMonths=15552e3]="SixMonths",e[e.OneYear=31536e3]="OneYear",e))(d||{});var u=(t,o)=>{n(),document.cookie=i({name:t,value:""},{...o,maxAge:-1})};var mo={getAll:p,get:f,set:c,remove:u};export{d as CookieMaxAge,mo as domCookie,T as httpCookie};