UNPKG

@samual/cookie

Version:

Set and get cookies with optional type validation with a Standard Schema.

43 lines (42 loc) 1.64 kB
import { tryCatch } from "@samual/lib/tryCatch" import { utf8Decoder } from "@samual/lib/utf8Decoder" import { utf8Encoder } from "@samual/lib/utf8Encoder" import { SchemaError } from "@standard-schema/utils" import { deleteCookie as deleteCookie$1, setCookie as setCookie$1 } from "./index.js" const encodeString = string => btoa(String.fromCharCode(...utf8Encoder.encode(string))) .replaceAll("=", "") .replaceAll("+", "-") .replaceAll("/", "_"), makeCookieOptions = options => options function getCookie(cookies, options) { const cookie = cookies.get(options.rawName ? options.name : encodeString(options.name)) if (cookie) { const result = options.schema["~standard"].validate( tryCatch(() => { return JSON.parse( options.rawValue ? cookie : ( ((string = cookie), utf8Decoder.decode( Uint8Array.from(atob(string.replaceAll("-", "+").replaceAll("_", "/")), character => character.charCodeAt(0) ) )) ) ) var string }) ) if (result instanceof Promise) throw TypeError("Schema validation must be synchronous") if (result.issues) throw new SchemaError(result.issues) return result.value } } function setCookie(options, value) { const name = options.rawName ? options.name : encodeString(options.name) if (void 0 === value) return deleteCookie$1(name) const json = JSON.stringify(value) return setCookie$1(name, options.rawValue ? json : encodeString(json), options) } const deleteCookie = options => deleteCookie$1(options.rawName ? options.name : encodeString(options.name)) export { deleteCookie, getCookie, makeCookieOptions, setCookie }