mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Merge remote-tracking branch 'origin/main' into global-chat
This commit is contained in:
17 files changed
+1786
-168
No files matched your search
+2
-2
@@ -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;
|
||||
|
||||
@@ -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<CloudflareFormData>({
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
||||
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 (
|
||||
<CloudflareDeployForm
|
||||
apiKey={cloudflareProvider.apiKey}
|
||||
accountId={cloudflareProvider.accountId}
|
||||
baseURL={cloudflareProvider.baseURL}
|
||||
baseDomain={cloudflareProvider.baseDomain}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedProjectName={savedProjectName}
|
||||
onProjectChange={handleCloudflareProjectChange}
|
||||
corsProxy={cloudflareProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider as DenoDeployProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
|
||||
|
||||
return (
|
||||
<DenoDeployForm
|
||||
apiKey={denoProvider.apiKey}
|
||||
organizationId={denoProvider.organizationId}
|
||||
baseURL={denoProvider.baseURL}
|
||||
baseDomain={denoProvider.baseDomain}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedProjectName={savedProjectName}
|
||||
onProjectChange={handleDenoDeployProjectChange}
|
||||
corsProxy={denoProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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 ? (
|
||||
|
||||
@@ -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<CloudflareWorkerScript[]>([]);
|
||||
const [workersSubdomain, setWorkersSubdomain] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Project</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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}.<subdomain>.${baseDomain}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cloudflare-project">Select Worker</Label>
|
||||
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
|
||||
<SelectTrigger id="cloudflare-project">
|
||||
<SelectValue placeholder="Select a worker or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new worker
|
||||
</div>
|
||||
</SelectItem>
|
||||
{workers.map((worker) => (
|
||||
<SelectItem key={worker.id} value={worker.id}>
|
||||
{worker.id}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProjectName === 'new' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-project-name">New Worker Name</Label>
|
||||
<Input
|
||||
id="new-project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL: <span className="font-mono">{getWorkerUrl(newProjectName || projectId)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new worker will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
) : selectedWorker ? (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedWorker.id}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{getWorkerUrl(selectedWorker.id)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`https://dash.cloudflare.com/${accountId}/workers/services/view/${selectedWorker.id}`, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deployment will update this existing worker
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<DenoProject[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Project</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedProject = projects.find(p => p.name === selectedProjectName);
|
||||
|
||||
// Construct the URL preview
|
||||
const getProjectUrl = (name: string) => {
|
||||
return `https://${name}.${baseDomain}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deno-project">Select Project</Label>
|
||||
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
|
||||
<SelectTrigger id="deno-project">
|
||||
<SelectValue placeholder="Select a project or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new project
|
||||
</div>
|
||||
</SelectItem>
|
||||
{projects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.name}>
|
||||
{project.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProjectName === 'new' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-project-name">New Project Name</Label>
|
||||
<Input
|
||||
id="new-project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL: <span className="font-mono">{getProjectUrl(newProjectName || projectId)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new project will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
) : selectedProject ? (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedProject.name}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{getProjectUrl(selectedProject.name)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`https://dash.deno.com/projects/${selectedProject.name}`, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deployment will create a new version for this project
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -2,8 +2,13 @@ import * as React from "react"
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, ...props }, ref) => {
|
||||
interface PasswordInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
/** Whether to show the visibility toggle button. Defaults to true. */
|
||||
showToggle?: boolean;
|
||||
}
|
||||
|
||||
const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
|
||||
({ 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<HTMLInputElement, React.InputHTMLAttribut
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
showToggle && "pr-10",
|
||||
isFocused && "ring-2 ring-ring ring-offset-2"
|
||||
)}
|
||||
ref={ref}
|
||||
@@ -26,19 +32,21 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={props.disabled}
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
{showToggle && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={props.disabled}
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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[];
|
||||
|
||||
@@ -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<string, ProjectProviderConfig>;
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -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<DeployProvider> = z.discriminatedUnion('type', [
|
||||
shakespeareDeployProviderSchema,
|
||||
netlifyProviderSchema,
|
||||
vercelProviderSchema,
|
||||
nsiteProviderSchema,
|
||||
cloudflareProviderSchema,
|
||||
denoDeployProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
|
||||
@@ -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<DeployResult> {
|
||||
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<string, FileInfo>();
|
||||
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<string, { path: string; info: FileInfo }>();
|
||||
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<string> {
|
||||
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<void> {
|
||||
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<InitializeAssetsResponse> {
|
||||
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<string, { path: string; info: FileInfo }>
|
||||
): Promise<UploadResponse> {
|
||||
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<WorkerScript> {
|
||||
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<string, FileInfo>
|
||||
): Promise<void> {
|
||||
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<string> {
|
||||
// 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<string, string> = {
|
||||
'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';
|
||||
}
|
||||
}
|
||||
@@ -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<DeployResult> {
|
||||
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<string, { kind: string; content: string; encoding: string }> = {};
|
||||
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<Project> {
|
||||
// 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<Project | null> {
|
||||
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<Project> {
|
||||
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<string, { kind: string; content: string; encoding: string }>,
|
||||
domain: string
|
||||
): Promise<Deployment> {
|
||||
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<string, { kind: string; content: string; encoding: string }>
|
||||
): Promise<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,5 @@ export * from './ShakespeareAdapter';
|
||||
export * from './NetlifyAdapter';
|
||||
export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
export * from './CloudflareAdapter';
|
||||
export * from './DenoDeployAdapter';
|
||||
@@ -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;
|
||||
}
|
||||
+36
-35
@@ -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 (
|
||||
<Card key={preset.id}>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
{(preset.apiKeysURL && preset.id !== "routstr") && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
onClick={() => window.open(preset.apiKeysURL, '_blank')}
|
||||
>
|
||||
{t('getApiKey')}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
|
||||
{showNostrLoginRequired ? (
|
||||
@@ -475,22 +464,34 @@ export function AISettings() {
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.nostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' &&
|
||||
presetApiKeys[preset.id]?.trim() &&
|
||||
presetTermsAgreements[preset.id]) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="relative flex-1">
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => 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] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.apiKeysURL, '_blank')}
|
||||
>
|
||||
Get Key
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
|
||||
+338
-63
@@ -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,
|
||||
@@ -46,12 +46,16 @@ import { normalizeUrl } from '@/lib/faviconUrl';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
|
||||
name: string;
|
||||
description: string;
|
||||
requiresNostr?: boolean;
|
||||
apiKeyLabel?: string;
|
||||
apiKeyURL?: string;
|
||||
accountIdLabel?: string;
|
||||
accountIdURL?: string;
|
||||
organizationIdLabel?: string;
|
||||
organizationIdURL?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
@@ -187,6 +191,32 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{provider.type === 'cloudflare' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-accountId`}>
|
||||
{preset?.accountIdLabel || 'Account ID'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`provider-${index}-accountId`}
|
||||
placeholder="Enter Account ID"
|
||||
value={provider.accountId}
|
||||
onChange={(e) => onUpdate(index, { ...provider, accountId: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{provider.type === 'deno' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-organizationId`}>
|
||||
{preset?.organizationIdLabel || 'Organization ID'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`provider-${index}-organizationId`}
|
||||
placeholder="Enter Organization ID"
|
||||
value={provider.organizationId}
|
||||
onChange={(e) => onUpdate(index, { ...provider, organizationId: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-apiKey`}>
|
||||
{preset?.apiKeyLabel || t('apiKey')} <span className="text-destructive">*</span>
|
||||
@@ -200,6 +230,10 @@ 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 });
|
||||
} else if (provider.type === 'deno') {
|
||||
onUpdate(index, { ...provider, apiKey: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -210,17 +244,45 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
|
||||
</Label>
|
||||
<Input
|
||||
id={`provider-${index}-baseURL`}
|
||||
placeholder={provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' : 'https://api.vercel.com'}
|
||||
placeholder={
|
||||
provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' :
|
||||
provider.type === 'vercel' ? 'https://api.vercel.com' :
|
||||
provider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
|
||||
provider.type === 'deno' ? 'https://api.deno.com/v1' :
|
||||
'Base URL'
|
||||
}
|
||||
value={provider.baseURL || ''}
|
||||
onChange={(e) => {
|
||||
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 });
|
||||
} else if (provider.type === 'deno') {
|
||||
onUpdate(index, { ...provider, baseURL: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{(provider.type === 'cloudflare' || provider.type === 'deno') && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`provider-${index}-baseDomain`}>
|
||||
Base Domain (Optional)
|
||||
</Label>
|
||||
<Input
|
||||
id={`provider-${index}-baseDomain`}
|
||||
placeholder={provider.type === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
|
||||
value={provider.baseDomain || ''}
|
||||
onChange={(e) => onUpdate(index, { ...provider, baseDomain: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{provider.type === 'cloudflare'
|
||||
? 'The domain suffix for deployed workers (e.g., workers.dev)'
|
||||
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`provider-${index}-proxy`}
|
||||
@@ -282,6 +344,28 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
apiKeyURL: 'https://vercel.com/account/tokens',
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: 'cloudflare',
|
||||
type: 'cloudflare',
|
||||
name: 'Cloudflare',
|
||||
description: 'Deploy to Cloudflare Workers',
|
||||
apiKeyLabel: 'API Token',
|
||||
apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens',
|
||||
accountIdLabel: 'Account ID',
|
||||
accountIdURL: 'https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/',
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: 'deno',
|
||||
type: 'deno',
|
||||
name: 'Deno Deploy',
|
||||
description: 'Deploy to Deno Deploy',
|
||||
apiKeyLabel: 'Access Token',
|
||||
apiKeyURL: 'https://dash.deno.com/account#access-tokens',
|
||||
organizationIdLabel: 'Organization ID',
|
||||
organizationIdURL: 'https://dash.deno.com/orgs',
|
||||
proxy: true,
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to generate custom provider ID
|
||||
@@ -314,6 +398,20 @@ 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 'deno':
|
||||
// For Deno Deploy providers, check for custom baseURL first, then use default
|
||||
if ('baseURL' in provider && provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://deno.com';
|
||||
|
||||
case 'nsite':
|
||||
// nsite uses Rocket icon fallback
|
||||
return null;
|
||||
@@ -338,10 +436,13 @@ export function DeploySettings() {
|
||||
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
|
||||
|
||||
// Custom provider form state
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAccountId, setCustomAccountId] = useState('');
|
||||
const [customOrganizationId, setCustomOrganizationId] = useState('');
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customBaseDomain, setCustomBaseDomain] = useState('');
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
@@ -416,7 +517,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 +525,34 @@ 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 if (preset.type === 'deno') {
|
||||
const organizationId = presetApiKeys[`${preset.id}-organizationId`];
|
||||
if (!organizationId?.trim()) {
|
||||
return;
|
||||
}
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
name: preset.name,
|
||||
type: 'deno',
|
||||
apiKey: apiKey.trim(),
|
||||
organizationId: organizationId.trim(),
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
} else {
|
||||
return; // Unknown type
|
||||
}
|
||||
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
@@ -472,7 +601,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 +611,32 @@ 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() }),
|
||||
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'deno') {
|
||||
if (!customApiKey.trim() || !customOrganizationId.trim()) return;
|
||||
newProvider = {
|
||||
id: generateCustomProviderId(customProviderType), // Generate custom ID
|
||||
name: customName.trim(),
|
||||
type: 'deno',
|
||||
apiKey: customApiKey.trim(),
|
||||
organizationId: customOrganizationId.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else {
|
||||
return; // Unknown type
|
||||
}
|
||||
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
@@ -490,7 +645,10 @@ export function DeploySettings() {
|
||||
setCustomProviderType('');
|
||||
setCustomName('');
|
||||
setCustomApiKey('');
|
||||
setCustomAccountId('');
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
};
|
||||
@@ -601,31 +759,20 @@ export function DeploySettings() {
|
||||
return (
|
||||
<Card key={preset.id}>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{(() => {
|
||||
const url = getProviderUrl(preset);
|
||||
return url ? (
|
||||
<ExternalFavicon
|
||||
url={url}
|
||||
size={16}
|
||||
fallback={<Rocket size={16} />}
|
||||
/>
|
||||
) : (
|
||||
<Rocket size={16} />
|
||||
);
|
||||
})()}
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
{preset.apiKeyURL && !isOAuthConfigured && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
onClick={() => window.open(preset.apiKeyURL, '_blank')}
|
||||
>
|
||||
{t('getApiKey')}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
{(() => {
|
||||
const url = getProviderUrl(preset);
|
||||
return url ? (
|
||||
<ExternalFavicon
|
||||
url={url}
|
||||
size={16}
|
||||
fallback={<Rocket size={16} />}
|
||||
/>
|
||||
) : (
|
||||
<Rocket size={16} />
|
||||
);
|
||||
})()}
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{preset.description}</p>
|
||||
|
||||
@@ -703,34 +850,106 @@ export function DeploySettings() {
|
||||
) : (
|
||||
// Show manual token input
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.requiresNostr && preset.type !== 'nsite' && (
|
||||
<PasswordInput
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
|
||||
}
|
||||
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
{!preset.requiresNostr && preset.type !== 'nsite' && (
|
||||
<>
|
||||
{preset.type === 'cloudflare' && (
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder={preset.accountIdLabel || 'Account ID'}
|
||||
value={presetApiKeys[`${preset.id}-accountId`] || ''}
|
||||
onChange={(e) => 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`] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.accountIdURL, '_blank')}
|
||||
>
|
||||
Find ID
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{preset.type === 'deno' && (
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder={preset.organizationIdLabel || 'Organization ID'}
|
||||
value={presetApiKeys[`${preset.id}-organizationId`] || ''}
|
||||
onChange={(e) => 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`] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.organizationIdURL, '_blank')}
|
||||
>
|
||||
Find ID
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="relative">
|
||||
<PasswordInput
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => 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] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.apiKeyURL, '_blank')}
|
||||
>
|
||||
Get Key
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim()) ||
|
||||
(preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) ||
|
||||
(preset.type === 'deno' && !presetApiKeys[`${preset.id}-organizationId`]?.trim())
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -759,11 +978,14 @@ export function DeploySettings() {
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
setCustomAccountId('');
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
@@ -779,6 +1001,8 @@ export function DeploySettings() {
|
||||
<SelectItem value="nsite">nsite</SelectItem>
|
||||
<SelectItem value="netlify">Netlify</SelectItem>
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
<SelectItem value="cloudflare">Cloudflare</SelectItem>
|
||||
<SelectItem value="deno">Deno Deploy</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -847,9 +1071,38 @@ export function DeploySettings() {
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{customProviderType === 'cloudflare' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-accountid">
|
||||
Account ID <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-accountid"
|
||||
placeholder="Enter Account ID"
|
||||
value={customAccountId}
|
||||
onChange={(e) => setCustomAccountId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{customProviderType === 'deno' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-organizationid">
|
||||
Organization ID <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-organizationid"
|
||||
placeholder="Enter Organization ID"
|
||||
value={customOrganizationId}
|
||||
onChange={(e) => setCustomOrganizationId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">
|
||||
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'} <span className="text-destructive">*</span>
|
||||
{customProviderType === 'netlify' ? 'Personal Access Token' :
|
||||
customProviderType === 'cloudflare' ? 'API Token' :
|
||||
customProviderType === 'deno' ? 'Access Token' :
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="custom-apikey"
|
||||
@@ -865,12 +1118,32 @@ export function DeploySettings() {
|
||||
placeholder={
|
||||
customProviderType === 'netlify'
|
||||
? 'https://api.netlify.com/api/v1'
|
||||
: 'https://api.vercel.com'
|
||||
: customProviderType === 'vercel'
|
||||
? 'https://api.vercel.com'
|
||||
: customProviderType === 'deno'
|
||||
? 'https://api.deno.com/v1'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
}
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{(customProviderType === 'cloudflare' || customProviderType === 'deno') && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-basedomain">Base Domain (Optional)</Label>
|
||||
<Input
|
||||
id="custom-basedomain"
|
||||
placeholder={customProviderType === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
|
||||
value={customBaseDomain}
|
||||
onChange={(e) => setCustomBaseDomain(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{customProviderType === 'cloudflare'
|
||||
? 'The domain suffix for deployed workers (e.g., workers.dev)'
|
||||
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -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"
|
||||
>
|
||||
|
||||
+60
-47
@@ -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) => (
|
||||
<Card key={preset.id}>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.origin}
|
||||
size={16}
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
onClick={() => window.open(preset.tokenURL, '_blank')}
|
||||
>
|
||||
{t('getToken')}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.origin}
|
||||
size={16}
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
</div>
|
||||
|
||||
{preset.id === 'github' ? (
|
||||
@@ -308,20 +297,32 @@ export function GitSettings() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="relative flex-1">
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => 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] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.tokenURL, '_blank')}
|
||||
>
|
||||
Get Token
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetTokens[preset.id]?.trim()}
|
||||
@@ -334,20 +335,32 @@ export function GitSettings() {
|
||||
) : (
|
||||
// Standard rendering for other providers
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="relative flex-1">
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => 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] && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
|
||||
onClick={() => window.open(preset.tokenURL, '_blank')}
|
||||
>
|
||||
Get Token
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!presetTokens[preset.id]?.trim()}
|
||||
|
||||
Reference in new issue
Block a user