import { browser } from '$app/environment'; import { writable, get, type Writable } from 'svelte/store'; type StateBin = Record; const STORAGE_KEY = 'stateBin'; const defaultState: StateBin = {}; function createStateBin() { const initialState: StateBin = browser ? JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') : defaultState; const store: Writable = writable(initialState); const writeToStorage = (val: StateBin) => { if (browser) try { localStorage.setItem(STORAGE_KEY, JSON.stringify(val)); } catch (error) { console.error('Failed to write stateBin:', error); } }; return { subscribe: store.subscribe, set: (value) => { writeToStorage(value); store.set(value); }, update: (updateFunction) => { const updatedStore = updateFunction(get(store)); writeToStorage(updatedStore); store.set(updatedStore); }, reset: () => { writeToStorage(defaultState); store.set(defaultState); }, get: () => get(store), setKey: (key: string, value: unknown) => { const currentStore = get(store); const updatedStore = { ...currentStore, [key]: value }; writeToStorage(updatedStore); store.set(updatedStore); }, removeKey: (key: string) => { const currentStore = get(store); const { [key]: _, ...rest } = currentStore; writeToStorage(rest); store.set(rest); } }; } const stateBin = createStateBin(); export default stateBin;