UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

309 lines (300 loc) 8.63 kB
/*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/cookie.ts var cookie_exports = {}; __export(cookie_exports, { CookieService: () => CookieService, listenCookieChange: () => listenCookieChange, parseCookie: () => parseCookie, serializeCookie: () => serializeCookie }); module.exports = __toCommonJS(cookie_exports); // src/convert.ts function toBoolean(val) { return val ? val !== "false" : false; } // src/env.ts var import_meta = {}; var _envShim = /* @__PURE__ */ Object.create(null); var _getEnv = (useShim) => globalThis.process?.env || // Node.js/Bun import_meta.env || // Vite env globalThis.Deno?.env.toObject() || // Deno env globalThis.__env__ || // Custom env (useShim ? _envShim : globalThis); var envs = new Proxy(_envShim, { get(_, prop) { const env = _getEnv(); return env[prop] ?? _envShim[prop]; }, has(_, prop) { const env = _getEnv(); return prop in env || prop in _envShim; }, set(_, prop, value) { const env = _getEnv(true); env[prop] = value; return true; }, deleteProperty(_, prop) { if (!prop) { return false; } const env = _getEnv(true); delete env[prop]; return true; }, ownKeys() { const env = _getEnv(); return Object.keys(env); } }); var nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || ""; // src/process.ts var _process = globalThis.process || /* @__PURE__ */ Object.create(null); var processShims = { versions: {} }; var process2 = new Proxy(_process, { get(target, prop) { if (prop === "env") { return envs; } if (prop in target) { return target[prop]; } if (prop in processShims) { return processShims[prop]; } } }); var platform = _process.platform || ""; // src/is.ts var isDate = (val) => toString.call(val) === "[object Date]"; var isBrowser = typeof window !== "undefined"; var isAndroid = isBrowser ? /(android)/i.test(navigator.userAgent) : false; var match = isBrowser ? window.matchMedia || window.msMatchMedia : void 0; var isMobile = isBrowser ? match?.("(pointer:coarse)")?.matches : false; var isCrawler = isBrowser && (!("onscroll" in window) || /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent)); var isCI = toBoolean(envs.CI); var isNodeTest = nodeENV === "test" || toBoolean(envs.TEST); var isWindows = /^win/i.test(platform); var isLinux = /^linux/i.test(platform); var isMacOS = /^darwin/i.test(platform); // src/cookie.ts var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; function parseCookie(str, options) { if (typeof str !== "string") { throw new TypeError("argument str must be a string"); } const obj = {}; const opt = options || {}; const dec = opt.decode || decode; let index = 0; while (index < str.length) { const eqIdx = str.indexOf("=", index); if (eqIdx === -1) { break; } let endIdx = str.indexOf(";", index); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { index = str.lastIndexOf(";", eqIdx - 1) + 1; continue; } const key = str.slice(index, eqIdx).trim(); if (obj[key] === void 0) { let val = str.slice(eqIdx + 1, endIdx).trim(); if (val.charCodeAt(0) === 34) { val = val.slice(1, -1); } obj[key] = tryDecode(val, dec); } index = endIdx + 1; } return obj; } function serializeCookie(name, value, options) { const opt = options || {}; const enc = opt.encode || encode; if (typeof enc !== "function") { throw new TypeError("option encode is invalid"); } if (!fieldContentRegExp.test(name)) { throw new TypeError("argument name is invalid"); } const encValue = enc(value); if (value && !fieldContentRegExp.test(value)) { throw new TypeError("argument val is invalid"); } let str = `${name}=${encValue}`; if (null != opt.maxAge) { const maxAge = opt.maxAge - 0; if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) { throw new TypeError("option maxAge is invalid"); } str += `; Max-Age=${Math.floor(maxAge)}`; } if (opt.domain) { if (!fieldContentRegExp.test(opt.domain)) { throw new TypeError("option domain is invalid"); } str += `; Domain=${opt.domain}`; } if (opt.path) { if (!fieldContentRegExp.test(opt.path)) { throw new TypeError("option path is invalid"); } str += `; Path=${opt.path}`; } if (opt.expires) { const expires = opt.expires; if (!isDate(expires) || Number.isNaN(expires.valueOf())) { throw new TypeError("option expires is invalid"); } str += `; Expires=${expires.toUTCString()}`; } if (opt.httpOnly) { str += "; HttpOnly"; } if (opt.secure) { str += "; Secure"; } if (opt.priority) { const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; switch (priority) { case "low": str += "; Priority=Low"; break; case "medium": str += "; Priority=Medium"; break; case "high": str += "; Priority=High"; break; default: throw new TypeError("option priority is invalid"); } } if (opt.sameSite) { const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; switch (sameSite) { case true: str += "; SameSite=Strict"; break; case "lax": str += "; SameSite=Lax"; break; case "strict": str += "; SameSite=Strict"; break; case "none": str += "; SameSite=None"; break; default: throw new TypeError("option sameSite is invalid"); } } return str; } function decode(str) { return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; } function encode(val) { return encodeURIComponent(val); } function tryDecode(str, decode2) { try { return decode2(str); } catch (e) { return str; } } var listenCookieChange = (callback, interval = 500) => { let lastCookie = document.cookie; setInterval(() => { const { cookie } = document; if (cookie !== lastCookie) { try { callback({ oldCookie: parseCookie(lastCookie), newCookie: parseCookie(cookie) }); } finally { lastCookie = cookie; } } }, interval); }; var CookieService = class { constructor(nodeEnv, env, cookieDomain) { this.nodeEnv = nodeEnv; this.env = env; this.domain = cookieDomain; this.tokenName = `token_${this.env}`; } get(name, options) { if (typeof window === "undefined") return void 0; try { const cookies = parseCookie(document.cookie, options); return cookies[name]; } catch (error) { console.error({ error }); return void 0; } } set(key, value, options) { const defaultOptions = { secure: true, path: "/", domain: this.domain, priority: "Medium", httpOnly: false, ...options }; try { document.cookie = serializeCookie(key, value, defaultOptions); } catch (error) { console.error({ error }); } } setToken(token) { document.cookie = this.env === "development" ? `${this.tokenName}=${token}; path=/; Secure` : `${this.tokenName}=${token}; path=/; Domain=${this.domain}; Secure`; } getToken() { const token = this.get(this.tokenName); return token; } clearToken() { document.cookie = this.env === "development" ? `${this.tokenName}=; path=/; Secure` : `${this.tokenName}=; path=/; Domain=${this.domain}; Secure`; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CookieService, listenCookieChange, parseCookie, serializeCookie });