From 46db6542aaf136c60f41239c88a20cfc78bd74f7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 19:37:36 -0600 Subject: [PATCH 01/16] Add Cloudflare deployment provider --- src/components/DeployDialog.tsx | 69 +++++- .../deploy/CloudflareDeployForm.tsx | 195 ++++++++++++++++ src/components/deploy/index.ts | 1 + src/contexts/DeploySettingsContext.ts | 10 +- src/hooks/useProjectDeploySettings.ts | 9 +- src/lib/deploy/CloudflareAdapter.ts | 220 ++++++++++++++++++ src/lib/deploy/index.ts | 1 + src/lib/deploy/types.ts | 9 + src/pages/DeploySettings.tsx | 159 +++++++++++-- 9 files changed, 643 insertions(+), 30 deletions(-) create mode 100644 src/components/deploy/CloudflareDeployForm.tsx create mode 100644 src/lib/deploy/CloudflareAdapter.ts diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index 1f78788e..c56b44ea 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -27,13 +27,14 @@ 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, 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 } 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'; /** * Helper function to get provider URL for favicon @@ -58,6 +59,12 @@ function getProviderUrl(provider: DeployProvider): string | null { } return 'https://vercel.com'; + case 'cloudflare': + if (provider.baseURL) { + return provider.baseURL; + } + return 'https://cloudflare.com'; + case 'nsite': return null; @@ -110,6 +117,10 @@ interface VercelFormData { teamId: string; } +interface CloudflareFormData { + projectName: string; +} + export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) { const { t } = useTranslation(); const { settings } = useDeploySettings(); @@ -141,6 +152,9 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectName: projectName || projectId, teamId: '', }); + const [cloudflareForm, setCloudflareForm] = useState({ + projectName: projectName || projectId, + }); // Load project settings when dialog opens useEffect(() => { @@ -230,6 +244,23 @@ 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, + projectName: cloudflareForm.projectName || undefined, + corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined, + }); } else { throw new Error('Unknown provider type'); } @@ -269,6 +300,13 @@ 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, + }, + }); } setDeployResult(result); @@ -288,6 +326,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setNsiteForm({ nsec: '' }); setNetlifyForm({ siteId: '', siteName: '' }); setVercelForm({ projectName: projectName || projectId, teamId: '' }); + setCloudflareForm({ projectName: projectName || projectId }); onOpenChange(false); }; @@ -311,6 +350,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setVercelForm({ projectName, teamId }); }, []); + const handleCloudflareProjectChange = useCallback((projectName: string) => { + setCloudflareForm({ projectName }); + }, []); + const renderProviderFields = () => { if (!selectedProvider) return null; @@ -373,6 +416,25 @@ 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 ( + + ); + } + return null; }; @@ -503,7 +565,8 @@ 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) } > {isDeploying ? ( diff --git a/src/components/deploy/CloudflareDeployForm.tsx b/src/components/deploy/CloudflareDeployForm.tsx new file mode 100644 index 00000000..952b4c6a --- /dev/null +++ b/src/components/deploy/CloudflareDeployForm.tsx @@ -0,0 +1,195 @@ +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 CloudflareProject { + id: string; + name: string; + subdomain: string; + domains: string[]; + production_branch: string; + created_on: string; +} + +interface CloudflareDeployFormProps { + apiKey: string; + accountId: string; + baseURL?: 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', + projectId, + projectName, + savedProjectName, + onProjectChange, + corsProxy, +}: CloudflareDeployFormProps) { + 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}/accounts/${accountId}/pages/projects`; + 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 = await response.json(); + setProjects(data.result || []); + + // If there's a saved project name and it exists in the list, select it + // Otherwise leave it empty (showing placeholder) + if (savedProjectName && data.result?.some((p: CloudflareProject) => p.name === savedProjectName)) { + setSelectedProjectName(savedProjectName); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch projects'); + } finally { + setIsLoading(false); + } + }, [apiKey, accountId, 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); + + return ( +
+ {error && ( + + {error} + + )} + +
+ + +
+ + {selectedProjectName === 'new' ? ( +
+ + setNewProjectName(e.target.value)} + placeholder={projectName || projectId} + /> +

+ Domain: {newProjectName || projectId}.pages.dev +

+

+ A new project will be created when you deploy +

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

{selectedProject.name}

+

+ https://{selectedProject.subdomain}.pages.dev +

+
+ +
+
+

+ Deployment will update this existing project +

+
+ ) : null} +
+ ); +} diff --git a/src/components/deploy/index.ts b/src/components/deploy/index.ts index 2333aa0c..98b40d1e 100644 --- a/src/components/deploy/index.ts +++ b/src/components/deploy/index.ts @@ -2,3 +2,4 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm'; export { NetlifyDeployForm } from './NetlifyDeployForm'; export { VercelDeployForm } from './VercelDeployForm'; export { NsiteDeployForm } from './NsiteDeployForm'; +export { CloudflareDeployForm } from './CloudflareDeployForm'; diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index d52a5e42..3699d70c 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -32,7 +32,15 @@ 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; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index 47e049c7..cbadfd5c 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -31,7 +31,14 @@ export interface VercelProjectConfig { }; } -export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig; +export interface CloudflareProjectConfig { + type: 'cloudflare'; + data: { + projectName?: string; + }; +} + +export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig; export interface ProjectDeploySettings { providers: Record; diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts new file mode 100644 index 00000000..9a0aedfe --- /dev/null +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -0,0 +1,220 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface CloudflareProject { + id: string; + name: string; + subdomain: string; + domains: string[]; + production_branch: string; +} + +interface CloudflareDeployment { + id: string; + url: string; + environment: string; + deployment_trigger: { + type: string; + }; + latest_stage: { + name: string; + status: string; + }; +} + +/** + * Cloudflare Pages Deploy Adapter + * Uses Cloudflare API with API token + */ +export class CloudflareAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private accountId: string; + private baseURL: 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.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 activeProjectName = this.projectName || projectId; + + // Get or create project + let project: CloudflareProject; + try { + project = await this.getProject(activeProjectName); + } catch { + // Project doesn't exist, create it + project = await this.createProject(activeProjectName); + } + + // Create FormData for deployment + const formData = new FormData(); + + // Collect all files from dist directory + await this.addFilesToFormData(distPath, '', formData); + + // Deploy to Cloudflare Pages + const deployment = await this.createDeployment(project.name, formData); + + // Construct the production URL + const productionUrl = `https://${project.subdomain}.pages.dev`; + + return { + url: productionUrl, + metadata: { + deploymentId: deployment.id, + projectId: project.id, + projectName: project.name, + provider: 'cloudflare', + environment: deployment.environment, + }, + }; + } + + private async getProject(projectName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${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) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to get Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async createProject(projectName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/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, + production_branch: 'main', + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async createDeployment(projectName: string, formData: FormData): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}/deployments`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create Cloudflare deployment: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async addFilesToFormData( + dirPath: string, + relativePath: string, + formData: FormData + ): 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()) { + // Recursively add files from subdirectories + await this.addFilesToFormData(fullPath, entryRelativePath, formData); + } else if (entry.isFile()) { + try { + // Read file content + const fileContent = await this.fs.readFile(fullPath); + + // Convert to Blob for FormData + let blob: Blob; + if (typeof fileContent === 'string') { + blob = new Blob([fileContent], { type: this.getMimeType(entry.name) }); + } else { + // Handle Uint8Array + blob = new Blob([fileContent], { type: this.getMimeType(entry.name) }); + } + + // Add to FormData with the relative path as the field name + formData.append(entryRelativePath, blob, entry.name); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private getMimeType(filename: string): string { + const ext = filename.split('.').pop()?.toLowerCase(); + const mimeTypes: Record = { + 'html': 'text/html', + 'css': 'text/css', + 'js': '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', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'ttf': 'font/ttf', + 'eot': 'application/vnd.ms-fontobject', + }; + return mimeTypes[ext || ''] || 'application/octet-stream'; + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 830bff96..5832fa94 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -3,3 +3,4 @@ export * from './ShakespeareAdapter'; export * from './NetlifyAdapter'; export * from './VercelAdapter'; export * from './NsiteAdapter'; +export * from './CloudflareAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 5adf4eeb..63a52fa5 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -54,3 +54,12 @@ export interface NsiteDeployConfig { relayUrls: string[]; blossomServers: string[]; } + +export interface CloudflareDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + accountId: string; + baseURL?: string; + projectName?: string; + corsProxy?: string; +} diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 9c88bff9..bd970c34 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -46,12 +46,14 @@ import { normalizeUrl } from '@/lib/faviconUrl'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare'; name: string; description: string; requiresNostr?: boolean; apiKeyLabel?: string; apiKeyURL?: string; + accountIdLabel?: string; + accountIdURL?: string; proxy?: boolean; } @@ -200,23 +202,45 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho onUpdate(index, { ...provider, apiKey: e.target.value }); } else if (provider.type === 'vercel') { onUpdate(index, { ...provider, apiKey: e.target.value }); + } else if (provider.type === 'cloudflare') { + onUpdate(index, { ...provider, apiKey: e.target.value }); } }} /> + {provider.type === 'cloudflare' && ( +
+ + onUpdate(index, { ...provider, accountId: e.target.value })} + /> +
+ )}
{ if (provider.type === 'netlify') { onUpdate(index, { ...provider, baseURL: e.target.value }); } else if (provider.type === 'vercel') { onUpdate(index, { ...provider, baseURL: e.target.value }); + } else if (provider.type === 'cloudflare') { + onUpdate(index, { ...provider, baseURL: e.target.value }); } }} /> @@ -282,6 +306,17 @@ const PRESET_PROVIDERS: PresetProvider[] = [ apiKeyURL: 'https://vercel.com/account/tokens', proxy: true, }, + { + id: 'cloudflare', + type: 'cloudflare', + name: 'Cloudflare Pages', + description: 'Deploy to Cloudflare Pages', + apiKeyLabel: 'API Token', + apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens', + accountIdLabel: 'Account ID', + accountIdURL: 'https://dash.cloudflare.com/', + proxy: true, + }, ]; // Helper function to generate custom provider ID @@ -314,6 +349,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul } return 'https://vercel.com'; + case 'cloudflare': + // For Cloudflare providers, check for custom baseURL first, then use default + if ('baseURL' in provider && provider.baseURL) { + return provider.baseURL; + } + return 'https://cloudflare.com'; + case 'nsite': // nsite uses Rocket icon fallback return null; @@ -338,9 +380,10 @@ export function DeploySettings() { const [forceManualEntry, setForceManualEntry] = useState>({}); // Custom provider form state - const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>(''); + const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | ''>(''); const [customName, setCustomName] = useState(''); const [customApiKey, setCustomApiKey] = useState(''); + const [customAccountId, setCustomAccountId] = useState(''); const [customBaseURL, setCustomBaseURL] = useState(''); const [customHost, setCustomHost] = useState(''); const [customProxy, setCustomProxy] = useState(false); @@ -416,7 +459,7 @@ export function DeploySettings() { apiKey: apiKey.trim(), ...(preset.proxy && { proxy: true }), }; - } else { + } else if (preset.type === 'vercel') { newProvider = { id: preset.id, // Use preset ID for presets name: preset.name, @@ -424,6 +467,21 @@ export function DeploySettings() { apiKey: apiKey.trim(), ...(preset.proxy && { proxy: true }), }; + } else if (preset.type === 'cloudflare') { + const accountId = presetApiKeys[`${preset.id}-accountId`]; + if (!accountId?.trim()) { + return; + } + newProvider = { + id: preset.id, // Use preset ID for presets + name: preset.name, + type: 'cloudflare', + apiKey: apiKey.trim(), + accountId: accountId.trim(), + ...(preset.proxy && { proxy: true }), + }; + } else { + return; // Unknown type } setProviders([...settings.providers, newProvider]); @@ -472,7 +530,7 @@ export function DeploySettings() { ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), ...(customProxy && { proxy: true }), }; - } else { + } else if (customProviderType === 'vercel') { if (!customApiKey.trim()) return; newProvider = { id: generateCustomProviderId(customProviderType), // Generate custom ID @@ -482,6 +540,19 @@ export function DeploySettings() { ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), ...(customProxy && { proxy: true }), }; + } else if (customProviderType === 'cloudflare') { + if (!customApiKey.trim() || !customAccountId.trim()) return; + newProvider = { + id: generateCustomProviderId(customProviderType), // Generate custom ID + name: customName.trim(), + type: 'cloudflare', + apiKey: customApiKey.trim(), + accountId: customAccountId.trim(), + ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), + ...(customProxy && { proxy: true }), + }; + } else { + return; // Unknown type } setProviders([...settings.providers, newProvider]); @@ -490,6 +561,7 @@ export function DeploySettings() { setCustomProviderType(''); setCustomName(''); setCustomApiKey(''); + setCustomAccountId(''); setCustomBaseURL(''); setCustomHost(''); setCustomProxy(false); @@ -703,34 +775,51 @@ export function DeploySettings() { ) : ( // Show manual token input
-
- {!preset.requiresNostr && preset.type !== 'nsite' && ( + {!preset.requiresNostr && preset.type !== 'nsite' && ( + <> setPresetApiKeys(prev => ({ ...prev, [preset.id]: e.target.value, }))} onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { handleAddPresetProvider(preset); } }} /> - )} - -
+ {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); + } + }} + /> + )} + + )} +
)} @@ -759,10 +848,11 @@ export function DeploySettings() {
@@ -849,7 +940,9 @@ export function DeploySettings() { <>
setCustomApiKey(e.target.value)} />
+ {customProviderType === 'cloudflare' && ( +
+ + setCustomAccountId(e.target.value)} + /> +
+ )}
setCustomBaseURL(e.target.value)} @@ -890,7 +998,8 @@ export function DeploySettings() { disabled={ !customProviderType || !customName.trim() || - (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) + (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) || + (customProviderType === 'cloudflare' && !customAccountId.trim()) } className="gap-2 ml-auto" > From b345145ad31d5efaa43a68faa2ced5ce511e5a6b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 20:02:50 -0600 Subject: [PATCH 02/16] Improve design of "Get Key" inputs --- src/pages/DeploySettings.tsx | 105 ++++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 46 deletions(-) diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index bd970c34..c7e7c604 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus } from 'lucide-react'; +import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus, ExternalLink } from 'lucide-react'; import { Checkbox } from '@/components/ui/checkbox'; import { DropdownMenu, @@ -673,31 +673,20 @@ export function DeploySettings() { return ( -
-
- {(() => { - const url = getProviderUrl(preset); - return url ? ( - } - /> - ) : ( - - ); - })()} -
{preset.name}
-
- {preset.apiKeyURL && !isOAuthConfigured && ( - - )} +
+ {(() => { + const url = getProviderUrl(preset); + return url ? ( + } + /> + ) : ( + + ); + })()} +
{preset.name}

{preset.description}

@@ -777,35 +766,59 @@ export function DeploySettings() {
{!preset.requiresNostr && preset.type !== 'nsite' && ( <> - 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())) { - handleAddPresetProvider(preset); - } - }} - /> - {preset.type === 'cloudflare' && ( - + setPresetApiKeys(prev => ({ ...prev, - [`${preset.id}-accountId`]: e.target.value, + [preset.id]: e.target.value, }))} onKeyDown={(e) => { if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && - presetApiKeys[`${preset.id}-accountId`]?.trim()) { + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { handleAddPresetProvider(preset); } }} /> + {preset.apiKeyURL && !presetApiKeys[preset.id] && ( + + )} +
+ {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`] && ( + + )} +
)} )} From fef40abcae40ddab1880469820808093f4693bef Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 20:09:47 -0600 Subject: [PATCH 03/16] Improve input external link hover style --- src/pages/DeploySettings.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index c7e7c604..a4bf53a2 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -784,7 +784,7 @@ export function DeploySettings() { {preset.apiKeyURL && !presetApiKeys[preset.id] && ( - )} -
{preset.type === 'cloudflare' && (
)} +
+ 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())) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.apiKeyURL && !presetApiKeys[preset.id] && ( + + )} +
)}

- Deployment will update this existing project + Deployment will update this existing worker

) : null} diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts index aa16a6ef..944fa06f 100644 --- a/src/lib/deploy/CloudflareAdapter.ts +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -2,30 +2,44 @@ import type { JSRuntimeFS } from '../JSRuntime'; import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types'; import { proxyUrl } from '../proxyUrl'; -interface CloudflareProject { - id: string; - name: string; - subdomain: string; - domains: string[]; - production_branch: string; +interface AssetManifest { + [path: string]: { hash: string; size: number }; } -interface CloudflareDeployment { +interface InitializeAssetsResponse { + buckets: string[][]; + jwt: string; +} + +interface UploadResponse { + jwt?: string; +} + +interface WorkerScript { id: string; - url: string; - environment: string; - deployment_trigger: { - type: string; - }; - latest_stage: { - name: string; - status: 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 Pages Deploy Adapter - * Uses Cloudflare API with API token + * 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; @@ -55,47 +69,74 @@ export class CloudflareAdapter implements DeployAdapter { throw new Error('No index.html found in dist directory. Please build the project first.'); } - const activeProjectName = this.projectName || projectId; + const scriptName = this.projectName || projectId; - // Get or create project - let project: CloudflareProject; - try { - project = await this.getProject(activeProjectName); - } catch { - // Project doesn't exist, create it - project = await this.createProject(activeProjectName); + // 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, + }; } - // Collect all files and create manifest - const files: Record = {}; - const fileContents: Record = {}; - await this.collectFiles(distPath, '', files, fileContents); + // Step 2: Initialize upload session + const initResponse = await this.initializeUploadSession(scriptName, manifest); - // Deploy to Cloudflare Pages using Direct Upload - const deployment = await this.createDeployment(project.name, files, fileContents); + // Step 3: Upload files in buckets + let completionJwt = initResponse.jwt; - // Construct the production URL - // The subdomain from the API response already includes the full domain - // e.g., "error-button.pages.dev" not just "error-button" - const productionUrl = project.subdomain.includes('.') - ? `https://${project.subdomain}` - : `https://${project.subdomain}.pages.dev`; + 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 each bucket + for (const bucket of initResponse.buckets) { + const uploadResult = await this.uploadBucket( + initResponse.jwt, + bucket, + hashToFile + ); + if (uploadResult.jwt) { + completionJwt = uploadResult.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.dev subdomain + const subdomain = await this.getWorkersSubdomain(); + + // Construct the URL + const workerUrl = `https://${scriptName}.${subdomain}.workers.dev`; return { - url: deployment.url, + url: workerUrl, metadata: { - deploymentId: deployment.id, - projectId: project.id, - projectName: project.name, - productionUrl, - provider: 'cloudflare', - environment: deployment.environment, + scriptId: deployment.id, + scriptName: scriptName, + provider: 'cloudflare-workers', + hasAssets: deployment.has_assets, + modifiedOn: deployment.modified_on, }, }; } - private async getProject(projectName: string): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}`; + 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, { @@ -107,19 +148,15 @@ export class CloudflareAdapter implements DeployAdapter { if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to get Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`); } const data = await response.json(); - - // Log the project response for debugging - console.log('Cloudflare project response:', data); - - return data.result; + return data.result.subdomain; } - private async createProject(projectName: string): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects`; + 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, { @@ -129,40 +166,125 @@ export class CloudflareAdapter implements DeployAdapter { 'Content-Type': 'application/json', }, body: JSON.stringify({ - name: projectName, - production_branch: 'main', + enabled: true, + previews_enabled: true, }), }); if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to create Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + 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 createDeployment( - projectName: string, - manifest: Record, - fileContents: Record - ): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}/deployments`; + 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; - // Create FormData with manifest const formData = new FormData(); - formData.append('manifest', JSON.stringify(manifest)); - // Add all files to FormData - for (const [path, content] of Object.entries(fileContents)) { - const blob = new Blob([content]); - formData.append(path, blob, path); + 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}`, }, @@ -171,22 +293,17 @@ export class CloudflareAdapter implements DeployAdapter { if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to create Cloudflare deployment: ${response.status} ${response.statusText}. ${errorText}`); + throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`); } const data = await response.json(); - - // Log the response for debugging - console.log('Cloudflare deployment response:', data); - return data.result; } private async collectFiles( dirPath: string, relativePath: string, - manifest: Record, - fileContents: Record + files: Map ): Promise { try { const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); @@ -196,11 +313,9 @@ export class CloudflareAdapter implements DeployAdapter { const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name; if (entry.isDirectory()) { - // Recursively collect files from subdirectories - await this.collectFiles(fullPath, entryRelativePath, manifest, fileContents); + await this.collectFiles(fullPath, entryRelativePath, files); } else if (entry.isFile()) { try { - // Read file content const fileContent = await this.fs.readFile(fullPath); // Convert to Uint8Array @@ -211,15 +326,18 @@ export class CloudflareAdapter implements DeployAdapter { content = fileContent; } - // Calculate hash for manifest + // Calculate hash (same algorithm as Wrangler uses) const hash = await this.calculateHash(content); - // Add to manifest with leading slash - const manifestPath = `/${entryRelativePath}`; - manifest[manifestPath] = hash; + // Determine content type + const contentType = this.getContentType(entry.name); - // Store file content - fileContents[entryRelativePath] = content; + files.set(entryRelativePath, { + hash, + content, + size: content.length, + contentType, + }); } catch (error) { console.warn(`Failed to read file ${fullPath}:`, error); } @@ -231,10 +349,55 @@ export class CloudflareAdapter implements DeployAdapter { } private async calculateHash(content: Uint8Array): Promise { - // Use SHA-256 to calculate hash + // 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)); - const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + // 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/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index b0aaef05..03401809 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -309,8 +309,8 @@ const PRESET_PROVIDERS: PresetProvider[] = [ { id: 'cloudflare', type: 'cloudflare', - name: 'Cloudflare Pages', - description: 'Deploy to Cloudflare Pages', + name: 'Cloudflare', + description: 'Deploy to Cloudflare Workers', apiKeyLabel: 'API Token', apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens', accountIdLabel: 'Account ID', @@ -882,7 +882,7 @@ export function DeploySettings() { nsite Netlify Vercel - Cloudflare Pages + Cloudflare From 74b5f60df83c490f2cf03123793b53dbb5df07e3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 23:02:50 -0600 Subject: [PATCH 10/16] Improve Get Key inputs --- src/components/ui/password-input.tsx | 40 +++++++++++++++++----------- src/pages/DeploySettings.tsx | 3 ++- 2 files changed, 26 insertions(+), 17 deletions(-) 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/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 03401809..5329eaa1 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -808,11 +808,12 @@ export function DeploySettings() { handleAddPresetProvider(preset); } }} + showToggle={!!presetApiKeys[preset.id]} /> {preset.apiKeyURL && !presetApiKeys[preset.id] && ( - )} +
+ } + /> +
{preset.name}
{showNostrLoginRequired ? ( @@ -458,22 +447,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] && ( + + )} +
)} - )} +
+ } + /> +
{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] && ( + + )} +
+ )} +
+
+ +

