diff --git a/services/proxy.ts b/services/proxy.ts index cc26d7c9..e8fe6721 100644 --- a/services/proxy.ts +++ b/services/proxy.ts @@ -13,7 +13,7 @@ export default { status: 200, headers: { "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS", + "Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS", "Access-Control-Allow-Headers": "*", // Or specify specific headers "Access-Control-Max-Age": "86400", // Cache preflight for 24 hours } @@ -32,7 +32,7 @@ export default { const response = new Response(targetResponse.body, targetResponse); response.headers.set("Access-Control-Allow-Origin", "*"); - response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS"); + response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"); response.headers.set("Access-Control-Allow-Headers", "*"); return response; diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index 1f78788e..8c8dbd88 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -27,13 +27,15 @@ import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useAppContext } from '@/hooks/useAppContext'; import { useNostr } from '@nostrify/react'; -import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy'; +import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy'; import { Link } from 'react-router-dom'; -import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext'; +import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } 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'; +import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm'; +import { DenoDeployForm } from '@/components/deploy/DenoDeployForm'; /** * Helper function to get provider URL for favicon @@ -58,6 +60,18 @@ function getProviderUrl(provider: DeployProvider): string | null { } return 'https://vercel.com'; + case 'cloudflare': + if (provider.baseURL) { + return provider.baseURL; + } + return 'https://cloudflare.com'; + + case 'deno': + if (provider.baseURL) { + return provider.baseURL; + } + return 'https://deno.com'; + case 'nsite': return null; @@ -110,6 +124,14 @@ interface VercelFormData { teamId: string; } +interface CloudflareFormData { + projectName: string; +} + +interface DenoDeployFormData { + projectName: string; +} + export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) { const { t } = useTranslation(); const { settings } = useDeploySettings(); @@ -141,6 +163,12 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectName: projectName || projectId, teamId: '', }); + const [cloudflareForm, setCloudflareForm] = useState({ + projectName: projectName || projectId, + }); + const [denoDeployForm, setDenoDeployForm] = useState({ + projectName: projectName || projectId, + }); // Load project settings when dialog opens useEffect(() => { @@ -230,6 +258,42 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectName: vercelForm.projectName || undefined, corsProxy: vercelProvider.proxy ? config.corsProxy : undefined, }); + } else if (selectedProvider.type === 'cloudflare') { + const cloudflareProvider = selectedProvider as CloudflareProvider; + if (!cloudflareProvider.apiKey) { + throw new Error('Cloudflare API key is required'); + } + if (!cloudflareProvider.accountId) { + throw new Error('Cloudflare account ID is required'); + } + + adapter = new CloudflareAdapter({ + fs, + apiKey: cloudflareProvider.apiKey, + accountId: cloudflareProvider.accountId, + baseURL: cloudflareProvider.baseURL, + baseDomain: cloudflareProvider.baseDomain, + projectName: cloudflareForm.projectName || undefined, + corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined, + }); + } else if (selectedProvider.type === 'deno') { + const denoProvider = selectedProvider as DenoDeployProvider; + if (!denoProvider.apiKey) { + throw new Error('Deno Deploy access token is required'); + } + if (!denoProvider.organizationId) { + throw new Error('Deno Deploy organization ID is required'); + } + + adapter = new DenoDeployAdapter({ + fs, + apiKey: denoProvider.apiKey, + organizationId: denoProvider.organizationId, + baseDomain: denoProvider.baseDomain, + baseURL: denoProvider.baseURL, + projectName: denoDeployForm.projectName || undefined, + corsProxy: denoProvider.proxy ? config.corsProxy : undefined, + }); } else { throw new Error('Unknown provider type'); } @@ -269,6 +333,20 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectId: vercelForm.projectName || undefined, }, }); + } else if (selectedProvider.type === 'cloudflare') { + await updateProjectSettings(selectedProviderId, { + type: 'cloudflare', + data: { + projectName: cloudflareForm.projectName || undefined, + }, + }); + } else if (selectedProvider.type === 'deno') { + await updateProjectSettings(selectedProviderId, { + type: 'deno', + data: { + projectName: denoDeployForm.projectName || undefined, + }, + }); } setDeployResult(result); @@ -288,6 +366,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setNsiteForm({ nsec: '' }); setNetlifyForm({ siteId: '', siteName: '' }); setVercelForm({ projectName: projectName || projectId, teamId: '' }); + setCloudflareForm({ projectName: projectName || projectId }); + setDenoDeployForm({ projectName: projectName || projectId }); onOpenChange(false); }; @@ -311,6 +391,14 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setVercelForm({ projectName, teamId }); }, []); + const handleCloudflareProjectChange = useCallback((projectName: string) => { + setCloudflareForm({ projectName }); + }, []); + + const handleDenoDeployProjectChange = useCallback((projectName: string) => { + setDenoDeployForm({ projectName }); + }, []); + const renderProviderFields = () => { if (!selectedProvider) return null; @@ -373,6 +461,46 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep ); } + if (selectedProvider.type === 'cloudflare') { + const cloudflareProvider = selectedProvider as CloudflareProvider; + const savedConfig = projectSettings.providers[selectedProviderId]; + const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined; + + return ( + + ); + } + + if (selectedProvider.type === 'deno') { + const denoProvider = selectedProvider as DenoDeployProvider; + const savedConfig = projectSettings.providers[selectedProviderId]; + const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined; + + return ( + + ); + } + return null; }; @@ -503,7 +631,9 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep (selectedProvider.type === 'shakespeare' && !user) || (selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) || (selectedProvider.type === 'nsite' && !nsiteForm.nsec) || - (selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) + (selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) || + (selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) || + (selectedProvider.type === 'deno' && !denoDeployForm.projectName) } > {isDeploying ? ( diff --git a/src/components/deploy/CloudflareDeployForm.tsx b/src/components/deploy/CloudflareDeployForm.tsx new file mode 100644 index 00000000..0acb061b --- /dev/null +++ b/src/components/deploy/CloudflareDeployForm.tsx @@ -0,0 +1,219 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Plus, ExternalLink } from 'lucide-react'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Button } from '@/components/ui/button'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Skeleton } from '@/components/ui/skeleton'; +import { proxyUrl } from '@/lib/proxyUrl'; + +interface CloudflareWorkerScript { + id: string; + etag: string; + handlers: string[]; + modified_on: string; + created_on: string; + has_assets: boolean; +} + +interface CloudflareDeployFormProps { + apiKey: string; + accountId: string; + baseURL?: string; + baseDomain?: string; + projectId: string; + projectName?: string; + savedProjectName?: string; + onProjectChange: (projectName: string) => void; + corsProxy?: string; +} + +export function CloudflareDeployForm({ + apiKey, + accountId, + baseURL = 'https://api.cloudflare.com/client/v4', + baseDomain = 'workers.dev', + projectId, + projectName, + savedProjectName, + onProjectChange, + corsProxy, +}: CloudflareDeployFormProps) { + const [workers, setWorkers] = useState([]); + const [workersSubdomain, setWorkersSubdomain] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedProjectName, setSelectedProjectName] = useState(''); + const [newProjectName, setNewProjectName] = useState(projectName || projectId); + + const fetchWorkersData = useCallback(async () => { + setIsLoading(true); + setError(null); + + try { + // Fetch workers subdomain and workers list in parallel + const subdomainUrl = `${baseURL}/accounts/${accountId}/workers/subdomain`; + const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`; + + const [subdomainResponse, workersResponse] = await Promise.all([ + fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, { + headers: { 'Authorization': `Bearer ${apiKey}` }, + }), + fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, { + headers: { 'Authorization': `Bearer ${apiKey}` }, + }), + ]); + + if (!subdomainResponse.ok) { + throw new Error(`Failed to fetch workers subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`); + } + + if (!workersResponse.ok) { + throw new Error(`Failed to fetch workers: ${workersResponse.status} ${workersResponse.statusText}`); + } + + const [subdomainData, workersData] = await Promise.all([ + subdomainResponse.json(), + workersResponse.json(), + ]); + + setWorkersSubdomain(subdomainData.result?.subdomain || null); + setWorkers(workersData.result || []); + + // If there's a saved project name and it exists in the list, select it + // Otherwise leave it empty (showing placeholder) + if (savedProjectName && workersData.result?.some((w: CloudflareWorkerScript) => w.id === savedProjectName)) { + setSelectedProjectName(savedProjectName); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch workers data'); + } finally { + setIsLoading(false); + } + }, [apiKey, accountId, baseURL, savedProjectName, corsProxy]); + + useEffect(() => { + fetchWorkersData(); + }, [fetchWorkersData]); + + // Update newProjectName when switching to "new" if it's empty + useEffect(() => { + if (selectedProjectName === 'new' && !newProjectName) { + setNewProjectName(projectName || projectId); + } + }, [selectedProjectName, newProjectName, projectName, projectId]); + + useEffect(() => { + if (selectedProjectName === '') { + // No selection yet - don't call onProjectChange + return; + } else if (selectedProjectName === 'new') { + onProjectChange(newProjectName); + } else { + onProjectChange(selectedProjectName); + } + }, [selectedProjectName, newProjectName, onProjectChange]); + + if (isLoading) { + return ( +
+
+ + +
+ +
+ ); + } + + const selectedWorker = workers.find(w => w.id === selectedProjectName); + + // Construct the URL preview + const getWorkerUrl = (scriptName: string) => { + if (workersSubdomain) { + return `https://${scriptName}.${workersSubdomain}.${baseDomain}`; + } + return `https://${scriptName}..${baseDomain}`; + }; + + return ( +
+ {error && ( + + {error} + + )} + +
+ + +
+ + {selectedProjectName === 'new' ? ( +
+ + setNewProjectName(e.target.value)} + placeholder={projectName || projectId} + /> +

+ URL: {getWorkerUrl(newProjectName || projectId)} +

+

+ A new worker will be created when you deploy +

+
+ ) : selectedWorker ? ( +
+
+
+
+

{selectedWorker.id}

+

+ {getWorkerUrl(selectedWorker.id)} +

+
+ +
+
+

+ Deployment will update this existing worker +

+
+ ) : null} +
+ ); +} diff --git a/src/components/deploy/DenoDeployForm.tsx b/src/components/deploy/DenoDeployForm.tsx new file mode 100644 index 00000000..961d2726 --- /dev/null +++ b/src/components/deploy/DenoDeployForm.tsx @@ -0,0 +1,198 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Plus, ExternalLink } from 'lucide-react'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Button } from '@/components/ui/button'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Skeleton } from '@/components/ui/skeleton'; +import { proxyUrl } from '@/lib/proxyUrl'; + +interface DenoProject { + id: string; + name: string; + createdAt: string; + updatedAt: string; +} + +interface DenoDeployFormProps { + apiKey: string; + organizationId: string; + baseURL?: string; + baseDomain?: string; + projectId: string; + projectName?: string; + savedProjectName?: string; + onProjectChange: (projectName: string) => void; + corsProxy?: string; +} + +export function DenoDeployForm({ + apiKey, + organizationId, + baseURL = 'https://api.deno.com/v1', + baseDomain = 'deno.dev', + projectId, + projectName, + savedProjectName, + onProjectChange, + corsProxy, +}: DenoDeployFormProps) { + const [projects, setProjects] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedProjectName, setSelectedProjectName] = useState(''); + const [newProjectName, setNewProjectName] = useState(projectName || projectId); + + const fetchProjects = useCallback(async () => { + setIsLoading(true); + setError(null); + + try { + const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`; + const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url; + + const response = await fetch(targetUrl, { + headers: { 'Authorization': `Bearer ${apiKey}` }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch projects: ${response.status} ${response.statusText}`); + } + + const data: DenoProject[] = await response.json(); + setProjects(data); + + // If there's a saved project name and it exists in the list, select it + // Otherwise leave it empty (showing placeholder) + if (savedProjectName && data.some((p: DenoProject) => p.name === savedProjectName)) { + setSelectedProjectName(savedProjectName); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch projects'); + } finally { + setIsLoading(false); + } + }, [apiKey, organizationId, baseURL, savedProjectName, corsProxy]); + + useEffect(() => { + fetchProjects(); + }, [fetchProjects]); + + // Update newProjectName when switching to "new" if it's empty + useEffect(() => { + if (selectedProjectName === 'new' && !newProjectName) { + setNewProjectName(projectName || projectId); + } + }, [selectedProjectName, newProjectName, projectName, projectId]); + + useEffect(() => { + if (selectedProjectName === '') { + // No selection yet - don't call onProjectChange + return; + } else if (selectedProjectName === 'new') { + onProjectChange(newProjectName); + } else { + onProjectChange(selectedProjectName); + } + }, [selectedProjectName, newProjectName, onProjectChange]); + + if (isLoading) { + return ( +
+
+ + +
+ +
+ ); + } + + const selectedProject = projects.find(p => p.name === selectedProjectName); + + // Construct the URL preview + const getProjectUrl = (name: string) => { + return `https://${name}.${baseDomain}`; + }; + + return ( +
+ {error && ( + + {error} + + )} + +
+ + +
+ + {selectedProjectName === 'new' ? ( +
+ + setNewProjectName(e.target.value)} + placeholder={projectName || projectId} + /> +

+ URL: {getProjectUrl(newProjectName || projectId)} +

+

+ A new project will be created when you deploy +

+
+ ) : selectedProject ? ( +
+
+
+
+

{selectedProject.name}

+

+ {getProjectUrl(selectedProject.name)} +

+
+ +
+
+

+ Deployment will create a new version for this project +

+
+ ) : null} +
+ ); +} diff --git a/src/components/deploy/index.ts b/src/components/deploy/index.ts index 2333aa0c..e0626373 100644 --- a/src/components/deploy/index.ts +++ b/src/components/deploy/index.ts @@ -2,3 +2,5 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm'; export { NetlifyDeployForm } from './NetlifyDeployForm'; export { VercelDeployForm } from './VercelDeployForm'; export { NsiteDeployForm } from './NsiteDeployForm'; +export { CloudflareDeployForm } from './CloudflareDeployForm'; +export { DenoDeployForm } from './DenoDeployForm'; diff --git a/src/components/ui/password-input.tsx b/src/components/ui/password-input.tsx index 1b19f661..a9f915fd 100644 --- a/src/components/ui/password-input.tsx +++ b/src/components/ui/password-input.tsx @@ -2,8 +2,13 @@ import * as React from "react" import { Eye, EyeOff } from "lucide-react" import { cn } from "@/lib/utils" -const PasswordInput = React.forwardRef>( - ({ className, ...props }, ref) => { +interface PasswordInputProps extends React.InputHTMLAttributes { + /** Whether to show the visibility toggle button. Defaults to true. */ + showToggle?: boolean; +} + +const PasswordInput = React.forwardRef( + ({ className, showToggle = true, ...props }, ref) => { const [showPassword, setShowPassword] = React.useState(false) const [isFocused, setIsFocused] = React.useState(false) @@ -12,7 +17,8 @@ const PasswordInput = React.forwardRef - + {showToggle && ( + + )} ) } diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index d52a5e42..09abe69a 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -32,7 +32,25 @@ export interface NsiteProvider extends BaseDeployProvider { blossomServers: string[]; } -export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider; +export interface CloudflareProvider extends BaseDeployProvider { + type: 'cloudflare'; + apiKey: string; + accountId: string; + baseURL?: string; + baseDomain?: string; + proxy?: boolean; +} + +export interface DenoDeployProvider extends BaseDeployProvider { + type: 'deno'; + apiKey: string; + organizationId: string; + baseURL?: string; + baseDomain?: string; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index 47e049c7..467bd3a9 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -31,7 +31,21 @@ export interface VercelProjectConfig { }; } -export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig; +export interface CloudflareProjectConfig { + type: 'cloudflare'; + data: { + projectName?: string; + }; +} + +export interface DenoDeployProjectConfig { + type: 'deno'; + data: { + projectName?: string; + }; +} + +export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig; export interface ProjectDeploySettings { providers: Record; diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts index ba7b2ffe..bd4c1ab5 100644 --- a/src/lib/configUtils.test.ts +++ b/src/lib/configUtils.test.ts @@ -228,6 +228,13 @@ describe('configUtils', () => { name: 'Shakespeare', type: 'shakespeare', }, + { + id: 'provider-4', + name: 'My Cloudflare', + type: 'cloudflare', + apiKey: 'cloudflare-token-789', + accountId: 'account-123', + }, ], }; diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 566dae6e..1a2a8f3b 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -106,11 +106,29 @@ const nsiteProviderSchema = baseDeployProviderSchema.extend({ blossomServers: z.array(z.string()), }); +const cloudflareProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('cloudflare'), + apiKey: z.string(), + accountId: z.string(), + baseURL: z.string().optional(), + baseDomain: z.string().optional(), +}); + +const denoDeployProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('deno'), + apiKey: z.string(), + organizationId: z.string(), + baseURL: z.string().optional(), + baseDomain: z.string().optional(), +}); + const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ shakespeareDeployProviderSchema, netlifyProviderSchema, vercelProviderSchema, nsiteProviderSchema, + cloudflareProviderSchema, + denoDeployProviderSchema, ]); const deploySettingsSchema = z.object({ diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts new file mode 100644 index 00000000..5db367c2 --- /dev/null +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -0,0 +1,406 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface AssetManifest { + [path: string]: { hash: string; size: number }; +} + +interface InitializeAssetsResponse { + buckets: string[][]; + jwt: string; +} + +interface UploadResponse { + jwt?: string; +} + +interface WorkerScript { + id: string; + etag: string; + handlers: string[]; + modified_on: string; + created_on: string; + has_assets: boolean; +} + +interface FileInfo { + hash: string; + content: Uint8Array; + size: number; + contentType: string; +} + +/** + * Cloudflare Workers Deploy Adapter + * Uses Cloudflare Workers API with static assets support + * + * Implements the Workers Assets upload workflow: + * 1. Build asset manifest with file hashes + * 2. Initialize upload session to get buckets of files to upload + * 3. Upload files in buckets using FormData with base64 content + * 4. Deploy worker with assets JWT + */ +export class CloudflareAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private accountId: string; + private baseURL: string; + private baseDomain: string; + private projectName?: string; + private corsProxy?: string; + + constructor(config: CloudflareDeployConfig) { + this.fs = config.fs; + this.apiKey = config.apiKey; + this.accountId = config.accountId; + this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4'; + this.baseDomain = config.baseDomain || 'workers.dev'; + this.projectName = config.projectName; + this.corsProxy = config.corsProxy; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, 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.'); + } + + const scriptName = this.projectName || projectId; + + // Step 1: Collect all files and build manifest + const files = new Map(); + await this.collectFiles(distPath, '', files); + + const manifest: AssetManifest = {}; + for (const [filePath, fileInfo] of files) { + // Normalize path with leading slash + const normalizedPath = '/' + filePath.replace(/\\/g, '/'); + manifest[normalizedPath] = { + hash: fileInfo.hash, + size: fileInfo.size, + }; + } + + // Step 2: Initialize upload session + const initResponse = await this.initializeUploadSession(scriptName, manifest); + + // Step 3: Upload files in buckets (in parallel for speed) + let completionJwt = initResponse.jwt; + + if (initResponse.buckets.flat().length > 0) { + // Create lookup from hash to file info + const hashToFile = new Map(); + for (const [filePath, fileInfo] of files) { + hashToFile.set(fileInfo.hash, { path: filePath, info: fileInfo }); + } + + // Upload all buckets in parallel + const uploadResults = await Promise.all( + initResponse.buckets.map((bucket) => + this.uploadBucket(initResponse.jwt, bucket, hashToFile) + ) + ); + + // Get the completion JWT from the last result that has one + const lastJwtResult = [...uploadResults].reverse().find((r) => r.jwt); + if (lastJwtResult?.jwt) { + completionJwt = lastJwtResult.jwt; + } + } + + // Step 4: Deploy the worker with assets + const deployment = await this.deployWorker(scriptName, completionJwt); + + // Step 5: Enable the workers.dev subdomain for this script + await this.enableWorkersDevSubdomain(scriptName); + + // Step 6: Get the account's workers subdomain + const subdomain = await this.getWorkersSubdomain(); + + // Construct the URL using the configurable base domain + const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`; + + return { + url: workerUrl, + metadata: { + scriptId: deployment.id, + scriptName: scriptName, + provider: 'cloudflare-workers', + hasAssets: deployment.has_assets, + modifiedOn: deployment.modified_on, + }, + }; + } + + private async getWorkersSubdomain(): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'GET', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result.subdomain; + } + + private async enableWorkersDevSubdomain(scriptName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + enabled: true, + previews_enabled: true, + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to enable workers.dev subdomain: ${response.status} ${response.statusText}. ${errorText}`); + } + } + + private async initializeUploadSession( + scriptName: string, + manifest: AssetManifest + ): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ manifest }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to initialize upload session: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async uploadBucket( + jwt: string, + bucket: string[], + hashToFile: Map + ): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const formData = new FormData(); + + for (const fileHash of bucket) { + const fileData = hashToFile.get(fileHash); + if (!fileData) { + throw new Error(`File with hash ${fileHash} not found in manifest`); + } + + // Convert content to base64 + const base64Content = this.uint8ArrayToBase64(fileData.info.content); + + // Use content type or "application/null" to signal no content-type header + const contentType = fileData.info.contentType || 'application/null'; + + // Create a File/Blob with the base64 content + const blob = new Blob([base64Content], { type: contentType }); + formData.append(fileHash, blob, fileHash); + } + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${jwt}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to upload assets: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result || {}; + } + + private async deployWorker(scriptName: string, assetsJwt: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + // Create a minimal worker script that serves static assets + // This is an assets-only worker - Cloudflare will automatically serve the uploaded assets + const workerScript = ` +export default { + async fetch(request, env) { + // This worker only serves static assets + // The assets are automatically served by Cloudflare's asset handler + return new Response('Not Found', { status: 404 }); + } +}; +`; + + const formData = new FormData(); + + // Add the worker script as the main module + const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' }); + formData.append('worker.js', scriptBlob, 'worker.js'); + + // Add metadata with assets configuration + const metadata = { + main_module: 'worker.js', + compatibility_date: new Date().toISOString().split('T')[0], + assets: { + jwt: assetsJwt, + config: { + html_handling: 'auto-trailing-slash', + not_found_handling: 'single-page-application', + }, + }, + }; + + formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); + + const response = await fetch(targetUrl, { + method: 'PUT', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async collectFiles( + dirPath: string, + relativePath: string, + files: Map + ): Promise { + try { + const entries = await this.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()) { + await this.collectFiles(fullPath, entryRelativePath, files); + } else if (entry.isFile()) { + try { + const fileContent = await this.fs.readFile(fullPath); + + // Convert to Uint8Array + let content: Uint8Array; + if (typeof fileContent === 'string') { + content = new TextEncoder().encode(fileContent); + } else { + content = fileContent; + } + + // Calculate hash (same algorithm as Wrangler uses) + const hash = await this.calculateHash(content); + + // Determine content type + const contentType = this.getContentType(entry.name); + + files.set(entryRelativePath, { + hash, + content, + size: content.length, + contentType, + }); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private async calculateHash(content: Uint8Array): Promise { + // Use xxHash algorithm like Wrangler does, but fall back to SHA-256 for browser compatibility + const hashBuffer = await crypto.subtle.digest('SHA-256', content); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + // Take first 16 bytes (32 hex chars) to match Wrangler's hash length + const hashHex = hashArray.slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join(''); + return hashHex; + } + + private uint8ArrayToBase64(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } + + private getContentType(filename: string): string { + const ext = filename.split('.').pop()?.toLowerCase() || ''; + const mimeTypes: Record = { + 'html': 'text/html', + 'htm': 'text/html', + 'css': 'text/css', + 'js': 'application/javascript', + 'mjs': 'application/javascript', + 'json': 'application/json', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'svg': 'image/svg+xml', + 'ico': 'image/x-icon', + 'webp': 'image/webp', + 'avif': 'image/avif', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'ttf': 'font/ttf', + 'eot': 'application/vnd.ms-fontobject', + 'otf': 'font/otf', + 'txt': 'text/plain', + 'xml': 'application/xml', + 'pdf': 'application/pdf', + 'zip': 'application/zip', + 'mp4': 'video/mp4', + 'webm': 'video/webm', + 'mp3': 'audio/mpeg', + 'wav': 'audio/wav', + 'ogg': 'audio/ogg', + 'wasm': 'application/wasm', + }; + return mimeTypes[ext] || 'application/octet-stream'; + } +} diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts new file mode 100644 index 00000000..041b0aa6 --- /dev/null +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -0,0 +1,287 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, DenoDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface Project { + id: string; + name: string; + createdAt: string; + updatedAt: string; +} + +interface Deployment { + id: string; + projectId: string; + status: string; + domains: string[]; + createdAt: string; + updatedAt: string; +} + +/** + * Deno Deploy Adapter + * Uses Deno Deploy API to deploy static sites + * + * Implements the Deno Deploy workflow: + * 1. Create or find existing project + * 2. Build asset manifest with file contents + * 3. Create deployment with assets + * 4. Attach domain to deployment + */ +export class DenoDeployAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private organizationId: string; + private baseURL: string; + private baseDomain: string; + private projectName?: string; + private corsProxy?: string; + + constructor(config: DenoDeployConfig) { + this.fs = config.fs; + this.apiKey = config.apiKey; + this.organizationId = config.organizationId; + this.baseURL = config.baseURL || 'https://api.deno.com/v1'; + this.baseDomain = config.baseDomain || 'deno.dev'; + this.projectName = config.projectName; + this.corsProxy = config.corsProxy; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, 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.'); + } + + const projectName = this.projectName || projectId; + + // Step 1: Get or create project + const project = await this.getOrCreateProject(projectName); + + // Step 2: Collect all files and build assets + const assets: Record = {}; + await this.collectFiles(distPath, '', assets); + + // Step 3: Create deployment with assets and domain + const domain = `${project.name}.${this.baseDomain}`; + const deployment = await this.createDeployment(project.id, assets, domain); + + return { + url: `https://${domain}`, + metadata: { + deploymentId: deployment.id, + projectId: project.id, + projectName: project.name, + provider: 'deno-deploy', + status: deployment.status, + }, + }; + } + + private async getOrCreateProject(projectName: string): Promise { + // First, try to find existing project + const existingProject = await this.findProject(projectName); + if (existingProject) { + return existingProject; + } + + // Create new project + return this.createProject(projectName); + } + + private async findProject(projectName: string): Promise { + const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'GET', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + }); + + if (!response.ok) { + // If we can't list projects, just return null and try to create + return null; + } + + const projects: Project[] = await response.json(); + return projects.find(p => p.name === projectName) || null; + } + + private async createProject(projectName: string): Promise { + const url = `${this.baseURL}/organizations/${this.organizationId}/projects`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + name: projectName, + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create project: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async createDeployment( + projectId: string, + assets: Record, + domain: string + ): Promise { + const url = `${this.baseURL}/projects/${projectId}/deployments`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + // Create a minimal server script that serves static files + // For static sites, we use a simple file server entry point + const entryPointUrl = 'main.ts'; + + // Add the entry point script that serves static files + const serverScript = ` +import { serveDir } from "jsr:@std/http/file-server"; + +Deno.serve((req) => { + return serveDir(req, { + fsRoot: ".", + showIndex: true, + enableCors: true, + }); +}); +`; + + // Add the server script to assets + assets['main.ts'] = { + kind: 'file', + content: serverScript, + encoding: 'utf-8', + }; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + entryPointUrl, + assets, + importMapUrl: null, + lockFileUrl: null, + compilerOptions: null, + envVars: {}, + // Attach domain during deployment creation instead of separately + domains: [domain], + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create deployment: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async collectFiles( + dirPath: string, + relativePath: string, + assets: Record + ): Promise { + try { + const entries = await this.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()) { + await this.collectFiles(fullPath, entryRelativePath, assets); + } else if (entry.isFile()) { + try { + const fileContent = await this.fs.readFile(fullPath); + + // Determine if file is text or binary based on extension + const isText = this.isTextFile(entry.name); + + let content: string; + let encoding: 'utf-8' | 'base64'; + + if (isText) { + if (typeof fileContent === 'string') { + content = fileContent; + } else { + content = new TextDecoder().decode(fileContent); + } + encoding = 'utf-8'; + } else { + // Binary file - encode as base64 + let bytes: Uint8Array; + if (typeof fileContent === 'string') { + bytes = new TextEncoder().encode(fileContent); + } else { + bytes = fileContent; + } + content = this.uint8ArrayToBase64(bytes); + encoding = 'base64'; + } + + assets[entryRelativePath] = { + kind: 'file', + content, + encoding, + }; + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private isTextFile(filename: string): boolean { + const textExtensions = [ + 'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', + 'json', 'xml', 'svg', 'txt', 'md', 'yaml', 'yml', 'toml', + 'sh', 'bash', 'zsh', 'fish', 'bat', 'cmd', 'ps1', + 'py', 'rb', 'php', 'java', 'c', 'cpp', 'h', 'hpp', + 'rs', 'go', 'swift', 'kt', 'scala', 'clj', 'ex', 'exs', + 'vue', 'svelte', 'astro', 'njk', 'ejs', 'pug', 'hbs', + 'graphql', 'gql', 'sql', 'csv', 'tsv', 'log', 'ini', 'cfg', + 'env', 'gitignore', 'dockerignore', 'editorconfig', + 'prettierrc', 'eslintrc', 'babelrc', 'npmrc', + 'map', // source maps + ]; + + const ext = filename.split('.').pop()?.toLowerCase() || ''; + // Also check if filename itself is a known text file + const textFilenames = [ + 'dockerfile', 'makefile', 'gemfile', 'rakefile', 'procfile', + 'license', 'readme', 'changelog', 'authors', 'contributors', + ]; + + return textExtensions.includes(ext) || textFilenames.includes(filename.toLowerCase()); + } + + private uint8ArrayToBase64(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 830bff96..24bf4795 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -3,3 +3,5 @@ export * from './ShakespeareAdapter'; export * from './NetlifyAdapter'; export * from './VercelAdapter'; export * from './NsiteAdapter'; +export * from './CloudflareAdapter'; +export * from './DenoDeployAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 5adf4eeb..60222a5d 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -54,3 +54,23 @@ export interface NsiteDeployConfig { relayUrls: string[]; blossomServers: string[]; } + +export interface CloudflareDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + accountId: string; + baseURL?: string; + baseDomain?: string; + projectName?: string; + corsProxy?: string; +} + +export interface DenoDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + organizationId: string; + baseURL?: string; + baseDomain?: string; + projectName?: string; + corsProxy?: string; +} diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index d8bdc5a5..ca57ee72 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -1,6 +1,6 @@ import { useState, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; -import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, MessageCircle } from 'lucide-react'; +import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, ExternalLink, MessageCircle } from 'lucide-react'; import { DndContext, closestCenter, @@ -437,24 +437,13 @@ export function AISettings() { return ( -
-
- } - /> -
{preset.name}
-
- {(preset.apiKeysURL && preset.id !== "routstr") && ( - - )} +
+ } + /> +
{preset.name}
{showNostrLoginRequired ? ( @@ -475,22 +464,34 @@ export function AISettings() {
{!preset.nostr && ( - setPresetApiKeys(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && - presetApiKeys[preset.id]?.trim() && - presetTermsAgreements[preset.id]) { - handleAddPresetProvider(preset); - } - }} - /> +
+ setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && + presetApiKeys[preset.id]?.trim() && + presetTermsAgreements[preset.id]) { + handleAddPresetProvider(preset); + } + }} + showToggle={!!presetApiKeys[preset.id]} + /> + {preset.apiKeysURL && !presetApiKeys[preset.id] && ( + + )} +
)} - )} +
+ {(() => { + const url = getProviderUrl(preset); + return url ? ( + } + /> + ) : ( + + ); + })()} +
{preset.name}

