import { uuid } from "@noya-app/noya-utils"; import { Observable } from "@noya-app/observable"; import { getClientAnimalFromName, getClientImageUrl, randomClientIdentity, } from "./defaultNames"; const CLIENT_ID_STORAGE_KEY = "noya-client-id"; const CLIENT_NAME_STORAGE_KEY = "noya-client-name"; const CLIENT_IMAGE_STORAGE_KEY = "noya-client-image"; export const clientId$ = new Observable(undefined); export const clientName$ = new Observable(undefined); export const clientImage$ = new Observable(undefined); const safeGetItem = (key: string) => { try { return typeof localStorage !== "undefined" ? localStorage.getItem(key) : null; } catch { return null; } }; const safeSetItem = (key: string, value: string) => { try { if (typeof localStorage !== "undefined") { localStorage.setItem(key, value); } } catch { // Ignore quota/security errors } }; const safeRemoveItem = (key: string) => { try { if (typeof localStorage !== "undefined") { localStorage.removeItem(key); } } catch { // Ignore quota/security errors } }; if (typeof window !== "undefined") { const storedClientId = safeGetItem(CLIENT_ID_STORAGE_KEY); if (storedClientId) { clientId$.set(storedClientId); } else { const newClientId = uuid(); safeSetItem(CLIENT_ID_STORAGE_KEY, newClientId); clientId$.set(newClientId); } let storedClientName = safeGetItem(CLIENT_NAME_STORAGE_KEY) ?? undefined; let storedClientImage = safeGetItem(CLIENT_IMAGE_STORAGE_KEY) ?? undefined; const newIdentity = randomClientIdentity(); if (!storedClientName) { storedClientName = newIdentity.name; safeSetItem(CLIENT_NAME_STORAGE_KEY, storedClientName); } if (!storedClientImage) { const animal = (storedClientName && getClientAnimalFromName(storedClientName)) ?? newIdentity.animal; if (animal) { storedClientImage = getClientImageUrl(animal); safeSetItem(CLIENT_IMAGE_STORAGE_KEY, storedClientImage); } } clientName$.set(storedClientName); clientImage$.set(storedClientImage); } export function setClientName(name: string | undefined) { clientName$.set(name); if (typeof window === "undefined") return; if (name === undefined) { safeRemoveItem(CLIENT_NAME_STORAGE_KEY); } else { safeSetItem(CLIENT_NAME_STORAGE_KEY, name); } } export function setClientId(id: string | undefined) { clientId$.set(id); if (typeof window === "undefined") return; if (id === undefined) { safeRemoveItem(CLIENT_ID_STORAGE_KEY); } else { safeSetItem(CLIENT_ID_STORAGE_KEY, id); } } export function setClientImage(image: string | undefined) { clientImage$.set(image); if (typeof window === "undefined") return; if (image === undefined) { safeRemoveItem(CLIENT_IMAGE_STORAGE_KEY); } else { safeSetItem(CLIENT_IMAGE_STORAGE_KEY, image); } }