+ 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 98b40d1e..e0626373 100644 --- a/src/components/deploy/index.ts +++ b/src/components/deploy/index.ts @@ -3,3 +3,4 @@ export { NetlifyDeployForm } from './NetlifyDeployForm'; export { VercelDeployForm } from './VercelDeployForm'; export { NsiteDeployForm } from './NsiteDeployForm'; export { CloudflareDeployForm } from './CloudflareDeployForm'; +export { DenoDeployForm } from './DenoDeployForm'; diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 3699d70c..5fc0b0e5 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -40,7 +40,15 @@ export interface CloudflareProvider extends BaseDeployProvider { proxy?: boolean; } -export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider; +export interface DenoDeployProvider extends BaseDeployProvider { + type: 'deno'; + apiKey: string; + organizationId: string; + baseURL?: 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 cbadfd5c..467bd3a9 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -38,7 +38,14 @@ export interface CloudflareProjectConfig { }; } -export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig; +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/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts new file mode 100644 index 00000000..8fa61f5c --- /dev/null +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -0,0 +1,304 @@ +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 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.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 + const deployment = await this.createDeployment(project.id, assets); + + // Step 4: Attach the deno.dev domain to the deployment + const domain = `${project.name}.deno.dev`; + await this.attachDomain(deployment.id, `{project.name}.deno.dev`); + + 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 + ): 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 = 'file:///src/main.ts'; + + // Add the entry point script that serves static files + const serverScript = ` +import { serveDir } from "https://deno.land/std@0.208.0/http/file_server.ts"; + +Deno.serve((req) => { + return serveDir(req, { + fsRoot: ".", + showIndex: true, + enableCors: true, + }); +}); +`; + + // Add the server script to assets + assets['src/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: {}, + }), + }); + + 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 attachDomain(deploymentId: string, domain: string): Promise { + const url = `${this.baseURL}/deployments/${deploymentId}/domains/${encodeURIComponent(domain)}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'PUT', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + // Don't throw on domain attachment failure - deployment still succeeded + console.warn(`Failed to attach domain: ${response.status} ${response.statusText}. ${errorText}`); + } + } + + 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 5832fa94..24bf4795 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -4,3 +4,4 @@ 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 63a52fa5..f7f2d1ea 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -63,3 +63,12 @@ export interface CloudflareDeployConfig { projectName?: string; corsProxy?: string; } + +export interface DenoDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + organizationId: string; + baseURL?: string; + projectName?: string; + corsProxy?: string; +} diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 5329eaa1..15bbddf9 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -46,7 +46,7 @@ import { normalizeUrl } from '@/lib/faviconUrl'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; name: string; description: string; requiresNostr?: boolean; @@ -54,6 +54,8 @@ interface PresetProvider { apiKeyURL?: string; accountIdLabel?: string; accountIdURL?: string; + organizationIdLabel?: string; + organizationIdURL?: string; proxy?: boolean; } @@ -202,6 +204,19 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho /> )} + {provider.type === 'deno' && ( +
+ + onUpdate(index, { ...provider, organizationId: e.target.value })} + /> +
+ )}
)} + {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`] && ( + + )} +
+ )}
{ if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && - (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim()) && + (preset.type !== 'deno' || presetApiKeys[`${preset.id}-organizationId`]?.trim())) { handleAddPresetProvider(preset); } }} @@ -828,7 +921,8 @@ export function DeploySettings() { disabled={ (preset.requiresNostr && !isLoggedIntoNostr) || (!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim()) || - (preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) + (preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) || + (preset.type === 'deno' && !presetApiKeys[`${preset.id}-organizationId`]?.trim()) } className="w-full" > @@ -862,11 +956,12 @@ export function DeploySettings() {
@@ -965,11 +1061,25 @@ export function DeploySettings() { /> )} + {customProviderType === 'deno' && ( +
+ + setCustomOrganizationId(e.target.value)} + /> +
+ )}
setCustomBaseURL(e.target.value)} @@ -1013,7 +1125,8 @@ export function DeploySettings() { !customProviderType || !customName.trim() || (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) || - (customProviderType === 'cloudflare' && !customAccountId.trim()) + (customProviderType === 'cloudflare' && !customAccountId.trim()) || + (customProviderType === 'deno' && !customOrganizationId.trim()) } className="gap-2 ml-auto" > From 5685c6f52f3042aacd38b429dd5f49e133655ad0 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 23:57:01 -0600 Subject: [PATCH 14/16] Fix Deno config in configUtils --- src/lib/configUtils.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 5b4975fc..62ab4799 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -113,12 +113,20 @@ const cloudflareProviderSchema = baseDeployProviderSchema.extend({ baseURL: z.string().optional(), }); +const denoDeployProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('deno'), + apiKey: z.string(), + organizationId: z.string(), + baseURL: z.string().optional(), +}); + const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ shakespeareDeployProviderSchema, netlifyProviderSchema, vercelProviderSchema, nsiteProviderSchema, cloudflareProviderSchema, + denoDeployProviderSchema, ]); const deploySettingsSchema = z.object({ From bbb4a2534bbde63ba5e22616a47a85170e76f7be Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 00:02:50 -0600 Subject: [PATCH 15/16] Fix Deno Deploy so it works --- src/lib/deploy/DenoDeployAdapter.ts | 37 +++++++---------------------- 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts index 8fa61f5c..57f7665c 100644 --- a/src/lib/deploy/DenoDeployAdapter.ts +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -65,12 +65,9 @@ export class DenoDeployAdapter implements DeployAdapter { const assets: Record = {}; await this.collectFiles(distPath, '', assets); - // Step 3: Create deployment with assets - const deployment = await this.createDeployment(project.id, assets); - - // Step 4: Attach the deno.dev domain to the deployment + // Step 3: Create deployment with assets and domain const domain = `${project.name}.deno.dev`; - await this.attachDomain(deployment.id, `{project.name}.deno.dev`); + const deployment = await this.createDeployment(project.id, assets, domain); return { url: `https://${domain}`, @@ -140,18 +137,19 @@ export class DenoDeployAdapter implements DeployAdapter { private async createDeployment( projectId: string, - assets: Record + 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 = 'file:///src/main.ts'; + const entryPointUrl = 'main.ts'; // Add the entry point script that serves static files const serverScript = ` -import { serveDir } from "https://deno.land/std@0.208.0/http/file_server.ts"; +import { serveDir } from "jsr:@std/http/file-server"; Deno.serve((req) => { return serveDir(req, { @@ -163,7 +161,7 @@ Deno.serve((req) => { `; // Add the server script to assets - assets['src/main.ts'] = { + assets['main.ts'] = { kind: 'file', content: serverScript, encoding: 'utf-8', @@ -182,6 +180,8 @@ Deno.serve((req) => { lockFileUrl: null, compilerOptions: null, envVars: {}, + // Attach domain during deployment creation instead of separately + domains: [domain], }), }); @@ -193,25 +193,6 @@ Deno.serve((req) => { return response.json(); } - private async attachDomain(deploymentId: string, domain: string): Promise { - const url = `${this.baseURL}/deployments/${deploymentId}/domains/${encodeURIComponent(domain)}`; - const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; - - const response = await fetch(targetUrl, { - method: 'PUT', - headers: { - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - const errorText = await response.text().catch(() => 'Unknown error'); - // Don't throw on domain attachment failure - deployment still succeeded - console.warn(`Failed to attach domain: ${response.status} ${response.statusText}. ${errorText}`); - } - } - private async collectFiles( dirPath: string, relativePath: string, From 2096c83b3cbc163e8b101a16ff0a8fa0c64b2ef3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 00:17:11 -0600 Subject: [PATCH 16/16] Let baseDomain be configured for Cloudflare and Deno Deploy --- src/components/DeployDialog.tsx | 4 ++ .../deploy/CloudflareDeployForm.tsx | 6 ++- src/components/deploy/DenoDeployForm.tsx | 4 +- src/contexts/DeploySettingsContext.ts | 2 + src/lib/configUtils.ts | 2 + src/lib/deploy/CloudflareAdapter.ts | 8 ++-- src/lib/deploy/DenoDeployAdapter.ts | 4 +- src/lib/deploy/types.ts | 2 + src/pages/DeploySettings.tsx | 39 +++++++++++++++++++ 9 files changed, 64 insertions(+), 7 deletions(-) diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index e34d8399..8c8dbd88 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -272,6 +272,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey: cloudflareProvider.apiKey, accountId: cloudflareProvider.accountId, baseURL: cloudflareProvider.baseURL, + baseDomain: cloudflareProvider.baseDomain, projectName: cloudflareForm.projectName || undefined, corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined, }); @@ -288,6 +289,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep fs, apiKey: denoProvider.apiKey, organizationId: denoProvider.organizationId, + baseDomain: denoProvider.baseDomain, baseURL: denoProvider.baseURL, projectName: denoDeployForm.projectName || undefined, corsProxy: denoProvider.proxy ? config.corsProxy : undefined, @@ -469,6 +471,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey={cloudflareProvider.apiKey} accountId={cloudflareProvider.accountId} baseURL={cloudflareProvider.baseURL} + baseDomain={cloudflareProvider.baseDomain} projectId={projectId} projectName={projectName} savedProjectName={savedProjectName} @@ -488,6 +491,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey={denoProvider.apiKey} organizationId={denoProvider.organizationId} baseURL={denoProvider.baseURL} + baseDomain={denoProvider.baseDomain} projectId={projectId} projectName={projectName} savedProjectName={savedProjectName} diff --git a/src/components/deploy/CloudflareDeployForm.tsx b/src/components/deploy/CloudflareDeployForm.tsx index 99d0f8b3..0acb061b 100644 --- a/src/components/deploy/CloudflareDeployForm.tsx +++ b/src/components/deploy/CloudflareDeployForm.tsx @@ -27,6 +27,7 @@ interface CloudflareDeployFormProps { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; projectId: string; projectName?: string; savedProjectName?: string; @@ -38,6 +39,7 @@ export function CloudflareDeployForm({ apiKey, accountId, baseURL = 'https://api.cloudflare.com/client/v4', + baseDomain = 'workers.dev', projectId, projectName, savedProjectName, @@ -136,9 +138,9 @@ export function CloudflareDeployForm({ // Construct the URL preview const getWorkerUrl = (scriptName: string) => { if (workersSubdomain) { - return `https://${scriptName}.${workersSubdomain}.workers.dev`; + return `https://${scriptName}.${workersSubdomain}.${baseDomain}`; } - return `https://${scriptName}..workers.dev`; + return `https://${scriptName}..${baseDomain}`; }; return ( diff --git a/src/components/deploy/DenoDeployForm.tsx b/src/components/deploy/DenoDeployForm.tsx index 152dcd23..961d2726 100644 --- a/src/components/deploy/DenoDeployForm.tsx +++ b/src/components/deploy/DenoDeployForm.tsx @@ -25,6 +25,7 @@ interface DenoDeployFormProps { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; projectId: string; projectName?: string; savedProjectName?: string; @@ -36,6 +37,7 @@ export function DenoDeployForm({ apiKey, organizationId, baseURL = 'https://api.deno.com/v1', + baseDomain = 'deno.dev', projectId, projectName, savedProjectName, @@ -117,7 +119,7 @@ export function DenoDeployForm({ // Construct the URL preview const getProjectUrl = (name: string) => { - return `https://${name}.deno.dev`; + return `https://${name}.${baseDomain}`; }; return ( diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 5fc0b0e5..09abe69a 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -37,6 +37,7 @@ export interface CloudflareProvider extends BaseDeployProvider { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; proxy?: boolean; } @@ -45,6 +46,7 @@ export interface DenoDeployProvider extends BaseDeployProvider { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; proxy?: boolean; } diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 62ab4799..1a2a8f3b 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -111,6 +111,7 @@ const cloudflareProviderSchema = baseDeployProviderSchema.extend({ apiKey: z.string(), accountId: z.string(), baseURL: z.string().optional(), + baseDomain: z.string().optional(), }); const denoDeployProviderSchema = baseDeployProviderSchema.extend({ @@ -118,6 +119,7 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({ apiKey: z.string(), organizationId: z.string(), baseURL: z.string().optional(), + baseDomain: z.string().optional(), }); const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts index 8157ff17..5db367c2 100644 --- a/src/lib/deploy/CloudflareAdapter.ts +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -46,6 +46,7 @@ export class CloudflareAdapter implements DeployAdapter { private apiKey: string; private accountId: string; private baseURL: string; + private baseDomain: string; private projectName?: string; private corsProxy?: string; @@ -54,6 +55,7 @@ export class CloudflareAdapter implements DeployAdapter { 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; } @@ -118,11 +120,11 @@ export class CloudflareAdapter implements DeployAdapter { // Step 5: Enable the workers.dev subdomain for this script await this.enableWorkersDevSubdomain(scriptName); - // Step 6: Get the account's workers.dev subdomain + // Step 6: Get the account's workers subdomain const subdomain = await this.getWorkersSubdomain(); - // Construct the URL - const workerUrl = `https://${scriptName}.${subdomain}.workers.dev`; + // Construct the URL using the configurable base domain + const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`; return { url: workerUrl, diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts index 57f7665c..041b0aa6 100644 --- a/src/lib/deploy/DenoDeployAdapter.ts +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -33,6 +33,7 @@ export class DenoDeployAdapter implements DeployAdapter { private apiKey: string; private organizationId: string; private baseURL: string; + private baseDomain: string; private projectName?: string; private corsProxy?: string; @@ -41,6 +42,7 @@ export class DenoDeployAdapter implements DeployAdapter { 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; } @@ -66,7 +68,7 @@ export class DenoDeployAdapter implements DeployAdapter { await this.collectFiles(distPath, '', assets); // Step 3: Create deployment with assets and domain - const domain = `${project.name}.deno.dev`; + const domain = `${project.name}.${this.baseDomain}`; const deployment = await this.createDeployment(project.id, assets, domain); return { diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index f7f2d1ea..60222a5d 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -60,6 +60,7 @@ export interface CloudflareDeployConfig { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; projectName?: string; corsProxy?: string; } @@ -69,6 +70,7 @@ export interface DenoDeployConfig { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; projectName?: string; corsProxy?: string; } diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 15bbddf9..1caffd50 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -265,6 +265,24 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho }} />
+ {(provider.type === 'cloudflare' || provider.type === 'deno') && ( +
+ + onUpdate(index, { ...provider, baseDomain: e.target.value })} + /> +

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

+
+ )}
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)'} +

+
+ )} )}