Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/samualtnorman/cookie. Set and get cookies with optional type validation using a Standard Schema.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import type { StandardSchemaV1 } from "@standard-schema/spec"import { SchemaError } from "@standard-schema/utils"import type { parseCookies } from "./index"import * as Cookie from "./index"
const utf8Encoder = new TextEncoderconst utf8Decoder = new TextDecoder
/** * A cookie options object produced by {@linkcode makeCookieOptions `makeCookieOptions()`}. */export type CookieOptions<T extends StandardSchemaV1> = { /** If `rawName` is not set to `true`, `name` can be any string as it'll be base64url encoded. */ name: string /** * Must be a [Standard Schema](https://standardschema.dev/#what-schema-libraries-implement-the-spec) that is * compatible with JSON. * @see {@linkcode makecookieoptions `makeCookieOptions()`} */ schema: T /** * Additional attributes to append to * [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie) strings created. */ attributes?: `;${string}` | undefined /** * If set to `true`, the `name` will not be base64url'd. This means the given `name` must be a valid cookie name or * a `SyntaxError` will be thrown. */ rawName?: boolean | undefined /** * If set to `true`, this should only be used when `schema` is a string schema or strange or broken behaviour is * likely to be seen. */ rawValue?: boolean | undefined}
const encodeString = (string: string) => btoa(String.fromCharCode(...utf8Encoder.encode(string))) .replaceAll(`=`, ``).replaceAll(`+`, `-`).replaceAll(`/`, `_`)
const decodeString = (string: string) => utf8Decoder.decode( Uint8Array.from(atob(string.replaceAll(`-`, `+`).replaceAll(`_`, `/`)), character => character.charCodeAt(0)))
/** * Make a {@linkcode CookieOptions} object for use with {@linkcode getCookie `getCookie()`}, * {@linkcode setCookie `setCookie()`}, and {@linkcode deleteCookie `deleteCookie()`}. * The schema should be compatible with [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) meaning only * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null), * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type)s, * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type)s, * [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type)s, * [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)s, and * [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects)s can be used. * @example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * ``` */export const makeCookieOptions = <T extends StandardSchemaV1>(options: CookieOptions<T>): CookieOptions<T> => options
/** * Get the validated value from the cookie * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) given by * {@linkcode parseCookies `parseCookies()`}. * @example Client Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * const cookies = parseCookies(document.cookie) * const myCookie = getCookie(cookies, MyCookie) * * console.log(myCookie) // { foo: "bar" } * ``` * @example Server Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * const cookies = parseCookies(request.headers.get("cookie")) * const myCookie = getCookie(cookies, MyCookie) * * console.log(myCookie) // { foo: "bar" } * ``` * @param cookies Returned value of {@linkcode parseCookies `parseCookies()`}. */export function getCookie< T extends StandardSchemaV1>(cookies: Map<string, string>, options: CookieOptions<T>): StandardSchemaV1.InferOutput<T> | undefined { const cookie = cookies.get(options.rawName ? options.name : encodeString(options.name))
if (cookie) { let parsedJson
try { parsedJson = JSON.parse(options.rawValue ? cookie : decodeString(cookie)) } catch {}
const result = options.schema["~standard"].validate(parsedJson)
if (result instanceof Promise) { console.error(`Caught`, TypeError(`Schema validation must be synchronous`))
return }
if (result.issues) { console.error(`Caught`, new SchemaError(result.issues))
return }
return result.value }}
/** * Create a [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie) string for * the given options object and from the given value. * @example Client Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * * document.cookie = setCookie(MyCookie, { foo: "bar" }) * ``` * @example Server Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * * response.headers.set("set-cookie", setCookie(MyCookie, { foo: "bar" })) * ``` */export function setCookie<T extends StandardSchemaV1>( options: CookieOptions<T>, value: StandardSchemaV1.InferInput<T> | undefined): string { const name = options.rawName ? options.name : encodeString(options.name)
if (value === undefined) return Cookie.deleteCookie(name)
const json = JSON.stringify(value)
return Cookie.setCookie(name, options.rawValue ? json : encodeString(json), options)}
/** * Create a [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie) string for * the given options object. * @example Client Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * * document.cookie = deleteCookie(MyCookie) * ``` * @example Server Example * ```ts * const MyCookie = makeCookieOptions({ name: "<unique name>", schema: z.object({ foo: z.string() }) }) * * response.headers.set("set-cookie", deleteCookie(MyCookie)) * ``` */export const deleteCookie = <T extends StandardSchemaV1>(options: CookieOptions<T>): string => Cookie.deleteCookie(options.rawName ? options.name : encodeString(options.name))