mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 16:13:34 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3555d05d54 |
No files matched your search
@@ -10,7 +10,6 @@
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
|
||||
Generated
-16
@@ -64,7 +64,6 @@
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
@@ -8202,21 +8201,6 @@
|
||||
"node": ">=8.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-4.1.0.tgz",
|
||||
"integrity": "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"mime": "bin/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/mimic-response": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
|
||||
|
||||
@@ -67,7 +67,6 @@
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 70 KiB |
@@ -25,14 +25,12 @@ import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
|
||||
interface DeployDialogProps {
|
||||
projectId: string;
|
||||
@@ -45,10 +43,6 @@ interface ShakespeareFormData {
|
||||
subdomain: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
nsec: string;
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
siteId: string;
|
||||
siteName: string;
|
||||
@@ -66,7 +60,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const { user } = useCurrentUser();
|
||||
const { fs } = useFS();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
@@ -77,9 +70,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
nsec: '',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
siteName: '',
|
||||
@@ -132,21 +122,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
|
||||
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
}
|
||||
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
nsec: nsiteForm.nsec,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider as NetlifyProvider;
|
||||
if (!netlifyProvider.apiKey) {
|
||||
@@ -194,13 +169,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'nsite',
|
||||
data: {
|
||||
nsec: nsiteForm.nsec,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
@@ -232,7 +200,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
onOpenChange(false);
|
||||
@@ -242,10 +209,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
setNetlifyForm({ siteId, siteName });
|
||||
}, []);
|
||||
@@ -269,32 +232,20 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'nsite') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
|
||||
|
||||
return (
|
||||
<NsiteDeployForm
|
||||
gateway={selectedProvider.gateway}
|
||||
savedNsec={savedNsec}
|
||||
onNsecChange={handleNsiteNsecChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider as NetlifyProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
|
||||
|
||||
return (
|
||||
<NetlifyDeployForm
|
||||
apiKey={selectedProvider.apiKey}
|
||||
baseURL={selectedProvider.baseURL}
|
||||
apiKey={netlifyProvider.apiKey}
|
||||
baseURL={netlifyProvider.baseURL}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedSiteId={savedSiteId}
|
||||
onSiteChange={handleNetlifySiteChange}
|
||||
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
|
||||
corsProxy={netlifyProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -445,7 +396,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,418 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
interface NsiteDeployFormProps {
|
||||
gateway: string;
|
||||
savedNsec?: string;
|
||||
onNsecChange: (nsec: string) => void;
|
||||
}
|
||||
|
||||
export function NsiteDeployForm({
|
||||
gateway,
|
||||
savedNsec,
|
||||
onNsecChange,
|
||||
}: NsiteDeployFormProps) {
|
||||
const [nsec, setNsec] = useState(savedNsec || '');
|
||||
const [npub, setNpub] = useState('');
|
||||
const initialized = useRef(false);
|
||||
|
||||
// Initialize nsec on mount
|
||||
useEffect(() => {
|
||||
if (!initialized.current) {
|
||||
initialized.current = true;
|
||||
if (savedNsec) {
|
||||
// If we have a saved nsec, notify parent immediately
|
||||
onNsecChange(savedNsec);
|
||||
} else if (!nsec) {
|
||||
// Generate a new nsec if none exists
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
}
|
||||
}
|
||||
}, [savedNsec, nsec, onNsecChange]);
|
||||
|
||||
// Update npub when nsec changes
|
||||
useEffect(() => {
|
||||
if (nsec) {
|
||||
try {
|
||||
const decoded = nip19.decode(nsec);
|
||||
if (decoded.type === 'nsec') {
|
||||
const pk = getPublicKey(decoded.data);
|
||||
const npubEncoded = nip19.npubEncode(pk);
|
||||
setNpub(npubEncoded);
|
||||
}
|
||||
} catch {
|
||||
setNpub('');
|
||||
}
|
||||
}
|
||||
}, [nsec]);
|
||||
|
||||
const handleNsecChange = (value: string) => {
|
||||
setNsec(value);
|
||||
onNsecChange(value);
|
||||
};
|
||||
|
||||
const handleGenerateNew = () => {
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
};
|
||||
|
||||
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Site URL</Label>
|
||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
||||
{fullDomain}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each site has a unique Nostr keypair
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
id="nsite-nsec"
|
||||
value={nsec}
|
||||
onChange={(e) => handleNsecChange(e.target.value)}
|
||||
placeholder="nsec1..."
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleGenerateNew}
|
||||
title="Generate new key"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Keep this private key secure. It's used to sign site metadata.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
|
||||
export { NetlifyDeployForm } from './NetlifyDeployForm';
|
||||
export { VercelDeployForm } from './VercelDeployForm';
|
||||
export { NsiteDeployForm } from './NsiteDeployForm';
|
||||
@@ -1,129 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -3,36 +3,27 @@ import { createContext } from 'react';
|
||||
export interface BaseDeployProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface ShakespeareDeployProvider extends BaseDeployProvider {
|
||||
type: 'shakespeare';
|
||||
host?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface NetlifyProvider extends BaseDeployProvider {
|
||||
type: 'netlify';
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface VercelProvider extends BaseDeployProvider {
|
||||
type: 'vercel';
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface NsiteProvider extends BaseDeployProvider {
|
||||
type: 'nsite';
|
||||
gateway: string;
|
||||
relayUrls: string[];
|
||||
blossomServers: string[];
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
@@ -8,13 +8,6 @@ export interface ShakespeareProjectConfig {
|
||||
};
|
||||
}
|
||||
|
||||
export interface NsiteProjectConfig {
|
||||
type: 'nsite';
|
||||
data: {
|
||||
nsec: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface NetlifyProjectConfig {
|
||||
type: 'netlify';
|
||||
data: {
|
||||
@@ -30,7 +23,7 @@ export interface VercelProjectConfig {
|
||||
};
|
||||
}
|
||||
|
||||
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
|
||||
export type ProjectProviderConfig = ShakespeareProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
|
||||
|
||||
export interface ProjectDeploySettings {
|
||||
providers: Record<string, ProjectProviderConfig>;
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
*/
|
||||
export interface JSRuntimeFS {
|
||||
// Core file operations with proper overloads for type safety
|
||||
readFile(path: string): Promise<Uint8Array<ArrayBuffer>>;
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
readFile(path: string, options: string): Promise<string>;
|
||||
readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
|
||||
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
||||
|
||||
writeFile(path: string, data: string | Uint8Array<ArrayBuffer>, options?: string | { encoding?: string }): Promise<void>;
|
||||
writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void>;
|
||||
|
||||
// readdir overloads for different return types
|
||||
readdir(path: string): Promise<string[]>;
|
||||
|
||||
@@ -32,6 +32,21 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
request = new Request(request, { headers });
|
||||
}
|
||||
|
||||
// Add Anthropic-specific headers
|
||||
// https://docs.anthropic.com/en/api/versioning
|
||||
if (provider.id === 'anthropic') {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('anthropic-version', '2023-06-01');
|
||||
// Required header for direct browser access
|
||||
headers.set('anthropic-dangerous-direct-browser-access', 'true');
|
||||
// Anthropic expects x-api-key header instead of Authorization: Bearer
|
||||
if (provider.apiKey) {
|
||||
headers.set('x-api-key', provider.apiKey);
|
||||
headers.delete('authorization'); // Remove the Bearer token that OpenAI client adds
|
||||
}
|
||||
request = new Request(request, { headers });
|
||||
}
|
||||
|
||||
// If Nostr authentication is required and we have a user, use NIP-98
|
||||
if (provider.nostr && user?.signer) {
|
||||
// Create the NIP98 token
|
||||
|
||||
@@ -71,18 +71,10 @@ const vercelProviderSchema = baseDeployProviderSchema.extend({
|
||||
baseURL: z.string().optional(),
|
||||
});
|
||||
|
||||
const nsiteProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('nsite'),
|
||||
gateway: z.string(),
|
||||
relayUrls: z.array(z.string()),
|
||||
blossomServers: z.array(z.string()),
|
||||
});
|
||||
|
||||
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||
shakespeareDeployProviderSchema,
|
||||
netlifyProviderSchema,
|
||||
vercelProviderSchema,
|
||||
nsiteProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
|
||||
import { NSecSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import mime from 'mime';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
||||
|
||||
/**
|
||||
* Nsite Deploy Adapter
|
||||
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
|
||||
*/
|
||||
export class NsiteAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private nostr: NsiteDeployConfig['nostr'];
|
||||
private nsec: string;
|
||||
private gateway: string;
|
||||
private relayUrls: string[];
|
||||
private blossomServers: string[];
|
||||
|
||||
constructor(config: NsiteDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.nostr = config.nostr;
|
||||
this.nsec = config.nsec;
|
||||
this.gateway = config.gateway;
|
||||
this.relayUrls = config.relayUrls;
|
||||
this.blossomServers = config.blossomServers;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
|
||||
// Check if dist directory exists and contains index.html
|
||||
const distPath = `${projectPath}/dist`;
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
throw new Error('No index.html found in dist directory. Please build the project first.');
|
||||
}
|
||||
|
||||
// Decode nsec to get the private key and create signer
|
||||
const decoded = nip19.decode(this.nsec);
|
||||
if (decoded.type !== 'nsec') {
|
||||
throw new Error('Invalid nsec format');
|
||||
}
|
||||
const signer = new NSecSigner(decoded.data);
|
||||
const pubkey = await signer.getPublicKey();
|
||||
|
||||
// Create a grouped Nostr client for the configured relays
|
||||
const relayClient = this.nostr.group(this.relayUrls);
|
||||
|
||||
// Initialize Blossom uploader
|
||||
const uploader = new BlossomUploader({
|
||||
servers: this.blossomServers,
|
||||
signer,
|
||||
});
|
||||
|
||||
// Collect all files and upload them
|
||||
const fileEvents: NostrEvent[] = [];
|
||||
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
|
||||
|
||||
// Publish file events and other metadata to the relays
|
||||
await Promise.all([
|
||||
this.publishRelayList(signer, relayClient),
|
||||
this.publishServerList(signer, relayClient),
|
||||
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
|
||||
]);
|
||||
|
||||
// Generate npub subdomain
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
const siteUrl = `https://${npub}.${this.gateway}`;
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
metadata: {
|
||||
pubkey,
|
||||
npub,
|
||||
filesPublished: fileEvents.length,
|
||||
provider: 'nsite',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async uploadDirectory(
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
uploader: BlossomUploader,
|
||||
signer: NSecSigner,
|
||||
fileEvents: NostrEvent[]
|
||||
): Promise<void> {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
|
||||
} else if (entry.isFile()) {
|
||||
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async uploadFile(
|
||||
filePath: string,
|
||||
relativePath: string,
|
||||
uploader: BlossomUploader,
|
||||
signer: NSecSigner,
|
||||
fileEvents: NostrEvent[]
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Read file content
|
||||
const content = await this.fs.readFile(filePath);
|
||||
|
||||
// Convert to File object for upload
|
||||
const file = new File([content], relativePath.split('/').pop() || 'file', {
|
||||
type: mime.getType(filePath) || undefined,
|
||||
});
|
||||
|
||||
// Upload to Blossom and get tags
|
||||
const tags = await uploader.upload(file);
|
||||
|
||||
// Extract sha256 hash from tags
|
||||
// Tags format: [['url', 'https://...'], ['x', 'sha256hash'], ['size', '1234'], ...]
|
||||
const xTag = tags.find(([name]) => name === 'x');
|
||||
if (!xTag || !xTag[1]) {
|
||||
throw new Error(`Failed to get sha256 hash for ${relativePath}`);
|
||||
}
|
||||
const sha256 = xTag[1];
|
||||
|
||||
// Create absolute path (must start with /)
|
||||
const absolutePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
|
||||
|
||||
// Create kind 34128 event
|
||||
const event = await signer.signEvent({
|
||||
kind: 34128,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['d', absolutePath],
|
||||
['x', sha256],
|
||||
],
|
||||
});
|
||||
|
||||
fileEvents.push(event);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to upload file ${filePath}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async publishRelayList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
||||
const relayListEvent = await signer.signEvent({
|
||||
kind: 10002,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: this.relayUrls.map(url => ['r', url]),
|
||||
});
|
||||
|
||||
await relayClient.event(relayListEvent, { signal: AbortSignal.timeout(5000) });
|
||||
}
|
||||
|
||||
private async publishServerList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
||||
const serverListEvent = await signer.signEvent({
|
||||
kind: 10063,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: this.blossomServers.map(server => ['server', server]),
|
||||
});
|
||||
|
||||
await relayClient.event(serverListEvent, { signal: AbortSignal.timeout(5000) });
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,3 @@ export * from './types';
|
||||
export * from './ShakespeareAdapter';
|
||||
export * from './NetlifyAdapter';
|
||||
export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
+1
-10
@@ -1,5 +1,5 @@
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
|
||||
export interface DeployOptions {
|
||||
/** Project ID */
|
||||
@@ -45,12 +45,3 @@ export interface VercelDeployConfig {
|
||||
projectName?: string;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export interface NsiteDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
nostr: NPool;
|
||||
nsec: string;
|
||||
gateway: string;
|
||||
relayUrls: string[];
|
||||
blossomServers: string[];
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
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
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,362 +0,0 @@
|
||||
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);
|
||||
}
|
||||
+8
-20
@@ -236,10 +236,8 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: 'Export files and manage local data.',
|
||||
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.',
|
||||
exportFiles: 'Export Files',
|
||||
exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.',
|
||||
exportAllFiles: 'Export All Files',
|
||||
exporting: 'Exporting...',
|
||||
clearAllData: 'Clear All Data',
|
||||
@@ -565,10 +563,8 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
|
||||
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.',
|
||||
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.',
|
||||
exportAllFiles: 'Exportar Todos os Arquivos',
|
||||
exporting: 'Exportando...',
|
||||
clearAllData: 'Limpar Todos os Dados',
|
||||
@@ -903,10 +899,8 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
|
||||
exportSystem: '导出系统',
|
||||
exportSystemDescription: '将您的完整Shakespeare工作空间下载为ZIP存档。这包括所有项目、设置和数据。',
|
||||
importSystem: '导入系统',
|
||||
importSystemDescription: '用之前导出的备份替换整个Shakespeare工作空间。这将永久删除所有当前数据。',
|
||||
exportFiles: '导出文件',
|
||||
exportFilesDescription: '将您的所有项目和文件下载为ZIP存档。这包括所有项目文件、设置和本地存储的数据。',
|
||||
exportAllFiles: '导出所有文件',
|
||||
exporting: '导出中...',
|
||||
clearAllData: '清除所有数据',
|
||||
@@ -1238,10 +1232,8 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: 'Fitar da fayiloli da sarrafa bayanan 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.',
|
||||
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.',
|
||||
exportAllFiles: 'Fitar da Duk Fayiloli',
|
||||
exporting: 'Ana fitarwa...',
|
||||
clearAllData: 'Share Duk Bayanai',
|
||||
@@ -1575,8 +1567,6 @@ 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',
|
||||
@@ -1905,8 +1895,6 @@ 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',
|
||||
|
||||
@@ -92,28 +92,8 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
const limitedResult = await tool.execute({ limit: 2 });
|
||||
expect(limitedResult).toContain('Found 2 console messages');
|
||||
|
||||
// Default limit (50) should return all messages when total is less than 50
|
||||
// No limit should return all messages
|
||||
const allResult = await tool.execute({});
|
||||
expect(allResult).toContain('Found 4 console messages');
|
||||
});
|
||||
|
||||
it('should show truncation note when messages exceed limit', async () => {
|
||||
clearConsoleMessages();
|
||||
// Add more messages than the limit
|
||||
for (let i = 1; i <= 60; i++) {
|
||||
addConsoleMessage('log', `Message ${i}`);
|
||||
}
|
||||
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
|
||||
// Default limit is 50
|
||||
const result = await tool.execute({});
|
||||
expect(result).toContain('(showing last 50 of 60)');
|
||||
expect(result).toContain('Message 60'); // Most recent
|
||||
expect(result).not.toContain('Message 10'); // Too old
|
||||
|
||||
// Custom limit
|
||||
const limitedResult = await tool.execute({ limit: 10 });
|
||||
expect(limitedResult).toContain('(showing last 10 of 60)');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { z } from 'zod';
|
||||
import { Tool } from './Tool';
|
||||
import { getConsoleMessages } from '@/lib/consoleMessages';
|
||||
|
||||
@@ -12,25 +11,15 @@ export interface ReadConsoleMessagesParams {
|
||||
* This tool allows AI assistants to access console logs for debugging assistance.
|
||||
*/
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
readonly description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
filter: z.enum(['error', 'warn', 'info', 'debug', 'log', 'all']).optional().describe(
|
||||
'Filter messages by level. Defaults to "all" to show all message types.'
|
||||
),
|
||||
limit: z.number().min(1).max(200).optional().describe(
|
||||
'Maximum number of most recent messages to return. Defaults to 50. Use smaller values (10-20) for quick checks, larger values (100-200) for comprehensive debugging.'
|
||||
),
|
||||
});
|
||||
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit = 50 } = params;
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
let messages = getConsoleMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter);
|
||||
|
||||
// Always apply a limit to prevent unbounded output
|
||||
messages = messages.slice(-limit);
|
||||
if (limit && limit > 0) {
|
||||
messages = messages.slice(-limit);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
@@ -41,9 +30,8 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
|
||||
.join('\n');
|
||||
|
||||
const suffix = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||
const totalAvailable = getConsoleMessages().filter(msg => filter === 'all' || msg.level === filter).length;
|
||||
const truncatedNote = totalAvailable > messages.length ? ` (showing last ${messages.length} of ${totalAvailable})` : '';
|
||||
|
||||
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}`;
|
||||
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`;
|
||||
}
|
||||
|
||||
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||
}
|
||||
+32
-151
@@ -38,7 +38,7 @@ import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel';
|
||||
name: string;
|
||||
description: string;
|
||||
requiresNostr?: boolean;
|
||||
@@ -123,42 +123,6 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : provider.type === 'nsite' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-gateway`}>Gateway</Label>
|
||||
<Input
|
||||
id={`provider-${index}-gateway`}
|
||||
placeholder="nsite.lol"
|
||||
value={provider.gateway || ''}
|
||||
onChange={(e) => onUpdate(index, { ...provider, gateway: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-relays`}>Relay URLs (comma-separated)</Label>
|
||||
<Input
|
||||
id={`provider-${index}-relays`}
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={provider.relayUrls?.join(', ') || ''}
|
||||
onChange={(e) => onUpdate(index, {
|
||||
...provider,
|
||||
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-blossom`}>Blossom Servers (comma-separated)</Label>
|
||||
<Input
|
||||
id={`provider-${index}-blossom`}
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={provider.blossomServers?.join(', ') || ''}
|
||||
onChange={(e) => onUpdate(index, {
|
||||
...provider,
|
||||
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
@@ -195,21 +159,21 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`provider-${index}-proxy`}
|
||||
checked={provider.proxy || false}
|
||||
onCheckedChange={(checked) => onUpdate(index, { ...provider, proxy: checked === true })}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`provider-${index}-proxy`}
|
||||
className="text-sm font-normal cursor-pointer"
|
||||
>
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`provider-${index}-proxy`}
|
||||
checked={provider.proxy || false}
|
||||
onCheckedChange={(checked) => onUpdate(index, { ...provider, proxy: checked === true })}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`provider-${index}-proxy`}
|
||||
className="text-sm font-normal cursor-pointer"
|
||||
>
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
@@ -232,12 +196,6 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
description: 'Deploy to Shakespeare hosting with Nostr authentication',
|
||||
requiresNostr: true,
|
||||
},
|
||||
{
|
||||
id: 'nsite',
|
||||
type: 'nsite',
|
||||
name: 'nsite',
|
||||
description: 'Deploy to Nostr as a static website',
|
||||
},
|
||||
{
|
||||
id: 'netlify',
|
||||
type: 'netlify',
|
||||
@@ -247,15 +205,15 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
apiKeyURL: 'https://app.netlify.com/user/applications#personal-access-tokens',
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: 'vercel',
|
||||
type: 'vercel',
|
||||
name: 'Vercel',
|
||||
description: 'Deploy to Vercel',
|
||||
apiKeyLabel: 'Access Token',
|
||||
apiKeyURL: 'https://vercel.com/account/tokens',
|
||||
proxy: true,
|
||||
},
|
||||
// {
|
||||
// id: 'vercel',
|
||||
// type: 'vercel',
|
||||
// name: 'Vercel',
|
||||
// description: 'Deploy to Vercel',
|
||||
// apiKeyLabel: 'Access Token',
|
||||
// apiKeyURL: 'https://vercel.com/account/tokens',
|
||||
// proxy: true,
|
||||
// },
|
||||
];
|
||||
|
||||
// Helper function to generate custom provider ID
|
||||
@@ -290,15 +248,12 @@ export function DeploySettings() {
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
|
||||
// Custom provider form state
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState('');
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState('');
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor),
|
||||
@@ -327,8 +282,8 @@ export function DeploySettings() {
|
||||
|
||||
const apiKey = presetApiKeys[preset.id];
|
||||
|
||||
// For non-Shakespeare/non-nsite providers, require API key
|
||||
if (!preset.requiresNostr && preset.type !== 'nsite' && !apiKey?.trim()) {
|
||||
// For non-Shakespeare providers, require API key
|
||||
if (!preset.requiresNostr && !apiKey?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -341,25 +296,6 @@ export function DeploySettings() {
|
||||
type: 'shakespeare',
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
} else if (preset.type === 'nsite') {
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
name: preset.name,
|
||||
type: 'nsite',
|
||||
gateway: 'nosto.re',
|
||||
relayUrls: [
|
||||
'wss://relay.nsite.lol',
|
||||
'wss://relay.nosto.re',
|
||||
'wss://relay.nostr.band',
|
||||
'wss://relay.primal.net',
|
||||
'wss://relay.damus.io',
|
||||
'wss://purplerelay.com',
|
||||
],
|
||||
blossomServers: [
|
||||
'https://blossom.primal.net',
|
||||
'https://cdn.sovbit.host',
|
||||
],
|
||||
};
|
||||
} else if (preset.type === 'netlify') {
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
@@ -397,23 +333,6 @@ export function DeploySettings() {
|
||||
...(customHost?.trim() && { host: customHost.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'nsite') {
|
||||
const gateway = customGateway.trim() || 'nsite.lol';
|
||||
const relayUrls = customRelayUrls.trim()
|
||||
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['wss://relay.nostr.band'];
|
||||
const blossomServers = customBlossomServers.trim()
|
||||
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['https://blossom.primal.net/'];
|
||||
|
||||
newProvider = {
|
||||
id: generateCustomProviderId(customProviderType), // Generate custom ID
|
||||
name: customName.trim(),
|
||||
type: 'nsite',
|
||||
gateway,
|
||||
relayUrls,
|
||||
blossomServers,
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
newProvider = {
|
||||
@@ -567,7 +486,6 @@ export function DeploySettings() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{preset.description}</p>
|
||||
|
||||
{showNostrLoginRequired ? (
|
||||
<div className="space-y-2">
|
||||
@@ -613,7 +531,7 @@ export function DeploySettings() {
|
||||
// Show manual token input
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.requiresNostr && preset.type !== 'nsite' && (
|
||||
{!preset.requiresNostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
className="flex-1"
|
||||
@@ -633,9 +551,9 @@ export function DeploySettings() {
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
|
||||
(!preset.requiresNostr && !presetApiKeys[preset.id]?.trim())
|
||||
}
|
||||
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
className={preset.requiresNostr ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
@@ -662,16 +580,13 @@ export function DeploySettings() {
|
||||
<Label htmlFor="custom-provider-type">{t('providerType')}</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
setCustomBaseURL('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
@@ -679,9 +594,8 @@ export function DeploySettings() {
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
|
||||
<SelectItem value="nsite">nsite</SelectItem>
|
||||
<SelectItem value="netlify">Netlify</SelectItem>
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
{/* <SelectItem value="vercel">Vercel</SelectItem> */}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -713,39 +627,6 @@ export function DeploySettings() {
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : customProviderType === 'nsite' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
<Input
|
||||
id="custom-gateway"
|
||||
placeholder="nsite.lol"
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-relays"
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={customRelayUrls}
|
||||
onChange={(e) => setCustomRelayUrls(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={customBlossomServers}
|
||||
onChange={(e) => setCustomBlossomServers(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
@@ -791,7 +672,7 @@ export function DeploySettings() {
|
||||
disabled={
|
||||
!customProviderType ||
|
||||
!customName.trim() ||
|
||||
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim())
|
||||
(customProviderType !== 'shakespeare' && !customApiKey.trim())
|
||||
}
|
||||
className="gap-2 ml-auto"
|
||||
>
|
||||
|
||||
@@ -20,8 +20,8 @@ describe('StorageSettings', () => {
|
||||
// Check for Persist Data section
|
||||
expect(screen.getByText('Persist Data')).toBeInTheDocument();
|
||||
|
||||
// Check for Export System section
|
||||
expect(screen.getByText('Export System')).toBeInTheDocument();
|
||||
// Check for Export Files section
|
||||
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
||||
|
||||
// Check for Clear All Data section
|
||||
|
||||
@@ -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, HardDrive } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } 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,7 +16,6 @@ import {
|
||||
requestPersistentStorage,
|
||||
getStorageInfo
|
||||
} from '@/lib/persistentStorage';
|
||||
import { FullSystemImportDialog } from '@/components/FullSystemImportDialog';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface StorageUsageDetails {
|
||||
@@ -121,21 +120,6 @@ 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' });
|
||||
|
||||
@@ -380,10 +364,10 @@ export function StorageSettings() {
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Download className="h-5 w-5" />
|
||||
{t('exportSystem')}
|
||||
{t('exportFiles')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('exportSystemDescription')}
|
||||
{t('exportFilesDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -407,28 +391,6 @@ 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>
|
||||
|
||||
Reference in new issue
Block a user