mini-cookie
Version:
一个 Document.cookie 管理包 - A Document.cookie Manager Lib
2 lines (1 loc) • 2.58 kB
JavaScript
;const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function t(t,r,i={}){const o=i||{};if(!e.test(t))throw new TypeError("argument name is invalid");const n=encodeURIComponent(JSON.stringify(r).trim());if(n&&!e.test(n))throw new TypeError("argument val is invalid");let a=`${t}=${n}`;if(o.domain){if(!e.test(o.domain))throw new TypeError("option domain is invalid");a+=`; Domain=${o.domain}`}if(o.path){if(!e.test(o.path))throw new TypeError("option path is invalid");a+=`; Path=${o.path}`}if(o.expires){if(!function(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(o.expires))throw new TypeError("option expires is invalid");a+=`; Expires=${o.expires.toUTCString()}`}if("number"==typeof o.maxAge){if(isNaN(o.maxAge)||!isFinite(o.maxAge))throw new TypeError("option maxAge is invalid");a+=`; Max-Age=${Math.floor(o.maxAge)}`}if(o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.sameSite){if("Strict"!==o.sameSite&&"Lax"!==o.sameSite&&"None"!==o.sameSite)throw new TypeError("option sameSite invalid, sameSite must be Strict | Lax |None");a+=`; SameSite=${o.sameSite}`}if(o.partitioned&&(a+="; Partitioned"),o.priority){if("High"!==o.priority&&"Medium"!==o.priority&&"Low"!==o.priority)throw new TypeError("option priority invalid, priority muse be High | Medium | Low");a+=`; Priority=${o.priority}`}return a}function r(e){try{return e&&"string"==typeof e?function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch(t){return e}}(e).split(";").filter(Boolean).map((e=>e.split("="))).reduce(((e,[t,r=""])=>{try{return Object.assign(Object.assign({},e),{[t.trim()]:JSON.parse(r.trim())})}catch(i){return Object.assign(Object.assign({},e),{[t.trim()]:r.trim()})}}),{}):{}}catch(e){return console.error(e),{}}}function i(e,r,i={}){try{if("undefined"!=typeof window&&i.httpOnly)throw new Error("Can not set a httpOnly cookie in the browser.");const o=t(String(e),r,i);return"undefined"==typeof window?!!i.ctx&&(i.ctx.res.setHeader("'Set-Cookie'",o),!0):(document.cookie=o,!0)}catch(e){return console.error("cookie set err:",e),!1}}var o={serialize:t,parse:r,get:function(e,t={}){try{return"undefined"==typeof window?t.ctx?r(t.ctx.req.headers.cookie||"")[e]:r("")[e]:r(document.cookie)[e]}catch(t){return console.error(t),r("")[e]}},set:i,del:function(e,t={}){return i(String(e),"",Object.assign(Object.assign({},t),{maxAge:-1}))},has:function(e,t={}){try{return"undefined"==typeof window?!!t.ctx&&!!r(t.ctx.req.headers.cookie||"")[String(e)]:!!r(document.cookie)[String(e)]}catch(e){return console.error(e),!1}}};module.exports=o;