{preset.description}

@@ -703,34 +850,106 @@ export function DeploySettings() { ) : ( // Show manual token input
-
- {!preset.requiresNostr && preset.type !== 'nsite' && ( - setPresetApiKeys(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} - /> - )} - -
+ {!preset.requiresNostr && preset.type !== 'nsite' && ( + <> + {preset.type === 'cloudflare' && ( +
+ setPresetApiKeys(prev => ({ + ...prev, + [`${preset.id}-accountId`]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + presetApiKeys[`${preset.id}-accountId`]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.accountIdURL && !presetApiKeys[`${preset.id}-accountId`] && ( + + )} +
+ )} + {preset.type === 'deno' && ( +
+ setPresetApiKeys(prev => ({ + ...prev, + [`${preset.id}-organizationId`]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + presetApiKeys[`${preset.id}-organizationId`]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.organizationIdURL && !presetApiKeys[`${preset.id}-organizationId`] && ( + + )} +
+ )} +
+ setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim()) && + (preset.type !== 'deno' || presetApiKeys[`${preset.id}-organizationId`]?.trim())) { + handleAddPresetProvider(preset); + } + }} + showToggle={!!presetApiKeys[preset.id]} + /> + {preset.apiKeyURL && !presetApiKeys[preset.id] && ( + + )} +
+ + )} +
)} @@ -759,11 +978,14 @@ export function DeploySettings() {
@@ -847,9 +1071,38 @@ export function DeploySettings() { ) : ( <> + {customProviderType === 'cloudflare' && ( +
+ + setCustomAccountId(e.target.value)} + /> +
+ )} + {customProviderType === 'deno' && ( +
+ + setCustomOrganizationId(e.target.value)} + /> +
+ )}
setCustomBaseURL(e.target.value)} />
+ {(customProviderType === 'cloudflare' || customProviderType === 'deno') && ( +
+ + setCustomBaseDomain(e.target.value)} + /> +

+ {customProviderType === 'cloudflare' + ? 'The domain suffix for deployed workers (e.g., workers.dev)' + : 'The domain suffix for deployed projects (e.g., deno.dev)'} +

+
+ )} )} @@ -890,7 +1163,9 @@ export function DeploySettings() { disabled={ !customProviderType || !customName.trim() || - (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) + (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) || + (customProviderType === 'cloudflare' && !customAccountId.trim()) || + (customProviderType === 'deno' && !customOrganizationId.trim()) } className="gap-2 ml-auto" > diff --git a/src/pages/GitSettings.tsx b/src/pages/GitSettings.tsx index 4741b10e..5331fdb8 100644 --- a/src/pages/GitSettings.tsx +++ b/src/pages/GitSettings.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown, Plus, User } from 'lucide-react'; +import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown, Plus, User, ExternalLink } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -232,24 +232,13 @@ export function GitSettings() { {availablePresets.map((preset) => ( -
-
- } - /> -
{preset.name}
-
- {preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && ( - - )} +
+ } + /> +
{preset.name}
{preset.id === 'github' ? ( @@ -308,20 +297,32 @@ export function GitSettings() {
) : (
- setPresetTokens(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} - /> +
+ setPresetTokens(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { + handleAddPresetProvider(preset); + } + }} + showToggle={!!presetTokens[preset.id]} + /> + {preset.tokenURL && !presetTokens[preset.id] && ( + + )} +
+ )} +