File to import as backup.
Parsed and validated backup data.
export async function importBackupFromFile(file: File): Promise<BackupData> {
try {
console.log("[Backup] Reading backup file:", file.name);
// Check file size against the limit
if (file.size > MAX_BACKUP_FILE_SIZE) {
const sizeMB = (file.size / 1024 / 1024).toFixed(2);
const limitMB = (MAX_BACKUP_FILE_SIZE / 1024 / 1024).toFixed(0);
throw new Error(
`Backup file is too large (${sizeMB} MB). Maximum recommended size is ${limitMB} MB.`,
);
} else if (file.size > 5 * 1024 * 1024) {
console.info(
`[Backup] Backup file size: ${(file.size / 1024 / 1024).toFixed(2)} MB`,
);
}
// Read file as text
const fileContent = await file.text();
// Parse JSON with error handling
let backupData: BackupData;
try {
backupData = JSON.parse(fileContent);
} catch (parseError) {
throw new Error(
`Invalid backup file format: ${
parseError instanceof Error ? parseError.message : "JSON parse error"
}`,
);
}
// Validate backup structure
const validation = validateBackup(backupData);
if (!validation.valid) {
throw new Error(
`Backup validation failed: ${validation.errors.join("; ")}`,
);
}
console.log("[Backup] File imported and validated successfully");
return backupData;
} catch (error) {
const message = `Failed to import backup: ${
error instanceof Error ? error.message : "Unknown error"
}`;
console.error("[Backup]", message);
throw new Error(message);
}
}
Imports backup from file and validates it. Reads file content and parses JSON backup format. Warns if file size exceeds recommended threshold.