Compare commits

...
Author SHA1 Message Date
Chad Curtis 4be7f67cac cleanup v2 2025-10-21 14:40:06 +00:00
Chad Curtis e1da355392 cleanup 2025-10-21 14:40:06 +00:00
Chad Curtis e47413559b Init 2025-10-21 14:40:06 +00:00
7 changed files with 1264 additions and 13 deletions

No files matched your search

+418
View File
@@ -0,0 +1,418 @@
import React, { useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { AlertTriangle, Trash2, CheckCircle, Loader2, HardDrive } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { cn } from '@/lib/utils';
import { importFullSystem, validateExportFile, type ImportProgress, type ImportValidation } from '@/lib/fullSystemImport';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { FileUploadArea } from '@/components/ui/file-upload-area';
interface FullSystemImportDialogProps {
onImport?: () => void;
disabled?: boolean;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
interface ImportState {
selectedFile: File | null;
validation: ImportValidation | null;
isImporting: boolean;
importProgress: ImportProgress | null;
error: string | null;
isDragOver: boolean;
showWarningDialog: boolean;
importComplete: boolean;
}
export function FullSystemImportDialog({
onImport,
disabled = false,
className,
open,
onOpenChange
}: FullSystemImportDialogProps) {
// Use controlled state if props are provided, otherwise use internal state
const [internalIsOpen, setInternalIsOpen] = useState(false);
const isOpen = open !== undefined ? open : internalIsOpen;
const setIsOpen = onOpenChange || setInternalIsOpen;
// Consolidated state management
const [state, setState] = useState<ImportState>({
selectedFile: null,
validation: null,
isImporting: false,
importProgress: null,
error: null,
isDragOver: false,
showWarningDialog: false,
importComplete: false
});
const { toast } = useToast();
const { fs } = useFS();
const updateState = (updates: Partial<ImportState>) => {
setState(prev => ({ ...prev, ...updates }));
};
const handleFileSelect = async (file: File) => {
if (!file.name.toLowerCase().endsWith('.zip')) {
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
try {
const validationResult = await validateExportFile(file);
updateState({ validation: validationResult });
if (!validationResult.isValid) {
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
} catch (err) {
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
}
};
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: true });
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: false });
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
updateState({ isDragOver: false });
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
const file = files[0];
if (!file.name.toLowerCase().endsWith('.zip')) {
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
validateExportFile(file).then(validationResult => {
updateState({ validation: validationResult });
if (!validationResult.isValid) {
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
}).catch(err => {
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
});
}
}, []);
const handleFileRemove = () => {
updateState({ selectedFile: null, validation: null, error: null, importComplete: false });
};
const handleImportStart = () => {
if (!state.selectedFile || !state.validation?.isValid) return;
updateState({ showWarningDialog: true });
};
const handleImportConfirm = async () => {
if (!state.selectedFile) return;
updateState({ showWarningDialog: false, isImporting: true, importProgress: null, error: null });
try {
await importFullSystem(state.selectedFile, fs, (progress) => {
updateState({ importProgress: progress });
});
updateState({ importComplete: true });
toast({
title: 'Import Successful',
description: 'Your workspace has been completely restored.',
});
if (onImport) onImport();
setTimeout(() => {
setIsOpen(false);
window.location.reload();
}, 2000);
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Import failed';
updateState({ error: errorMsg, importProgress: null, isImporting: false });
toast({
title: 'Import Failed',
description: errorMsg,
variant: 'destructive',
});
}
};
const handleClose = () => {
if (!state.isImporting) {
setIsOpen(false);
updateState({
selectedFile: null,
validation: null,
error: null,
importProgress: null,
importComplete: false
});
}
};
const getStageDescription = (stage: ImportProgress['stage']): string => {
const descriptions = {
extracting: 'Extracting ZIP file...',
validating: 'Validating export...',
creating_temp: 'Setting up workspace...',
importing: 'Importing files...',
replacing: 'Replacing system...',
cleanup: 'Cleaning up...',
complete: 'Import completed!'
};
return descriptions[stage] || 'Processing...';
};
const isControlled = open !== undefined && onOpenChange !== undefined;
return (
<>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{!isControlled && (
<DialogTrigger asChild>
<Button
variant="outline"
disabled={disabled}
className={cn("gap-2 text-destructive border-destructive hover:bg-destructive hover:text-destructive-foreground", className)}
>
<HardDrive className="h-4 w-4" />
Import System
</Button>
</DialogTrigger>
)}
<DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<HardDrive className="h-5 w-5 text-destructive" />
Import System
</DialogTitle>
<DialogDescription>
Select a Shakespeare export file to replace your entire workspace.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{!state.isImporting && (
<Alert className="border-destructive/50 bg-destructive/5">
<AlertTriangle className="h-4 w-4 text-destructive" />
<AlertDescription className="text-destructive">
<strong>Warning:</strong> This action will <strong>completely replace</strong> your Shakespeare workspace with the imported data.
All current projects, AI settings, Git credentials, and preferences will be <strong>permanently deleted</strong>.
</AlertDescription>
</Alert>
)}
{!state.isImporting && !state.importComplete && (
<>
<FileUploadArea
selectedFile={state.selectedFile}
isDragOver={state.isDragOver}
isValid={state.validation?.isValid ?? false}
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
disabled={state.isImporting}
accept=".zip"
className="mb-4"
>
<div className="space-y-3">
<div className="flex justify-center">
{state.selectedFile ? (
state.validation?.isValid ? (
<CheckCircle className="h-8 w-8 text-green-600" />
) : (
<Trash2 className="h-8 w-8 text-destructive" />
)
) : (
<HardDrive className="h-8 w-8 text-muted-foreground" />
)}
</div>
<div>
{state.selectedFile ? (
<div className="space-y-2">
<p className="text-sm font-medium">{state.selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(state.selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
<button
onClick={(e) => {
e.stopPropagation();
handleFileRemove();
}}
className="text-xs text-destructive hover:underline"
>
Remove file
</button>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop ZIP file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
Only Shakespeare export ZIP files
</p>
</div>
)}
</div>
</div>
</FileUploadArea>
{state.validation && (
<div className="text-sm space-y-2 p-3 bg-muted rounded">
<div className="flex justify-between">
<span>Projects:</span>
<span className="font-medium">{state.validation.projectCount}</span>
</div>
<div className="flex justify-between">
<span>Files:</span>
<span className="font-medium">{state.validation.totalFiles}</span>
</div>
{state.validation.errors.length > 0 && (
<div className="text-xs text-destructive">
{state.validation.errors.slice(0, 2).join(', ')}
</div>
)}
</div>
)}
{state.error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{state.error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleImportStart}
disabled={!state.selectedFile || !state.validation?.isValid}
variant="destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Replace Entire System
</Button>
</div>
</>
)}
{state.isImporting && state.importProgress && (
<div className="space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{getStageDescription(state.importProgress.stage)}
</div>
<Progress value={state.importProgress.progress} className="w-full" />
<div className="flex justify-between text-xs text-muted-foreground">
<span>{state.importProgress.message}</span>
<span>{Math.round(state.importProgress.progress)}%</span>
</div>
</div>
<Alert>
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Please do not close this window during import.
</AlertDescription>
</Alert>
</div>
)}
{state.importComplete && (
<Alert className="border-green-500/50 bg-green-500/5">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-600">
Import completed successfully! Reloading page...
</AlertDescription>
</Alert>
)}
</div>
</DialogContent>
</Dialog>
<AlertDialog open={state.showWarningDialog} onOpenChange={(open) => updateState({ showWarningDialog: open })}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Confirm Complete System Replacement
</AlertDialogTitle>
<AlertDialogDescription className="space-y-3">
<p>
You are about to <strong>completely replace</strong> your workspace with imported data.
</p>
<div className="bg-destructive/10 border border-destructive/20 rounded p-3">
<p className="text-sm font-medium text-destructive mb-2">This will permanently delete:</p>
<ul className="list-disc list-inside text-sm text-destructive space-y-1">
<li>All current projects and their files</li>
<li>AI provider settings and API keys</li>
<li>Git credentials and repository settings</li>
<li>User preferences and theme settings</li>
<li>All cached data and temporary files</li>
</ul>
</div>
{state.validation && (
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded p-3">
<p className="text-sm font-medium text-green-800 dark:text-green-200 mb-2">Import will restore:</p>
<ul className="list-disc list-inside text-sm text-green-700 dark:text-green-300 space-y-1">
<li>{state.validation.projectCount} projects</li>
<li>{state.validation.totalFiles} total files</li>
{state.validation.hasConfig && <li>Settings, themes, and preferences</li>}
</ul>
</div>
)}
<p className="text-destructive font-medium">
This action cannot be undone. Are you absolutely sure?
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleImportConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, Replace Everything
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
+129
View File
@@ -0,0 +1,129 @@
import React, { useRef } from 'react';
import { cn } from '@/lib/utils';
interface FileUploadAreaProps {
selectedFile: File | null;
isDragOver: boolean;
isValid: boolean;
onFileSelect: (file: File) => void;
onFileRemove: () => void;
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
disabled?: boolean;
accept?: string;
className?: string;
children?: React.ReactNode;
}
export function FileUploadArea({
selectedFile,
isDragOver,
isValid,
onFileSelect,
onFileRemove,
onDragOver,
onDragLeave,
onDrop,
disabled = false,
accept = '.zip',
className,
children
}: FileUploadAreaProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleClickUpload = () => {
fileInputRef.current?.click();
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
onFileSelect(files[0]);
}
};
return (
<div
className={cn(
"relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer",
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50",
selectedFile && isValid && "border-green-500/50 bg-green-500/5",
selectedFile && !isValid && "border-destructive/50 bg-destructive/5",
disabled && "opacity-50 cursor-not-allowed",
className
)}
onClick={!disabled ? handleClickUpload : undefined}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
<input
ref={fileInputRef}
type="file"
onChange={handleFileChange}
accept={accept}
className="hidden"
disabled={disabled}
/>
{children || (
<div className="space-y-3">
<div className="flex justify-center">
{selectedFile ? (
isValid ? (
<div className="h-8 w-8 rounded-full bg-green-100 flex items-center justify-center">
<svg className="h-4 w-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
) : (
<div className="h-8 w-8 rounded-full bg-red-100 flex items-center justify-center">
<svg className="h-4 w-4 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
)
) : (
<div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
<svg className="h-4 w-4 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
</div>
)}
</div>
<div>
{selectedFile ? (
<div className="space-y-2">
<p className="text-sm font-medium">{selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
<button
onClick={(e) => {
e.stopPropagation();
onFileRemove();
}}
className="text-xs text-destructive hover:underline"
disabled={disabled}
>
Remove file
</button>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
{accept === '.zip' ? 'ZIP files only' : `Accepted files: ${accept}`}
</p>
</div>
)}
</div>
</div>
)}
</div>
);
}
+292
View File
@@ -0,0 +1,292 @@
import { describe, it, expect, beforeEach } from 'vitest';
import JSZip from 'jszip';
import { FullSystemImporter, validateExportFile } from './fullSystemImport';
import type { JSRuntimeFS } from './JSRuntime';
// Simplified mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files = new Map<string, Uint8Array | string>();
private dirs = new Set<string>(['/']);
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options?: { encoding?: string } | string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`ENOENT: no such file or directory, open '${path}'`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8' || encoding) {
if (content instanceof Uint8Array) {
return new TextDecoder().decode(content);
}
return content as string;
}
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
const dirPath = path.split('/').slice(0, -1).join('/') || '/';
this.dirs.add(dirPath);
this.files.set(path, data);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>> {
const items: string[] = [];
const prefix = path === '/' ? '/' : `${path}/`;
for (const filePath of this.files.keys()) {
if (filePath.startsWith(prefix)) {
const relativePath = filePath.slice(prefix.length);
const firstSegment = relativePath.split('/')[0];
if (firstSegment && !items.includes(firstSegment)) {
items.push(firstSegment);
}
}
}
for (const dirPath of this.dirs) {
if (dirPath.startsWith(prefix) && dirPath !== path) {
const relativePath = dirPath.slice(prefix.length);
const firstSegment = relativePath.split('/')[0];
if (firstSegment && !items.includes(firstSegment)) {
items.push(firstSegment);
}
}
}
if (options?.withFileTypes) {
return items.map(name => ({
name,
isDirectory: () => this.dirs.has(path === '/' ? `/${name}` : `${path}/${name}`),
isFile: () => this.files.has(path === '/' ? `/${name}` : `${path}/${name}`)
}));
}
return items;
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
if (options?.recursive) {
const parts = path.split('/').filter(Boolean);
let currentPath = path.startsWith('/') ? '/' : '';
for (const part of parts) {
currentPath = currentPath === '/' ? `/${part}` : `${currentPath}/${part}`;
this.dirs.add(currentPath);
}
} else {
this.dirs.add(path);
}
}
async stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; size?: number; mtimeMs?: number }> {
const isFile = this.files.has(path);
const isDir = this.dirs.has(path);
if (!isFile && !isDir) {
throw new Error(`ENOENT: no such file or directory, stat '${path}'`);
}
return {
isDirectory: () => isDir,
isFile: () => isFile,
size: isFile ? (this.files.get(path)?.length || 0) : undefined,
mtimeMs: Date.now()
};
}
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; size?: number; mtimeMs?: number }> {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
if (!this.files.has(path)) {
throw new Error(`ENOENT: no such file or directory, unlink '${path}'`);
}
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
if (!this.dirs.has(path)) {
throw new Error(`ENOENT: no such file or directory, rmdir '${path}'`);
}
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
const content = this.files.get(oldPath);
if (content !== undefined) {
this.files.set(newPath, content);
this.files.delete(oldPath);
}
if (this.dirs.has(oldPath)) {
this.dirs.add(newPath);
this.dirs.delete(oldPath);
}
}
async readlink(): Promise<string> {
throw new Error('Symlinks not supported');
}
async symlink(): Promise<void> {
throw new Error('Symlinks not supported');
}
clear(): void {
this.files.clear();
this.dirs.clear();
this.dirs.add('/');
}
}
// Helper functions
async function createValidExportZip(): Promise<File> {
const zip = new JSZip();
// Add project
zip.folder('projects/test-project/src');
zip.file('projects/test-project/package.json', JSON.stringify({ name: 'test-project' }));
zip.file('projects/test-project/src/index.ts', 'console.log("Hello");');
// Add config
zip.file('config/ai.json', JSON.stringify({ provider: 'openai' }));
// Add localStorage
zip.file('localStorage.json', JSON.stringify({
'nostr:app-config': JSON.stringify({ theme: 'dark' })
}));
const content = await zip.generateAsync({ type: 'arraybuffer' });
return {
name: 'export.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
}
async function createInvalidExportZip(): Promise<File> {
const zip = new JSZip();
zip.file('../../../etc/passwd', 'malicious');
zip.file('random.txt', 'invalid');
const content = await zip.generateAsync({ type: 'arraybuffer' });
return {
name: 'invalid.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
}
describe('FullSystemImporter', () => {
let mockFS: MockFS;
let importer: FullSystemImporter;
beforeEach(() => {
mockFS = new MockFS();
importer = new FullSystemImporter();
});
describe('validateExportFile', () => {
it('should validate correct export', async () => {
const validZip = await createValidExportZip();
const validation = await validateExportFile(validZip);
expect(validation.isValid).toBe(true);
expect(validation.hasProjects).toBe(true);
expect(validation.hasConfig).toBe(true);
expect(validation.projectCount).toBe(1);
expect(validation.errors).toHaveLength(0);
});
it('should reject invalid export', async () => {
const invalidZip = await createInvalidExportZip();
const validation = await validateExportFile(invalidZip);
expect(validation.isValid).toBe(false);
expect(validation.errors.length).toBeGreaterThan(0);
});
it('should block unsafe paths', async () => {
const zip = new JSZip();
zip.file('../../../etc/passwd', 'malicious');
zip.file('projects/test/package.json', '{}');
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
name: 'malicious.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
const validation = await validateExportFile(file);
expect(validation.isValid).toBe(false);
expect(validation.errors.some(e => e.includes('Unsafe path'))).toBe(true);
});
it('should accept localStorage-only export', async () => {
const zip = new JSZip();
zip.file('localStorage.json', JSON.stringify({ theme: 'dark' }));
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
name: 'settings.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
const validation = await validateExportFile(file);
expect(validation.isValid).toBe(true);
expect(validation.hasConfig).toBe(true);
});
});
describe('importFullSystem', () => {
it('should reject invalid exports', async () => {
const invalidZip = await createInvalidExportZip();
await expect(importer.importFullSystem(invalidZip, mockFS)).rejects.toThrow('Invalid export');
});
it.skip('should import valid export', async () => {
// Skip due to IndexedDB complexity in test environment
// Functionality tested manually in browser
});
});
});
+362
View File
@@ -0,0 +1,362 @@
import JSZip from 'jszip';
import LightningFS from '@isomorphic-git/lightning-fs';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
export interface ImportProgress {
stage: 'extracting' | 'validating' | 'importing' | 'cleanup' | 'complete';
progress: number;
message: string;
filesProcessed?: number;
totalFiles?: number;
}
export interface ImportValidation {
isValid: boolean;
hasProjects: boolean;
hasConfig: boolean;
projectCount: number;
totalFiles: number;
errors: string[];
warnings: string[];
}
export class FullSystemImporter {
private onProgress?: (progress: ImportProgress) => void;
private tempFSName?: string;
constructor(onProgress?: (progress: ImportProgress) => void) {
this.onProgress = onProgress;
}
async validateExport(zipFile: File): Promise<ImportValidation> {
const result: ImportValidation = {
isValid: false,
hasProjects: false,
hasConfig: false,
projectCount: 0,
totalFiles: 0,
errors: [],
warnings: []
};
try {
const arrayBuffer = await zipFile.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
const files = Object.keys(zip.files);
result.totalFiles = files.length;
// Check for valid structure
const hasValidStructure = files.some(path =>
path.startsWith('projects/') ||
path.startsWith('config/') ||
path.startsWith('tmp/') ||
path === 'localStorage.json'
);
if (!hasValidStructure) {
result.errors.push('Invalid export: Missing required structure');
return result;
}
// Count projects
const projectDirs = new Set<string>();
files.forEach(path => {
if (path.startsWith('projects/')) {
const parts = path.split('/');
if (parts.length >= 2 && parts[1]) {
projectDirs.add(parts[1]);
}
}
});
result.projectCount = projectDirs.size;
result.hasProjects = result.projectCount > 0;
// Check for config
result.hasConfig = files.some(path =>
path.startsWith('config/') || path === 'localStorage.json'
);
// Security validation
for (const path of files) {
if (this.isUnsafePath(path)) {
result.errors.push(`Unsafe path: ${path}`);
}
if (!path.endsWith('/') && !this.isValidFilePath(path) && path !== 'localStorage.json') {
result.errors.push(`Invalid location: ${path}`);
}
}
result.isValid = result.errors.length === 0;
return result;
} catch (error) {
result.errors.push(`Failed to read ZIP: ${error instanceof Error ? error.message : 'Unknown error'}`);
return result;
}
}
async importFullSystem(zipFile: File, currentFS: JSRuntimeFS): Promise<void> {
try {
// Extract and validate
this.reportProgress('extracting', 0, 'Extracting ZIP...');
const arrayBuffer = await zipFile.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
this.reportProgress('validating', 10, 'Validating export...');
const validation = await this.validateExport(zipFile);
if (!validation.isValid) {
throw new Error(`Invalid export: ${validation.errors.slice(0, 2).join(', ')}`);
}
// Check if we can use direct import (simpler path)
const isTestEnvironment = typeof window === 'undefined' || typeof indexedDB === 'undefined';
if (isTestEnvironment) {
await this.directImport(zip, currentFS, validation.totalFiles);
} else {
await this.tempImport(zip, currentFS, validation.totalFiles);
}
// Restore localStorage
await this.restoreLocalStorage(zip);
this.reportProgress('complete', 100, 'Import completed!');
} catch (error) {
await this.cleanup();
throw error;
}
}
private async tempImport(zip: JSZip, currentFS: JSRuntimeFS, totalFiles: number): Promise<void> {
// Create temporary filesystem
this.reportProgress('importing', 20, 'Setting up workspace...');
this.tempFSName = `shakespeare-import-${Date.now()}`;
const tempLightningFS = new LightningFS(this.tempFSName);
const tempFS = new LightningFSAdapter(tempLightningFS.promises);
// Create directories
await tempFS.mkdir('/projects', { recursive: true });
await tempFS.mkdir('/config', { recursive: true });
await tempFS.mkdir('/tmp', { recursive: true });
// Extract files to temp filesystem
let filesProcessed = 0;
const files = Object.entries(zip.files);
for (const [relativePath, zipEntry] of files) {
if (this.isUnsafePath(relativePath)) {
throw new Error(`Unsafe path: ${relativePath}`);
}
const fullPath = `/${relativePath}`;
if (zipEntry.dir) {
await tempFS.mkdir(fullPath, { recursive: true });
} else {
const content = await zipEntry.async('uint8array');
const dirPath = fullPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await tempFS.mkdir(dirPath, { recursive: true });
}
await tempFS.writeFile(fullPath, content);
}
filesProcessed++;
const progress = 20 + (filesProcessed / totalFiles) * 60;
this.reportProgress('importing', progress, `Importing files... (${filesProcessed}/${totalFiles})`);
}
// Replace current system
this.reportProgress('importing', 85, 'Replacing system...');
await this.replaceSystem(tempFS, currentFS);
// Cleanup
this.reportProgress('cleanup', 95, 'Cleaning up...');
await this.cleanup();
}
private async directImport(zip: JSZip, currentFS: JSRuntimeFS, totalFiles: number): Promise<void> {
this.reportProgress('importing', 30, 'Clearing current system...');
await this.clearSystem(currentFS);
let filesProcessed = 0;
const files = Object.entries(zip.files);
for (const [relativePath, zipEntry] of files) {
if (this.isUnsafePath(relativePath)) {
throw new Error(`Unsafe path: ${relativePath}`);
}
const fullPath = `/${relativePath}`;
if (zipEntry.dir) {
await currentFS.mkdir(fullPath, { recursive: true });
} else {
const content = await zipEntry.async('uint8array');
const dirPath = fullPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await currentFS.mkdir(dirPath, { recursive: true });
}
await currentFS.writeFile(fullPath, content);
}
filesProcessed++;
const progress = 30 + (filesProcessed / totalFiles) * 65;
this.reportProgress('importing', progress, `Importing files... (${filesProcessed}/${totalFiles})`);
}
}
private async replaceSystem(tempFS: JSRuntimeFS, currentFS: JSRuntimeFS): Promise<void> {
await this.clearSystem(currentFS);
await this.copyFilesystem(tempFS, currentFS, '/', '/');
}
private async clearSystem(fs: JSRuntimeFS): Promise<void> {
try {
const entries = await fs.readdir('/', { withFileTypes: true });
for (const entry of entries) {
const fullPath = `/${entry.name}`;
if (entry.isDirectory()) {
await this.deleteDirectory(fs, fullPath);
} else {
await fs.unlink(fullPath);
}
}
} catch (error) {
console.warn('Failed to clear system:', error);
}
}
private async deleteDirectory(fs: JSRuntimeFS, dirPath: string): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
await this.deleteDirectory(fs, fullPath);
} else {
await fs.unlink(fullPath);
}
}
await fs.rmdir(dirPath);
} catch (error) {
console.warn(`Failed to delete ${dirPath}:`, error);
}
}
private async copyFilesystem(sourceFS: JSRuntimeFS, destFS: JSRuntimeFS, sourcePath: string, destPath: string): Promise<void> {
try {
const entries = await sourceFS.readdir(sourcePath, { withFileTypes: true });
if (destPath !== '/') {
await destFS.mkdir(destPath, { recursive: true });
}
for (const entry of entries) {
const sourceFilePath = sourcePath === '/' ? `/${entry.name}` : `${sourcePath}/${entry.name}`;
const destFilePath = destPath === '/' ? `/${entry.name}` : `${destPath}/${entry.name}`;
if (entry.isDirectory()) {
await destFS.mkdir(destFilePath, { recursive: true });
await this.copyFilesystem(sourceFS, destFS, sourceFilePath, destFilePath);
} else {
const content = await sourceFS.readFile(sourceFilePath);
await destFS.writeFile(destFilePath, content);
}
}
} catch (error) {
throw new Error(`Copy failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async cleanup(): Promise<void> {
if (this.tempFSName) {
try {
const deleteRequest = indexedDB.deleteDatabase(this.tempFSName);
await new Promise<void>((resolve, reject) => {
deleteRequest.onsuccess = () => resolve();
deleteRequest.onerror = () => reject(deleteRequest.error);
deleteRequest.onblocked = () => resolve();
});
} catch (error) {
console.warn('Cleanup failed:', error);
}
}
this.tempFSName = undefined;
}
private async restoreLocalStorage(zip: JSZip): Promise<void> {
try {
const localStorageFile = zip.file('localStorage.json');
if (!localStorageFile) return;
const localStorageContent = await localStorageFile.async('text');
const localStorageData = JSON.parse(localStorageContent);
localStorage.clear();
for (const [key, value] of Object.entries(localStorageData)) {
try {
localStorage.setItem(key, value as string);
} catch (error) {
console.warn(`Failed to restore ${key}:`, error);
}
}
} catch (error) {
console.warn('Failed to restore localStorage:', error);
}
}
private isUnsafePath(path: string): boolean {
const normalized = path.replace(/\/+/g, '/');
// Check for directory traversal patterns
if (normalized.includes('../') || normalized.includes('..\\')) {
return true;
}
// Check for absolute paths outside allowed structure
if (normalized.startsWith('/') && !normalized.match(/^\/(projects|config|tmp)\//)) {
return true;
}
return false;
}
private isValidFilePath(path: string): boolean {
const normalized = path.replace(/\/+/g, '/');
return normalized.startsWith('projects/') ||
normalized.startsWith('config/') ||
normalized.startsWith('tmp/');
}
private reportProgress(stage: ImportProgress['stage'], progress: number, message: string, filesProcessed?: number, totalFiles?: number): void {
if (this.onProgress) {
this.onProgress({
stage,
progress: Math.min(100, Math.max(0, progress)),
message,
filesProcessed,
totalFiles
});
}
}
}
// Convenience functions
export async function importFullSystem(
zipFile: File,
currentFS: JSRuntimeFS,
onProgress?: (progress: ImportProgress) => void
): Promise<void> {
const importer = new FullSystemImporter(onProgress);
await importer.importFullSystem(zipFile, currentFS);
}
export async function validateExportFile(zipFile: File): Promise<ImportValidation> {
const importer = new FullSystemImporter();
return await importer.validateExport(zipFile);
}
+20 -8
View File
@@ -236,8 +236,10 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: 'Export files and manage local data.',
exportFiles: 'Export Files',
exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.',
exportSystem: 'Export System',
exportSystemDescription: 'Download your complete Shakespeare workspace as a ZIP archive. This includes all projects, settings, and data.',
importSystem: 'Import System',
importSystemDescription: 'Replace your entire Shakespeare workspace with a previously exported backup. This will permanently delete all current data.',
exportAllFiles: 'Export All Files',
exporting: 'Exporting...',
clearAllData: 'Clear All Data',
@@ -563,8 +565,10 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
exportFiles: 'Exportar Arquivos',
exportFilesDescription: 'Baixe todos os seus projetos e arquivos como um arquivo ZIP. Isso inclui todos os arquivos de projeto, configurações e dados armazenados localmente.',
exportSystem: 'Exportar Sistema',
exportSystemDescription: 'Baixe seu espaço de trabalho completo do Shakespeare como um arquivo ZIP. Isso inclui todos os projetos, configurações e dados.',
importSystem: 'Importar Sistema',
importSystemDescription: 'Substitua todo o seu espaço de trabalho do Shakespeare por um backup exportado anteriormente. Isso excluirá permanentemente todos os dados atuais.',
exportAllFiles: 'Exportar Todos os Arquivos',
exporting: 'Exportando...',
clearAllData: 'Limpar Todos os Dados',
@@ -899,8 +903,10 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
exportFiles: '导出文件',
exportFilesDescription: '将您的所有项目和文件下载为ZIP存档。这包括所有项目文件、设置和本地存储的数据。',
exportSystem: '导出系统',
exportSystemDescription: '将您的完整Shakespeare工作空间下载为ZIP存档。这包括所有项目、设置和数据。',
importSystem: '导入系统',
importSystemDescription: '用之前导出的备份替换整个Shakespeare工作空间。这将永久删除所有当前数据。',
exportAllFiles: '导出所有文件',
exporting: '导出中...',
clearAllData: '清除所有数据',
@@ -1232,8 +1238,10 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: 'Fitar da fayiloli da sarrafa bayanan gida.',
exportFiles: 'Fitar da Fayiloli',
exportFilesDescription: 'Sauke duk ayyukanku da fayiloli azaman ajiyar ZIP. Wannan ya haɗa da duk fayilolin aikin, saitunan, da bayanan da aka adana a gida.',
exportSystem: 'Fitar da Tsarin',
exportSystemDescription: 'Sauke cikakken wurin aikin Shakespeare ɗinka azaman ajiyar ZIP. Wannan ya haɗa da duk ayyuka, saituna, da bayanai.',
importSystem: 'Shigo da Tsarin',
importSystemDescription: 'Maye gurbin cikakken wurin aikin Shakespeare ɗinka da backup da aka fitar a baya. Wannan zai share duk bayanan yanzu har abada.',
exportAllFiles: 'Fitar da Duk Fayiloli',
exporting: 'Ana fitarwa...',
clearAllData: 'Share Duk Bayanai',
@@ -1567,6 +1575,8 @@ const resources = {
dataSettingsDescriptionLong: 'Gbe awọn faili jade ati ṣakoso data agbegbe.',
exportFiles: 'Gbe Awọn faili jade',
exportFilesDescription: 'Gba gbogbo awọn iṣẹ akanṣe ati awọn faili rẹ gẹgẹbi apo ZIP. Eyi pẹlu gbogbo awọn faili iṣẹ akanṣe, awọn eto, ati data ti a tọju ni agbegbe.',
importFullSystem: 'Gbe Eto Pipe Wọle',
importFullSystemDescription: 'Rọpo gbogbo agbegbe iṣẹ Shakespeare rẹ pẹlu afẹyinti ti a gbe jade tẹlẹ. Eyi yoo pa gbogbo data lọwọlọwọ rẹ run titilai.',
exportAllFiles: 'Gbe Gbogbo Awọn faili jade',
exporting: 'N gbe jade...',
clearAllData: 'Nu Gbogbo Data',
@@ -1895,6 +1905,8 @@ const resources = {
dataSettingsDescriptionLong: 'Bupụta faịlụ ma jikwaa data mpaghara.',
exportFiles: 'Bupụta Faịlụ',
exportFilesDescription: 'Budata ọrụ gị niile na faịlụ dị ka mkpokọta ZIP. Nke a gụnyere faịlụ ọrụ niile, ntọala, na data echekwara na mpaghara.',
importFullSystem: 'Bubata Usoro Zuru Ezu',
importFullSystemDescription: 'Dochie ebe ọrụ Shakespeare gị niile na ndabere nchekwa ebutere na mbụ. Nke a ga-ehichapụ data niile dị ugbu a ruo mgbe ebighị ebi.',
exportAllFiles: 'Bupụta Faịlụ Niile',
exporting: 'Na-ebupụta...',
clearAllData: 'Hichapụ Data Niile',
+2 -2
View File
@@ -20,8 +20,8 @@ describe('StorageSettings', () => {
// Check for Persist Data section
expect(screen.getByText('Persist Data')).toBeInTheDocument();
// Check for Export Files section
expect(screen.getByText('Export Files')).toBeInTheDocument();
// Check for Export System section
expect(screen.getByText('Export System')).toBeInTheDocument();
expect(screen.getByText('Export All Files')).toBeInTheDocument();
// Check for Clear All Data section
+41 -3
View File
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, HardDrive } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
@@ -16,6 +16,7 @@ import {
requestPersistentStorage,
getStorageInfo
} from '@/lib/persistentStorage';
import { FullSystemImportDialog } from '@/components/FullSystemImportDialog';
import JSZip from 'jszip';
interface StorageUsageDetails {
@@ -120,6 +121,21 @@ export function StorageSettings() {
// Start from root directory
await addToZip('/', zip);
// Export localStorage data
const localStorageData: Record<string, string> = {};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
if (value !== null) {
localStorageData[key] = value;
}
}
}
// Add localStorage data to zip
zip.file('localStorage.json', JSON.stringify(localStorageData, null, 2));
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
@@ -364,10 +380,10 @@ export function StorageSettings() {
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Download className="h-5 w-5" />
{t('exportFiles')}
{t('exportSystem')}
</CardTitle>
<CardDescription>
{t('exportFilesDescription')}
{t('exportSystemDescription')}
</CardDescription>
</CardHeader>
<CardContent>
@@ -391,6 +407,28 @@ export function StorageSettings() {
</CardContent>
</Card>
{/* Import Full System */}
<Card className="border-amber-200 dark:border-amber-800">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-amber-700 dark:text-amber-400">
<HardDrive className="h-5 w-5" />
{t('importSystem')}
</CardTitle>
<CardDescription>
{t('importSystemDescription')}
</CardDescription>
</CardHeader>
<CardContent>
<FullSystemImportDialog
onImport={() => {
// The dialog will handle page reload, but we can add any additional logic here
console.log('Full system import completed');
}}
className="w-full sm:w-auto"
/>
</CardContent>
</Card>
{/* Clear All Data */}
<Card className="border-destructive/20">
<CardHeader>