// Versioned adapter only; TASK-009 owns the user-facing import/export workflow. import { initialRoutine, exerciseDefinitions } from './data/index.js' import { openLocalDatabase } from './localDatabase.js' import { performanceError } from './performanceModel.js' import { performanceKey } from './performanceStorage.js' import { detailError, detailKey } from './workoutDetailStorage.js' import { validEntry } from './strengthStorage.js' const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries', 'workoutDetails'] function validJSON(value) { if (value === null || typeof value === 'string' || typeof value === 'boolean') return true if (typeof value === 'number') return Number.isFinite(value) return typeof value === 'object' && Object.values(value).every(validJSON) } export function parseBackup(input) { let backup try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) } catch { throw new Error('Invalid backup JSON.') } if (backup?.format !== 'workout-tracker' || ![1, 2, 3, 4].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.') if (Object.keys(backup.stores).some((store) => !stores.includes(store))) throw new Error('Unsupported backup store.') if (backup.version < 4 && Object.hasOwn(backup.stores, 'workoutDetails')) throw new Error('Unsupported backup store for this version.') // Version 1 is the legacy adapter envelope with the two original stores. for (const store of stores) { if (store === 'workoutDetails' && backup.version < 4) continue if (backup.version === 1 && store === 'performanceEntries' && backup.stores[store] == null) backup.stores[store] = [] if (!Array.isArray(backup.stores[store])) throw new Error(`Missing backup store: ${store}.`) const keys = new Set() for (const entry of backup.stores[store]) { if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.') keys.add(entry.key) if (store === 'workoutDetails' && (detailError(entry.value) || entry.key !== detailKey(entry.value))) throw new Error('Invalid notes or body-weight entry.') if (store === 'strengthEntries' && (!/^\d{4}-\d{2}-\d{2}:.+/.test(entry.key) || !validEntry(entry.value))) throw new Error('Invalid legacy strength entry.') if (store === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId, entry.value.format))) throw new Error('Invalid detailed performance entry.') if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.') } } return backup } export async function exportBackup() { const db = await openLocalDatabase() return new Promise((resolve, reject) => { const tx = db.transaction(stores, 'readonly') const data = Object.fromEntries(stores.map((store) => [store, []])) for (const name of stores) { const cursor = tx.objectStore(name).openCursor() cursor.onsuccess = () => { if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() } } } tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 4, reference: { exerciseDefinitions, initialRoutine }, stores: data })) } tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) } }) } export async function importBackup(input, { replace = false } = {}) { const backup = parseBackup(input) // Validate everything before opening a write transaction. const db = await openLocalDatabase() return new Promise((resolve, reject) => { const tx = db.transaction(stores, 'readwrite') try { for (const name of stores) { // Old backups never represented observations; replacing them must not erase new data. if (name === 'workoutDetails' && backup.version < 4) continue const store = tx.objectStore(name) if (replace) store.clear() for (const { key, value } of backup.stores[name]) store.add(value, key) } } catch { tx.abort() } tx.oncomplete = () => { db.close(); resolve() } tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Import failed; existing data was left unchanged. Duplicate keys require an explicit replacement.')) } }) }