// // IdentityContainerStore.swift // Prisme // // Author: Simon-Pierre Boucher // import Foundation import Observation import WebKit /// Owns the list of identity containers and hands out their partitioned /// `WKWebsiteDataStore`s. Container IDs are persisted in UserDefaults so the /// same data stores are recovered across launches. @MainActor @Observable final class IdentityContainerStore { private static let defaultsKey = "prisme.identityContainers" private(set) var all: [IdentityContainer] init() { if let data = UserDefaults.standard.data(forKey: Self.defaultsKey), let decoded = try? JSONDecoder().decode([IdentityContainer].self, from: data), !decoded.isEmpty { all = decoded } else { all = IdentityContainer.makeDefaults() persist() } } func container(for id: IdentityContainer.ID) -> IdentityContainer? { all.first { $0.id == id } } /// The partitioned data store for a container. Same UUID → same /// persistent store, fully isolated from every other container. func dataStore(for id: IdentityContainer.ID) -> WKWebsiteDataStore { WKWebsiteDataStore(forIdentifier: id) } private func persist() { if let data = try? JSONEncoder().encode(all) { UserDefaults.standard.set(data, forKey: Self.defaultsKey) } } }