UNPKG

@sovgut/state

Version:

<p align="center"> <b>A lightweight, type-safe, and reactive state management library for modern web applications</b> </p>

461 lines (460 loc) 14.5 kB
var y = Object.defineProperty; var k = (l, t, e) => t in l ? y(l, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[t] = e; var h = (l, t, e) => k(l, typeof t != "symbol" ? t + "" : t, e); const i = class i { /** * Gets or creates the event registry for a specific class * @param target - The class constructor function * @returns The event registry for the target class */ static getRegistry(t) { return i.eventRegistry.has(t) || i.eventRegistry.set(t, { events: /* @__PURE__ */ new Map(), onceEvents: /* @__PURE__ */ new Map() }), i.eventRegistry.get(t); } /** * Adds an event listener for the specified event * @template T - The type of data passed to the callback * @param event - The name of the event to listen for * @param callback - The callback function to execute when the event is emitted */ static on(t, e) { const r = i.getRegistry(this); r.events.has(t) || r.events.set(t, /* @__PURE__ */ new Set()), r.events.get(t).add(e); } /** * Adds a one-time event listener for the specified event * @template T - The type of data passed to the callback * @param event - The name of the event to listen for * @param callback - The callback function to execute once when the event is emitted */ static once(t, e) { const r = i.getRegistry(this); r.onceEvents.has(t) || r.onceEvents.set(t, /* @__PURE__ */ new Set()), r.onceEvents.get(t).add(e); } /** * Removes an event listener for the specified event * @template T - The type of data passed to the callback * @param event - The name of the event * @param callback - The callback function to remove */ static off(t, e) { var s, c; const r = i.getRegistry(this); (s = r.events.get(t)) == null || s.delete(e), (c = r.onceEvents.get(t)) == null || c.delete(e); } /** * Emits an event with the given data to all registered listeners * @template T - The type of data being emitted * @param event - The name of the event to emit * @param data - The data to pass to the event listeners */ static emit(t, e) { var c; const r = i.getRegistry(this); (c = r.events.get(t)) == null || c.forEach((a) => a(e)); const s = r.onceEvents.get(t); s && (s.forEach((a) => a(e)), r.onceEvents.delete(t)); } /** * Removes all event listeners for all events */ static removeAllListeners() { const t = i.getRegistry(this); t.events.clear(), t.onceEvents.clear(); } /** * Removes all listeners for a specific event * @param event - The name of the event */ static removeListener(t) { const e = i.getRegistry(this); e.events.delete(t), e.onceEvents.delete(t); } /** * Gets the number of listeners for a specific event * @param event - The name of the event * @returns The total number of listeners (regular + once) */ static listenerCount(t) { var c, a; const e = i.getRegistry(this), r = ((c = e.events.get(t)) == null ? void 0 : c.size) || 0, s = ((a = e.onceEvents.get(t)) == null ? void 0 : a.size) || 0; return r + s; } /** * Gets an array of all event names that have listeners * @returns Array of event names */ static eventNames() { const t = i.getRegistry(this), e = /* @__PURE__ */ new Set([...t.events.keys(), ...t.onceEvents.keys()]); return Array.from(e); } }; h(i, "eventRegistry", /* @__PURE__ */ new Map()); let g = i; class m extends Error { /** * Creates a new StateDoesNotExist error * @param key - The key that was not found * @param storage - The storage type where the key was not found */ constructor(t, e = "storage") { super(`Key "${t}" does not exist in the ${e}.`), this.key = t, this.storage = e, this.name = "KeyDoesNotExist"; } } class b extends Error { /** * Creates a new StateInvalidCast error * @param key - The key of the value that failed to cast * @param storage - The storage type where the value is stored * @param value - The actual value that failed to cast * @param type - The target type that the cast failed to */ constructor(t, e = "storage", r, s) { super(`Cannot cast value for key "${t}" in ${e} to type "${s}". Value: ${r}`), this.key = t, this.storage = e, this.value = r, this.type = s, this.name = "CannotCastValue"; } } class o extends g { static get(t, e = {}) { const r = localStorage.getItem(t); if (r === null) { if (e.strict) throw new m(t, "localStorage"); return e.fallback !== void 0 ? e.fallback : void 0; } try { let s = JSON.parse(r); if (e.fallback !== void 0 && (s == null || s === "" || Array.isArray(s) && s.length === 0 || typeof s == "object" && Object.keys(s).length === 0)) return e.fallback; if (e.cast) switch (e.cast) { case "string": s = String(s); break; case "number": s = Number(s); break; case "boolean": s = !!s; break; case "bigint": s = BigInt(String(s)); break; } return s; } catch { if (e.cast) try { switch (e.cast) { case "string": return r; case "number": return Number(r); case "boolean": return r === "true" || r === "1"; case "bigint": return BigInt(r); } } catch { if (e.strict) throw new b(t, "localStorage", r, e.cast); return e.fallback !== void 0 ? e.fallback : void 0; } return r; } } /** * Stores a value in local storage * @template T - The type of the value to store * @param key - The key to store the value under * @param value - The value to store (will be JSON stringified) * @emits Will emit an event with the key and new value */ static set(t, e) { const r = typeof e == "string" ? e : JSON.stringify(e); localStorage.setItem(t, r), o.emit(t, e); } /** * Removes a value from local storage * @param key - The key to remove * @emits Will emit an event with the key and null value */ static remove(t) { localStorage.removeItem(t), o.emit(t, null); } /** * Clears all values from local storage * @emits Will emit an event for each removed key with null value */ static clear() { Object.keys(localStorage).forEach((t) => { localStorage.removeItem(t), o.emit(t, null); }); } /** * Checks if a key exists in local storage * @param key - The key to check * @returns True if the key exists, false otherwise */ static has(t) { return localStorage.getItem(t) !== null; } } const n = class n extends g { static get(t, e = {}) { const r = n.storage.get(t); if (r === void 0) { if (e.strict) throw new m(t, "memory"); return e.fallback !== void 0 ? e.fallback : void 0; } if (e.fallback !== void 0 && (r == null || r === "" || Array.isArray(r) && r.length === 0 || typeof r == "object" && r !== null && Object.keys(r).length === 0)) return e.fallback; if (e.cast) try { switch (e.cast) { case "string": return String(r); case "number": return Number(r); case "boolean": return !!r; case "bigint": return BigInt(String(r)); } } catch { if (e.strict) throw new b(t, "memory", r, e.cast); return e.fallback !== void 0 ? e.fallback : void 0; } return r; } /** * Stores a value in memory state * @template T - The type of the value to store * @param key - The key to store the value under * @param value - The value to store * @emits Will emit an event with the key and new value */ static set(t, e) { n.storage.set(t, e), n.emit(t, e); } /** * Removes a value from memory state * @param key - The key to remove * @emits Will emit an event with the key and null value */ static remove(t) { n.storage.delete(t), n.emit(t, null); } /** * Clears all values from memory state * @emits Will emit an event for each removed key with null value */ static clear() { const t = Array.from(n.storage.keys()); n.storage.clear(), t.forEach((e) => n.emit(e, null)); } /** * Checks if a key exists in memory state * @param key - The key to check * @returns True if the key exists, false otherwise */ static has(t) { return n.storage.has(t); } }; h(n, "storage", /* @__PURE__ */ new Map()); let d = n; class u extends g { static get(t, e = {}) { const r = sessionStorage.getItem(t); if (r === null) { if (e.strict) throw new m(t, "sessionStorage"); return e.fallback !== void 0 ? e.fallback : void 0; } try { let s = JSON.parse(r); if (e.fallback !== void 0 && (s == null || s === "" || Array.isArray(s) && s.length === 0 || typeof s == "object" && Object.keys(s).length === 0)) return e.fallback; if (e.cast) switch (e.cast) { case "string": s = String(s); break; case "number": s = Number(s); break; case "boolean": s = !!s; break; case "bigint": s = BigInt(String(s)); break; } return s; } catch { if (e.cast) try { switch (e.cast) { case "string": return r; case "number": return Number(r); case "boolean": return r === "true" || r === "1"; case "bigint": return BigInt(r); } } catch { if (e.strict) throw new b(t, "sessionStorage", r, e.cast); return e.fallback !== void 0 ? e.fallback : void 0; } return r; } } /** * Stores a value in session storage * @template T - The type of the value to store * @param key - The key to store the value under * @param value - The value to store (will be JSON stringified) * @emits Will emit an event with the key and new value */ static set(t, e) { const r = typeof e == "string" ? e : JSON.stringify(e); sessionStorage.setItem(t, r), u.emit(t, e); } /** * Removes a value from session storage * @param key - The key to remove * @emits Will emit an event with the key and null value */ static remove(t) { sessionStorage.removeItem(t), u.emit(t, null); } /** * Clears all values from session storage * @emits Will emit an event for each removed key with null value */ static clear() { Object.keys(sessionStorage).forEach((t) => { sessionStorage.removeItem(t), u.emit(t, null); }); } /** * Checks if a key exists in session storage * @param key - The key to check * @returns True if the key exists, false otherwise */ static has(t) { return sessionStorage.getItem(t) !== null; } } class f extends g { static get(t, e = {}) { const s = document.cookie.split(";").find((a) => a.trim().startsWith(`${t}=`)); if (!s) { if (e.strict) throw new m(t, "cookies"); return e.fallback !== void 0 ? e.fallback : void 0; } const c = decodeURIComponent(s.split("=")[1]); try { let a = JSON.parse(c); if (e.fallback !== void 0 && (a == null || a === "" || Array.isArray(a) && a.length === 0 || typeof a == "object" && Object.keys(a).length === 0)) return e.fallback; if (e.cast) switch (e.cast) { case "string": a = String(a); break; case "number": a = Number(a); break; case "boolean": a = !!a; break; case "bigint": a = BigInt(String(a)); break; } return a; } catch { if (e.cast) try { switch (e.cast) { case "string": return c; case "number": return Number(c); case "boolean": return c === "true" || c === "1"; case "bigint": return BigInt(c); } } catch { if (e.strict) throw new b(t, "cookies", c, e.cast); return e.fallback !== void 0 ? e.fallback : void 0; } return c; } } /** * Stores a value in cookies * @template T - The type of the value to store * @param key - The key to store the value under * @param value - The value to store (will be JSON stringified and URI encoded) * @param options - Cookie configuration options * @emits Will emit an event with the key and new value */ static set(t, e, r) { const s = JSON.stringify(e), c = encodeURIComponent(s); let a = `${t}=${c}`; if (r) { if (r.expires) { const v = r.expires instanceof Date ? r.expires : new Date(Date.now() + r.expires * 24 * 60 * 60 * 1e3); a += `; expires=${v.toUTCString()}`; } r.maxAge !== void 0 && (a += `; max-age=${r.maxAge}`), r.domain && (a += `; domain=${r.domain}`), r.path && (a += `; path=${r.path}`), r.secure && (a += "; secure"), r.sameSite && (a += `; samesite=${r.sameSite}`); } document.cookie = a, f.emit(t, e); } /** * Removes a cookie * @param key - The key of the cookie to remove * @emits Will emit an event with the key and null value */ static remove(t) { document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`, f.emit(t, null); } /** * Clears all cookies accessible to the current document * @emits Will emit an event for each removed cookie with null value */ static clear() { document.cookie.split(";").forEach((e) => { const r = e.indexOf("="), s = r > -1 ? e.substring(0, r).trim() : e.trim(); s && (document.cookie = `${s}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`, f.emit(s, null)); }); } /** * Checks if a cookie exists * @param key - The key to check * @returns True if the cookie exists, false otherwise */ static has(t) { return document.cookie.split(";").some((e) => e.trim().startsWith(`${t}=`)); } } export { f as CookieState, o as LocalState, d as MemoryState, u as SessionState, m as StateDoesNotExist, b as StateInvalidCast };