diff --git a/src/App.tsx b/src/App.tsx index e3c848ae..4fe4f617 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,7 @@ import { AppProvider } from '@/components/AppProvider'; import { AppConfig } from '@/contexts/AppContext'; import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; +import { DeploySettingsProvider } from '@/components/DeploySettingsProvider'; import { SessionManagerProvider } from '@/components/SessionManagerProvider'; import { FSProvider } from '@/components/FSProvider'; import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; @@ -87,15 +88,17 @@ export function App() { - - - - - - - - - + + + + + + + + + + + diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index ad95ec65..b3eef03f 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -10,6 +10,7 @@ import Preferences from "./pages/Preferences"; import NostrSettings from "./pages/NostrSettings"; import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; +import DeploySettings from "./pages/DeploySettings"; import SystemSettings from "./pages/SystemSettings"; import StorageSettings from "./pages/StorageSettings"; import AboutSettings from "./pages/AboutSettings"; @@ -36,6 +37,7 @@ export function AppRouter() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 5a1c2913..040fcd4d 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -12,9 +12,11 @@ import { MessageSquarePlus, History, Folder, + Rocket, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; +import { DeployDialog } from '@/components/DeployDialog'; interface ActionsMenuProps { projectId: string; @@ -29,7 +31,7 @@ interface ActionsMenuProps { export function ActionsMenu({ projectId, - projectName: _projectName, + projectName, onNewChat, onProjectDetails, isLoading = false, @@ -39,6 +41,7 @@ export function ActionsMenu({ }: ActionsMenuProps) { const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); + const [deployDialogOpen, setDeployDialogOpen] = useState(false); const isAnyLoading = isLoading || isBuildLoading; @@ -86,6 +89,15 @@ export function ActionsMenu({ Repository + setDeployDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Deploy + + + ); diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index 87d1f94f..371173f9 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -1,182 +1,351 @@ import { useState, useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Rocket, ExternalLink, AlertCircle } from 'lucide-react'; import { Dialog, DialogContent, + DialogDescription, DialogHeader, DialogTitle, - DialogFooter, } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; -import { useToast } from '@/hooks/useToast'; -import { useAppContext } from '@/hooks/useAppContext'; -import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useMutation } from '@tanstack/react-query'; -import { deployProject } from '@/lib/deploy'; -import { useFS } from '@/hooks/useFS'; +import { Alert, AlertDescription } from '@/components/ui/alert'; import { - CloudUpload, - Loader2, -} from 'lucide-react'; + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { useDeploySettings } from '@/hooks/useDeploySettings'; +import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useFS } from '@/hooks/useFS'; +import { ShakespeareDeployProvider, NetlifyDeployProvider, VercelDeployProvider } from '@/lib/deploy-providers'; +import type { DeployProvider as DeployProviderType } from '@/contexts/DeploySettingsContext'; +import { Link } from 'react-router-dom'; interface DeployDialogProps { projectId: string; projectName: string; open: boolean; onOpenChange: (open: boolean) => void; - onFirstInteraction?: () => void; } -export function DeployDialog({ - projectId, - projectName, - open, - onOpenChange, - onFirstInteraction -}: DeployDialogProps) { - const { config } = useAppContext(); +export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) { + const { t } = useTranslation(); + const { settings, setProvider } = useDeploySettings(); + const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId); const { user } = useCurrentUser(); - const { fs } = useFS(); - const { toast } = useToast(); + const fs = useFS(); - // State for the deploy URL input - const [deployUrl, setDeployUrl] = useState(''); + const [selectedProviderId, setSelectedProviderId] = useState(''); + const [isDeploying, setIsDeploying] = useState(false); + const [deployResult, setDeployResult] = useState<{ url: string } | null>(null); + const [error, setError] = useState(null); - // Initialize deploy URL when dialog opens + // Form fields for each provider + const [netlifyFields, setNetlifyFields] = useState({ siteId: '' }); + const [vercelFields, setVercelFields] = useState({ teamId: '', projectId: '' }); + + // Load project settings when dialog opens useEffect(() => { - if (open) { - setDeployUrl(`${projectId}.${config.deployServer}`); + if (open && projectSettings.providerId) { + setSelectedProviderId(projectSettings.providerId); + + if (projectSettings.netlify?.siteId) { + setNetlifyFields({ siteId: projectSettings.netlify.siteId }); + } + + if (projectSettings.vercel) { + setVercelFields({ + teamId: projectSettings.vercel.teamId || '', + projectId: projectSettings.vercel.projectId || '', + }); + } } - }, [open, projectId, config.deployServer]); + }, [open, projectSettings]); - const deployMutation = useMutation({ - mutationFn: async () => { - if (!user) { - throw new Error("You must be logged into Nostr to deploy a project"); + const selectedProvider = settings.providers.find(p => p.id === selectedProviderId); + + const handleDeploy = async () => { + if (!selectedProvider) return; + + setIsDeploying(true); + setError(null); + setDeployResult(null); + + try { + const projectPath = `/projects/${projectId}`; + + let provider; + + if (selectedProvider.type === 'shakespeare') { + if (!user) { + throw new Error('You must be logged in with Nostr to use Shakespeare Deploy'); + } + provider = new ShakespeareDeployProvider({ + signer: user.signer, + }); + } else if (selectedProvider.type === 'netlify') { + if (!selectedProvider.apiKey) { + throw new Error('Netlify API key is required'); + } + + // Update provider with site ID if provided + const updatedProvider: DeployProviderType = { + ...selectedProvider, + siteId: netlifyFields.siteId || selectedProvider.siteId, + }; + + if (netlifyFields.siteId && netlifyFields.siteId !== selectedProvider.siteId) { + setProvider(updatedProvider); + } + + provider = new NetlifyDeployProvider({ + apiKey: selectedProvider.apiKey, + siteId: updatedProvider.siteId, + }); + } else if (selectedProvider.type === 'vercel') { + if (!selectedProvider.apiKey) { + throw new Error('Vercel API key is required'); + } + + // Update provider with team/project ID if provided + const updatedProvider: DeployProviderType = { + ...selectedProvider, + teamId: vercelFields.teamId || selectedProvider.teamId, + projectId: vercelFields.projectId || selectedProvider.projectId, + }; + + if ( + (vercelFields.teamId && vercelFields.teamId !== selectedProvider.teamId) || + (vercelFields.projectId && vercelFields.projectId !== selectedProvider.projectId) + ) { + setProvider(updatedProvider); + } + + provider = new VercelDeployProvider({ + apiKey: selectedProvider.apiKey, + teamId: updatedProvider.teamId, + projectId: updatedProvider.projectId, + }); + } else { + throw new Error('Unknown provider type'); } - // Parse the deploy URL to extract hostname and server - const hostname = deployUrl.trim(); - const parts = hostname.split('.'); - - if (parts.length < 2) { - throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com"); - } - - // Extract the deploy server (everything after the first dot) - const deployServer = parts.slice(1).join('.'); - - return await deployProject({ + const result = await provider.deploy({ + projectId, + projectName, fs, - projectId, // Keep the original projectId for file path - deployServer, - projectPath: `/projects/${projectId}`, - signer: user.signer, - customHostname: hostname, // Pass the custom hostname - }); - }, - onSuccess: (result) => { - toast({ - title: "Deployment successful!", - description: `Your project is now live at ${result.hostname}`, + projectPath, }); - // Open the deployed site in a new tab - window.open(result.url, '_blank'); - - // Close the dialog - onOpenChange(false); - }, - onError: (error) => { - toast({ - title: "Deployment failed", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", + // Save project-specific settings + await updateProjectSettings({ + providerId: selectedProviderId, + netlify: selectedProvider.type === 'netlify' ? { siteId: netlifyFields.siteId } : undefined, + vercel: selectedProvider.type === 'vercel' ? { + teamId: vercelFields.teamId, + projectId: vercelFields.projectId, + } : undefined, }); - }, - }); - const handleDeploy = () => { - if (onFirstInteraction) { - onFirstInteraction(); + setDeployResult(result); + } catch (err) { + setError(err instanceof Error ? err.message : 'Deployment failed'); + } finally { + setIsDeploying(false); } - deployMutation.mutate(); }; - const handleUrlChange = (value: string) => { - // Remove protocol if user enters it - const cleanValue = value.replace(/^https?:\/\//, ''); - setDeployUrl(cleanValue); - }; - - const isValidUrl = () => { - const trimmed = deployUrl.trim(); - return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.'); + const handleClose = () => { + setSelectedProviderId(''); + setDeployResult(null); + setError(null); + setNetlifyFields({ siteId: '' }); + setVercelFields({ teamId: '', projectId: '' }); + onOpenChange(false); }; return ( - - + + - - Deploy "{projectName}" + + Deploy Project + + Deploy your project to a hosting platform + -
-
- -
- - https:// - - handleUrlChange(e.target.value)} - placeholder={`${projectId}.${config.deployServer}`} - className="pl-16" - disabled={deployMutation.isPending} - /> + {deployResult ? ( +
+ + + + Your project has been successfully deployed! + + + +
+ +
+ + +
+
+ +
+
-

- Your project will be deployed to this URL. You can customize the subdomain. -

- - {!user && ( -
-

- You must be logged into Nostr to deploy projects. -

-
- )} -
- - - - + +
+ )} - {deployMutation.isPending ? 'Deploying...' : 'Deploy'} - - +
+ )}
); -} \ No newline at end of file +} diff --git a/src/components/DeploySettingsProvider.tsx b/src/components/DeploySettingsProvider.tsx new file mode 100644 index 00000000..785ee84f --- /dev/null +++ b/src/components/DeploySettingsProvider.tsx @@ -0,0 +1,82 @@ +import { useState, useEffect, useMemo, type ReactNode } from 'react'; +import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext'; + +const STORAGE_KEY = 'shakespeare-deploy-settings'; + +const DEFAULT_SETTINGS: DeploySettings = { + providers: [], +}; + +export function DeploySettingsProvider({ children }: { children: ReactNode }) { + const [settings, setSettings] = useState(() => { + try { + const stored = localStorage.getItem(STORAGE_KEY); + if (stored) { + return JSON.parse(stored); + } + } catch (error) { + console.error('Failed to load deploy settings:', error); + } + return DEFAULT_SETTINGS; + }); + + useEffect(() => { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); + } catch (error) { + console.error('Failed to save deploy settings:', error); + } + }, [settings]); + + const updateSettings = (updates: Partial) => { + setSettings(prev => ({ ...prev, ...updates })); + }; + + const setProvider = (provider: DeployProvider) => { + setSettings(prev => { + const existingIndex = prev.providers.findIndex(p => p.id === provider.id); + + if (existingIndex >= 0) { + // Update existing provider + const newProviders = [...prev.providers]; + newProviders[existingIndex] = provider; + return { ...prev, providers: newProviders }; + } else { + // Add new provider + return { ...prev, providers: [...prev.providers, provider] }; + } + }); + }; + + const removeProvider = (id: string) => { + setSettings(prev => ({ + ...prev, + providers: prev.providers.filter(p => p.id !== id), + // Clear default if it was removed + defaultProviderId: prev.defaultProviderId === id ? undefined : prev.defaultProviderId, + })); + }; + + const setProviders = (providers: DeployProvider[]) => { + setSettings(prev => ({ ...prev, providers })); + }; + + const isConfigured = useMemo(() => { + return settings.providers.length > 0; + }, [settings.providers]); + + const value = { + settings, + updateSettings, + setProvider, + removeProvider, + setProviders, + isConfigured, + }; + + return ( + + {children} + + ); +} diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index e59412bf..a3b633bd 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -71,7 +71,7 @@ interface JSONRPCResponse { id: number; } -export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) { +export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) { const { t } = useTranslation(); const { config } = useAppContext(); const { previewDomain } = config; @@ -933,7 +933,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o projectName={projectName} open={deployDialogOpen} onOpenChange={setDeployDialogOpen} - onFirstInteraction={onFirstInteraction} /> )} diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts new file mode 100644 index 00000000..4f9495a2 --- /dev/null +++ b/src/contexts/DeploySettingsContext.ts @@ -0,0 +1,26 @@ +import { createContext } from 'react'; + +export interface DeployProvider { + id: string; + type: 'shakespeare' | 'netlify' | 'vercel'; + apiKey?: string; // Not used for Shakespeare Deploy + siteId?: string; // For Netlify + projectId?: string; // For Vercel + teamId?: string; // For Vercel +} + +export interface DeploySettings { + providers: DeployProvider[]; + defaultProviderId?: string; +} + +export interface DeploySettingsContextType { + settings: DeploySettings; + updateSettings: (settings: Partial) => void; + setProvider: (provider: DeployProvider) => void; + removeProvider: (id: string) => void; + setProviders: (providers: DeployProvider[]) => void; + isConfigured: boolean; +} + +export const DeploySettingsContext = createContext(undefined); diff --git a/src/hooks/useDeploySettings.tsx b/src/hooks/useDeploySettings.tsx new file mode 100644 index 00000000..294e7ae1 --- /dev/null +++ b/src/hooks/useDeploySettings.tsx @@ -0,0 +1,10 @@ +import { useContext } from 'react'; +import { DeploySettingsContext } from '@/contexts/DeploySettingsContext'; + +export function useDeploySettings() { + const context = useContext(DeploySettingsContext); + if (!context) { + throw new Error('useDeploySettings must be used within DeploySettingsProvider'); + } + return context; +} diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts new file mode 100644 index 00000000..af0a9b5d --- /dev/null +++ b/src/hooks/useProjectDeploySettings.ts @@ -0,0 +1,73 @@ +import { useState, useEffect, useCallback } from 'react'; +import { useFS } from './useFS'; + +export interface ProjectDeploySettings { + providerId?: string; + netlify?: { + siteId?: string; + }; + vercel?: { + teamId?: string; + projectId?: string; + }; +} + +/** + * Hook to manage project-specific deployment settings + * Stores settings in .git/shakespeare/deploy.json + */ +export function useProjectDeploySettings(projectId: string) { + const fs = useFS(); + const [settings, setSettings] = useState({}); + const [isLoading, setIsLoading] = useState(true); + + const settingsPath = `/projects/${projectId}/.git/shakespeare/deploy.json`; + + const loadSettings = useCallback(async () => { + try { + setIsLoading(true); + const content = await fs.fs.readFile(settingsPath, 'utf8'); + setSettings(JSON.parse(content as string)); + } catch { + // File doesn't exist or is invalid, use empty settings + setSettings({}); + } finally { + setIsLoading(false); + } + }, [fs.fs, settingsPath]); + + useEffect(() => { + loadSettings(); + }, [loadSettings]); + + const saveSettings = async (newSettings: ProjectDeploySettings) => { + try { + // Ensure .git/shakespeare directory exists + const shakespeareDir = `/projects/${projectId}/.git/shakespeare`; + try { + await fs.fs.stat(shakespeareDir); + } catch { + await fs.fs.mkdir(shakespeareDir, { recursive: true }); + } + + // Save settings + await fs.fs.writeFile(settingsPath, JSON.stringify(newSettings, null, 2), 'utf8'); + setSettings(newSettings); + } catch (error) { + console.error('Failed to save deploy settings:', error); + throw error; + } + }; + + const updateSettings = async (updates: Partial) => { + const newSettings = { ...settings, ...updates }; + await saveSettings(newSettings); + }; + + return { + settings, + isLoading, + updateSettings, + saveSettings, + }; +} diff --git a/src/lib/deploy-providers/NetlifyDeployProvider.ts b/src/lib/deploy-providers/NetlifyDeployProvider.ts new file mode 100644 index 00000000..6086826a --- /dev/null +++ b/src/lib/deploy-providers/NetlifyDeployProvider.ts @@ -0,0 +1,161 @@ +import JSZip from 'jszip'; +import type { DeployProvider, DeployOptions, DeployResult, NetlifyDeployConfig } from './types'; + +interface NetlifySite { + id: string; + site_id: string; + name: string; + url: string; + admin_url: string; +} + +interface NetlifyBuildResponse { + id: string; + deploy_id: string; + state: string; + error?: string; +} + +/** + * Netlify Deploy Provider + * Uses Netlify API with personal access token + */ +export class NetlifyDeployProvider implements DeployProvider { + private config: NetlifyDeployConfig; + + constructor(config: NetlifyDeployConfig) { + this.config = config; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, projectName, fs, projectPath } = options; + const { apiKey, siteId, siteName } = this.config; + + // Check if dist directory exists and contains index.html + const distPath = `${projectPath}/dist`; + try { + await fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No index.html found in dist directory. Please build the project first.'); + } + + // Get or create site + let activeSiteId = siteId; + let siteUrl = ''; + + if (!activeSiteId) { + // Create new site + const site = await this.createSite(apiKey, siteName || projectName || projectId); + activeSiteId = site.id; + siteUrl = site.url; + } else { + // Get existing site URL + const site = await this.getSite(apiKey, activeSiteId); + siteUrl = site.url; + } + + // Create ZIP of dist directory + const zip = new JSZip(); + await this.addDirectoryToZip(fs, distPath, zip); + + // Generate ZIP blob + const zipBlob = await zip.generateAsync({ type: 'blob' }); + + // Deploy to Netlify + await this.triggerBuild(apiKey, activeSiteId, zipBlob, `Deploy from Shakespeare - ${new Date().toISOString()}`); + + return { + url: siteUrl, + metadata: { + siteId: activeSiteId, + provider: 'netlify', + }, + }; + } + + private async createSite(apiKey: string, name: string): Promise { + const response = await fetch('https://api.netlify.com/api/v1/sites', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + name, + created_via: 'shakespeare', + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create Netlify site: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async getSite(apiKey: string, siteId: string): Promise { + const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, { + method: 'GET', + headers: { + 'Authorization': `Bearer ${apiKey}`, + }, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to get Netlify site: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async triggerBuild(apiKey: string, siteId: string, zipBlob: Blob, title: string): Promise { + const formData = new FormData(); + formData.append('title', title); + formData.append('zip', zipBlob, 'deploy.zip'); + + const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/builds`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiKey}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise { + try { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + + if (entry.isDirectory()) { + // Create folder in zip and recursively add its contents + const folder = zip.folder(entry.name); + if (folder) { + await this.addDirectoryToZip(fs, fullPath, folder); + } + } else if (entry.isFile()) { + // Add file to zip + try { + const fileContent = await fs.readFile(fullPath); + zip.file(entry.name, fileContent); + } catch { + console.warn(`Failed to read file ${fullPath}`); + } + } + } + } catch { + console.warn(`Failed to read directory ${dirPath}`); + } + } +} diff --git a/src/lib/deploy-providers/ShakespeareDeployProvider.ts b/src/lib/deploy-providers/ShakespeareDeployProvider.ts new file mode 100644 index 00000000..6e4f2f66 --- /dev/null +++ b/src/lib/deploy-providers/ShakespeareDeployProvider.ts @@ -0,0 +1,93 @@ +import JSZip from 'jszip'; +import { NIP98Client } from '@nostrify/nostrify'; +import type { DeployProvider, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types'; + +/** + * Shakespeare Deploy Provider + * Uses NIP-98 authentication with Nostr signer + */ +export class ShakespeareDeployProvider implements DeployProvider { + private config: ShakespeareDeployConfig; + + constructor(config: ShakespeareDeployConfig) { + this.config = config; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, fs, projectPath } = options; + const { signer, deployServer = 'shakespeare.wtf', customHostname } = this.config; + + // Use custom hostname if provided, otherwise construct from projectId.deployServer + const hostname = customHostname || `${projectId}.${deployServer}`; + const deployUrl = `https://${deployServer}/deploy`; + const siteUrl = `https://${hostname}`; + + // Check if dist directory exists and contains index.html + const distPath = `${projectPath}/dist`; + try { + await fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No index.html found in dist directory. Please build the project first.'); + } + + // Create ZIP of dist directory + const zip = new JSZip(); + await this.addDirectoryToZip(fs, distPath, zip); + + // Generate ZIP blob + const zipBlob = await zip.generateAsync({ type: 'blob' }); + + // Create FormData + const formData = new FormData(); + formData.append('hostname', hostname); + formData.append('file', zipBlob, `${projectId}.zip`); + + // Create NIP-98 authenticated client and deploy + const nip98Client = new NIP98Client({ signer }); + const response = await nip98Client.fetch(deployUrl, { + method: 'POST', + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Deployment failed: ${response.status} ${response.statusText}. ${errorText}`); + } + + return { + url: siteUrl, + metadata: { + hostname, + provider: 'shakespeare', + }, + }; + } + + private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise { + try { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + + if (entry.isDirectory()) { + // Create folder in zip and recursively add its contents + const folder = zip.folder(entry.name); + if (folder) { + await this.addDirectoryToZip(fs, fullPath, folder); + } + } else if (entry.isFile()) { + // Add file to zip + try { + const fileContent = await fs.readFile(fullPath); + zip.file(entry.name, fileContent); + } catch { + console.warn(`Failed to read file ${fullPath}`); + } + } + } + } catch { + console.warn(`Failed to read directory ${dirPath}`); + } + } +} diff --git a/src/lib/deploy-providers/VercelDeployProvider.ts b/src/lib/deploy-providers/VercelDeployProvider.ts new file mode 100644 index 00000000..499b99f7 --- /dev/null +++ b/src/lib/deploy-providers/VercelDeployProvider.ts @@ -0,0 +1,131 @@ +import type { DeployProvider, DeployOptions, DeployResult, VercelDeployConfig } from './types'; + +interface VercelFile { + file: string; + data: string; +} + +interface VercelDeployment { + id: string; + url: string; + name: string; + readyState: string; +} + +/** + * Vercel Deploy Provider + * Uses Vercel REST API with access token + */ +export class VercelDeployProvider implements DeployProvider { + private config: VercelDeployConfig; + + constructor(config: VercelDeployConfig) { + this.config = config; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, projectName, fs, projectPath } = options; + const { apiKey, teamId } = this.config; + + // Check if dist directory exists and contains index.html + const distPath = `${projectPath}/dist`; + try { + await fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No index.html found in dist directory. Please build the project first.'); + } + + // Collect all files from dist directory + const files: VercelFile[] = []; + await this.collectFiles(fs, distPath, '', files); + + // Create deployment payload + const deploymentPayload = { + name: this.config.projectName || projectName || projectId, + files, + projectSettings: { + framework: null, // Static deployment + }, + target: 'production' as const, + }; + + // Build API URL with optional team parameter + let apiUrl = 'https://api.vercel.com/v13/deployments'; + if (teamId) { + apiUrl += `?teamId=${teamId}`; + } + + // Deploy to Vercel + const response = await fetch(apiUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(deploymentPayload), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to deploy to Vercel: ${response.status} ${response.statusText}. ${errorText}`); + } + + const deployment: VercelDeployment = await response.json(); + + return { + url: `https://${deployment.url}`, + metadata: { + deploymentId: deployment.id, + provider: 'vercel', + readyState: deployment.readyState, + }, + }; + } + + private async collectFiles( + fs: DeployOptions['fs'], + dirPath: string, + relativePath: string, + files: VercelFile[] + ): Promise { + try { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name; + + if (entry.isDirectory()) { + // Recursively collect files from subdirectories + await this.collectFiles(fs, fullPath, entryRelativePath, files); + } else if (entry.isFile()) { + try { + // Read file content + const fileContent = await fs.readFile(fullPath); + + // Convert to base64 for Vercel API + let base64Content: string; + if (typeof fileContent === 'string') { + base64Content = btoa(fileContent); + } else { + // Handle Uint8Array + const binary = Array.from(fileContent) + .map(byte => String.fromCharCode(byte)) + .join(''); + base64Content = btoa(binary); + } + + files.push({ + file: entryRelativePath, + data: base64Content, + }); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } +} diff --git a/src/lib/deploy-providers/index.ts b/src/lib/deploy-providers/index.ts new file mode 100644 index 00000000..86d0350b --- /dev/null +++ b/src/lib/deploy-providers/index.ts @@ -0,0 +1,4 @@ +export * from './types'; +export * from './ShakespeareDeployProvider'; +export * from './NetlifyDeployProvider'; +export * from './VercelDeployProvider'; diff --git a/src/lib/deploy-providers/types.ts b/src/lib/deploy-providers/types.ts new file mode 100644 index 00000000..34839199 --- /dev/null +++ b/src/lib/deploy-providers/types.ts @@ -0,0 +1,44 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { NostrSigner } from '@nostrify/nostrify'; + +export interface DeployOptions { + /** Project ID */ + projectId: string; + /** Filesystem instance containing the project */ + fs: JSRuntimeFS; + /** Path to the project directory */ + projectPath: string; + /** Project name */ + projectName?: string; +} + +export interface DeployResult { + /** The deployed URL */ + url: string; + /** Additional metadata */ + metadata?: Record; +} + +export interface DeployProvider { + /** Deploy a project */ + deploy(options: DeployOptions): Promise; +} + +export interface ShakespeareDeployConfig { + signer: NostrSigner; + deployServer?: string; + customHostname?: string; +} + +export interface NetlifyDeployConfig { + apiKey: string; + siteId?: string; + siteName?: string; +} + +export interface VercelDeployConfig { + apiKey: string; + projectId?: string; + teamId?: string; + projectName?: string; +} diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 69391b87..1c4bdd30 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -88,6 +88,9 @@ const resources = { aiSettingsDescription: 'Configure AI providers and API keys', gitSettings: 'Git Settings', gitSettingsDescription: 'Configure Git credentials for HTTP authentication', + deploySettings: 'Deployment', + deploySettingsDescription: 'Configure deployment providers', + deploySettingsDescriptionLong: 'Configure deployment providers to deploy your projects to various hosting platforms.', nostrSettings: 'Nostr Settings', nostrSettingsDescription: 'Configure relay connections and Nostr preferences', storageSettings: 'Storage', @@ -205,6 +208,9 @@ const resources = { loginToNostrRequired: 'Log in to Nostr to use this provider', goToNostrSettings: 'Go to Nostr Settings', + // Deploy Settings + shakespeareDeployNostrAuth: 'This provider uses Nostr authentication. Make sure you are logged in to deploy.', + // Git Settings gitSettingsDescriptionLong: 'Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.', configuredCredentials: 'Configured Credentials', @@ -412,6 +418,9 @@ const resources = { aiSettingsDescription: 'Configure provedores de IA e chaves de API', gitSettings: 'Configurações do Git', gitSettingsDescription: 'Configure credenciais do Git para autenticação HTTP', + deploySettings: 'Implantação', + deploySettingsDescription: 'Configure provedores de implantação', + deploySettingsDescriptionLong: 'Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.', nostrSettings: 'Configurações do Nostr', nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr', storageSettings: 'Armazenamento', @@ -529,6 +538,9 @@ const resources = { loginToNostrRequired: 'Faça login no Nostr para usar este provedor', goToNostrSettings: 'Ir para Configurações do Nostr', + // Deploy Settings + shakespeareDeployNostrAuth: 'Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.', + // Git Settings gitSettingsDescriptionLong: 'Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.', configuredCredentials: 'Credenciais Configuradas', @@ -742,6 +754,9 @@ const resources = { aiSettingsDescription: '配置AI提供商和API密钥', gitSettings: 'Git设置', gitSettingsDescription: '配置HTTP身份验证的Git凭据', + deploySettings: '部署', + deploySettingsDescription: '配置部署提供商', + deploySettingsDescriptionLong: '配置部署提供商以将您的项目部署到各种托管平台。', nostrSettings: 'Nostr设置', nostrSettingsDescription: '配置中继连接和Nostr偏好', storageSettings: '存储', @@ -859,6 +874,9 @@ const resources = { loginToNostrRequired: '登录Nostr以使用此提供商', goToNostrSettings: '前往Nostr设置', + // Deploy Settings + shakespeareDeployNostrAuth: '此提供商使用Nostr身份验证。请确保您已登录以进行部署。', + // Git Settings gitSettingsDescriptionLong: '配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。', configuredCredentials: '已配置的凭据', diff --git a/src/lib/settingsItems.ts b/src/lib/settingsItems.ts index 5b2de675..c116a6c1 100644 --- a/src/lib/settingsItems.ts +++ b/src/lib/settingsItems.ts @@ -1,4 +1,4 @@ -import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings } from 'lucide-react'; +import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react'; export interface SettingsItem { id: string; @@ -35,6 +35,13 @@ export const getSettingsItems = (t: (key: string) => string): SettingsItem[] => icon: GitBranch, href: '/settings/git', }, + { + id: 'deploy', + title: t('deploySettings'), + description: t('deploySettingsDescription'), + icon: Rocket, + href: '/settings/deploy', + }, { id: 'nostr', title: t('nostrSettings'), diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx new file mode 100644 index 00000000..653b8c30 --- /dev/null +++ b/src/pages/DeploySettings.tsx @@ -0,0 +1,382 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Rocket, ArrowLeft, Trash2, Check } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { PasswordInput } from '@/components/ui/password-input'; +import { Label } from '@/components/ui/label'; +import { Badge } from '@/components/ui/badge'; +import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; +import { useDeploySettings } from '@/hooks/useDeploySettings'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useIsMobile } from '@/hooks/useIsMobile'; +import { useNavigate, Link } from 'react-router-dom'; +import type { DeployProvider } from '@/contexts/DeploySettingsContext'; + +interface PresetProvider { + id: string; + type: 'shakespeare' | 'netlify' | 'vercel'; + name: string; + description: string; + requiresNostr?: boolean; + apiKeyLabel?: string; + apiKeyURL?: string; + fields?: Array<{ + key: string; + label: string; + placeholder: string; + type?: 'text' | 'password'; + }>; +} + +const PRESET_PROVIDERS: PresetProvider[] = [ + { + id: 'shakespeare', + type: 'shakespeare', + name: 'Shakespeare Deploy', + description: 'Deploy to Shakespeare hosting with Nostr authentication', + requiresNostr: true, + }, + { + id: 'netlify', + type: 'netlify', + name: 'Netlify', + description: 'Deploy to Netlify with personal access token', + apiKeyLabel: 'Personal Access Token', + apiKeyURL: 'https://app.netlify.com/user/applications#personal-access-tokens', + fields: [ + { + key: 'siteId', + label: 'Site ID (Optional)', + placeholder: 'Leave empty to create new site', + type: 'text', + }, + ], + }, + { + id: 'vercel', + type: 'vercel', + name: 'Vercel', + description: 'Deploy to Vercel with access token', + apiKeyLabel: 'Access Token', + apiKeyURL: 'https://vercel.com/account/tokens', + fields: [ + { + key: 'teamId', + label: 'Team ID (Optional)', + placeholder: 'Leave empty for personal account', + type: 'text', + }, + { + key: 'projectId', + label: 'Project ID (Optional)', + placeholder: 'Leave empty to create new project', + type: 'text', + }, + ], + }, +]; + +export function DeploySettings() { + const { t } = useTranslation(); + const { settings, setProvider, removeProvider } = useDeploySettings(); + const { user } = useCurrentUser(); + const isMobile = useIsMobile(); + const navigate = useNavigate(); + + const [presetApiKeys, setPresetApiKeys] = useState>({}); + const [presetFields, setPresetFields] = useState>>({}); + + const handleAddPresetProvider = (preset: PresetProvider) => { + // For Shakespeare, just check if user is logged in + if (preset.requiresNostr && !user) { + return; + } + + const apiKey = presetApiKeys[preset.id]; + + // For non-Shakespeare providers, require API key + if (!preset.requiresNostr && !apiKey?.trim()) { + return; + } + + const newProvider: DeployProvider = { + id: preset.id, + type: preset.type, + apiKey: preset.requiresNostr ? undefined : apiKey?.trim(), + }; + + // Add any additional fields + const fields = presetFields[preset.id] || {}; + Object.entries(fields).forEach(([key, value]) => { + if (value.trim()) { + newProvider[key as keyof DeployProvider] = value.trim() as never; + } + }); + + setProvider(newProvider); + + // Clear inputs + setPresetApiKeys(prev => ({ ...prev, [preset.id]: '' })); + setPresetFields(prev => ({ ...prev, [preset.id]: {} })); + }; + + const handleRemoveProvider = (id: string) => { + removeProvider(id); + }; + + const handleUpdateProvider = (provider: DeployProvider) => { + setProvider(provider); + }; + + const handleFieldChange = (presetId: string, fieldKey: string, value: string) => { + setPresetFields(prev => ({ + ...prev, + [presetId]: { + ...(prev[presetId] || {}), + [fieldKey]: value, + }, + })); + }; + + const configuredProviderIds = settings.providers.map(p => p.id); + const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id)); + + return ( +
+ {isMobile && ( +
+ +
+

+ + {t('deploySettings')} +

+

+ {t('deploySettingsDescriptionLong')} +

+
+
+ )} + + {!isMobile && ( +
+

+ + {t('deploySettings')} +

+

+ {t('deploySettingsDescriptionLong')} +

+
+ )} + +
+ {/* Configured Providers */} + {settings.providers.length > 0 && ( +
+

{t('configuredProviders')}

+ + {settings.providers.map((provider) => { + const preset = PRESET_PROVIDERS.find(p => p.id === provider.id); + + return ( + + +
+
+ + {preset?.name || provider.id} + + {provider.type === 'shakespeare' && ( + Nostr + )} +
+ +
+
+ +
+ {provider.type === 'shakespeare' ? ( +

+ {t('shakespeareDeployNostrAuth')} +

+ ) : ( + <> +
+ + handleUpdateProvider({ ...provider, apiKey: e.target.value })} + /> +
+ + {/* Additional fields based on provider type */} + {preset?.fields?.map((field) => ( +
+ + {field.type === 'password' ? ( + handleUpdateProvider({ + ...provider, + [field.key]: e.target.value, + })} + /> + ) : ( + handleUpdateProvider({ + ...provider, + [field.key]: e.target.value, + })} + /> + )} +
+ ))} + + )} +
+
+
+ ); + })} +
+
+ )} + + {/* Available Preset Providers */} + {availablePresets.length > 0 && ( +
+

{t('addProvider')}

+
+ {availablePresets.map((preset) => { + const isNostrPreset = preset.requiresNostr; + const isLoggedIntoNostr = !!user; + const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr; + + return ( +
+
+
+
{preset.name}
+

{preset.description}

+
+ {preset.apiKeyURL && ( + + )} +
+ + {showNostrLoginRequired ? ( +
+

+ {t('loginToNostrRequired')} +

+ +
+ ) : ( +
+ {!preset.requiresNostr && ( +
+ + setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + /> +
+ )} + + {/* Additional fields */} + {preset.fields?.map((field) => ( +
+ + {field.type === 'password' ? ( + handleFieldChange(preset.id, field.key, e.target.value)} + /> + ) : ( + handleFieldChange(preset.id, field.key, e.target.value)} + /> + )} +
+ ))} + + +
+ )} +
+ ); + })} +
+
+ )} +
+
+ ); +} + +export default DeploySettings;