import config from '@/application/config' import type { HttpResponse } from '@/application/types' import type { BaseStorage } from '@/storage/baseStorage' export function uuidv4() { return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))).toString(16)) } export function unduplicateArray(array: any[]) { const arrayToProcess = typeof array.flat === 'function' ? array.flat() : array return [...new Set(arrayToProcess)] } export async function downloadCache(endpoint: string, storage: BaseStorage) { const request = await fetch(`${config.server_endpoint}/cache/${endpoint}`) const response = (await request.json()) as HttpResponse if (!response.success) { console.error(`Failed to download ${endpoint}:`, response.message) return } const items = response.data ?? [] const serverItemIds = new Set(items.map((item) => item.id)) // Remove items that don't exist on server const existingItems = await storage.getAll() for (const existingItem of existingItems) { if (!serverItemIds.has(existingItem.id)) { await storage.delete(existingItem.id) } } // Update or add new items for (const item of items) { let overwrite = false const existingItem = await storage.getById(item.id) if (!existingItem || item.updatedAt > existingItem.updatedAt) { overwrite = true } await storage.add(item, overwrite) } }