-
-
-
{t('plugins')}
+
+
+
{t('pluginsDescription')}
@@ -160,6 +173,12 @@ export function PluginsSection() {
+
+ {/* Discover Plugins Dialog */}
+
);
}
diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx
index a24e9115..8434a701 100644
--- a/src/components/Shakespeare/PreviewPane.tsx
+++ b/src/components/Shakespeare/PreviewPane.tsx
@@ -708,6 +708,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
+ {/* Category Tags (t-tags) */}
+
+
+
tag.trim().toLowerCase()}
+ allowDuplicates={false}
+ />
+
+ Tags for categorizing your repository. Press space or comma to add a tag.
+
+
+
{/* Earliest Commit */}
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/components/ui/tag-input.test.tsx b/src/components/ui/tag-input.test.tsx
new file mode 100644
index 00000000..d651182d
--- /dev/null
+++ b/src/components/ui/tag-input.test.tsx
@@ -0,0 +1,256 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { TagInput } from './tag-input';
+
+describe('TagInput', () => {
+ it('renders with placeholder when no tags', () => {
+ const onChange = vi.fn();
+ render(
+
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ expect(input).toBeInTheDocument();
+ });
+
+ it('displays existing tags', () => {
+ const onChange = vi.fn();
+ render(
+
+ );
+
+ expect(screen.getByText('tag1')).toBeInTheDocument();
+ expect(screen.getByText('tag2')).toBeInTheDocument();
+ expect(screen.getByText('tag3')).toBeInTheDocument();
+ });
+
+ it('adds tag on space key', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ await user.type(input, 'newtag ');
+
+ expect(onChange).toHaveBeenCalledWith(['newtag']);
+ });
+
+ it('adds tag on comma key', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ await user.type(input, 'newtag,');
+
+ expect(onChange).toHaveBeenCalledWith(['newtag']);
+ });
+
+ it('adds tag on Enter key', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ await user.type(input, 'newtag{Enter}');
+
+ expect(onChange).toHaveBeenCalledWith(['newtag']);
+ });
+
+ it('removes last tag on Backspace when input is empty', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByRole('textbox');
+ await user.click(input);
+ await user.keyboard('{Backspace}');
+
+ expect(onChange).toHaveBeenCalledWith(['tag1']);
+ });
+
+ it('removes tag when clicking X button', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const removeButtons = screen.getAllByRole('button');
+ await user.click(removeButtons[1]); // Remove tag2
+
+ expect(onChange).toHaveBeenCalledWith(['tag1', 'tag3']);
+ });
+
+ it('transforms tags using transformTag function', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
tag.toUpperCase()}
+ placeholder="Add tags..."
+ />
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ await user.type(input, 'lowercase ');
+
+ expect(onChange).toHaveBeenCalledWith(['LOWERCASE']);
+ });
+
+ it('prevents duplicate tags by default', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByRole('textbox');
+ await user.type(input, 'existing ');
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('allows duplicate tags when allowDuplicates is true', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByRole('textbox');
+ await user.type(input, 'existing ');
+
+ expect(onChange).toHaveBeenCalledWith(['existing', 'existing']);
+ });
+
+ it('validates tags using validateTag function', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+ tag.length >= 3}
+ placeholder="Add tags..."
+ />
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+
+ // Try adding tag that's too short
+ await user.type(input, 'ab ');
+ expect(onChange).not.toHaveBeenCalled();
+
+ // Add valid tag
+ await user.type(input, 'valid ');
+ expect(onChange).toHaveBeenCalledWith(['valid']);
+ });
+
+ it('does not add empty tags', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByPlaceholderText('Add tags...');
+ await user.type(input, ' '); // Just spaces
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('focuses input when container is clicked', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ const { container } = render(
+
+ );
+
+ const inputContainer = container.querySelector('div');
+ if (inputContainer) {
+ await user.click(inputContainer);
+ }
+
+ const input = screen.getByRole('textbox');
+ expect(input).toHaveFocus();
+ });
+
+ it('is disabled when disabled prop is true', () => {
+ const onChange = vi.fn();
+
+ render(
+
+ );
+
+ const input = screen.getByRole('textbox');
+ expect(input).toBeDisabled();
+ });
+});
diff --git a/src/components/ui/tag-input.tsx b/src/components/ui/tag-input.tsx
new file mode 100644
index 00000000..71484c03
--- /dev/null
+++ b/src/components/ui/tag-input.tsx
@@ -0,0 +1,172 @@
+import * as React from 'react';
+import { X } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+
+export interface TagInputProps
+ extends Omit, 'value' | 'onChange'> {
+ value: string[];
+ onChange: (tags: string[]) => void;
+ /** Character(s) that trigger tag creation. Default: [' ', ','] */
+ delimiters?: string[];
+ /** Transform tag before adding (e.g., toLowerCase). Default: (tag) => tag.trim() */
+ transformTag?: (tag: string) => string;
+ /** Validate tag before adding. Return false to reject. */
+ validateTag?: (tag: string) => boolean;
+ /** Allow duplicate tags. Default: false */
+ allowDuplicates?: boolean;
+}
+
+export const TagInput = React.forwardRef(
+ (
+ {
+ className,
+ value = [],
+ onChange,
+ delimiters = [' ', ','],
+ transformTag = (tag) => tag.trim(),
+ validateTag,
+ allowDuplicates = false,
+ disabled,
+ placeholder,
+ ...props
+ },
+ ref
+ ) => {
+ const [inputValue, setInputValue] = React.useState('');
+ const inputRef = React.useRef(null);
+ const containerRef = React.useRef(null);
+
+ // Combine external ref with internal ref
+ React.useImperativeHandle(ref, () => inputRef.current!);
+
+ const addTag = (tag: string) => {
+ const transformed = transformTag(tag);
+
+ if (!transformed) return;
+
+ // Check for duplicates if not allowed
+ if (!allowDuplicates && value.includes(transformed)) {
+ setInputValue('');
+ return;
+ }
+
+ // Validate if validator provided
+ if (validateTag && !validateTag(transformed)) {
+ setInputValue('');
+ return;
+ }
+
+ onChange([...value, transformed]);
+ setInputValue('');
+ };
+
+ const removeTag = (index: number) => {
+ onChange(value.filter((_, i) => i !== index));
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ // Handle delimiters (space, comma, etc.)
+ if (delimiters.includes(e.key)) {
+ e.preventDefault();
+ if (inputValue.trim()) {
+ addTag(inputValue);
+ }
+ return;
+ }
+
+ // Handle Enter key
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ if (inputValue.trim()) {
+ addTag(inputValue);
+ }
+ return;
+ }
+
+ // Handle Backspace - delete last tag if input is empty
+ if (e.key === 'Backspace' && !inputValue && value.length > 0) {
+ e.preventDefault();
+ removeTag(value.length - 1);
+ return;
+ }
+ };
+
+ const handleInputChange = (e: React.ChangeEvent) => {
+ const newValue = e.target.value;
+
+ // Check if any delimiter was typed
+ const hasDelimiter = delimiters.some(delimiter => newValue.includes(delimiter));
+
+ if (hasDelimiter) {
+ // Extract the part before the delimiter
+ const parts = newValue.split(new RegExp(`[${delimiters.map(d => d === ' ' ? '\\s' : d).join('')}]`));
+ const tagToAdd = parts[0];
+
+ if (tagToAdd.trim()) {
+ addTag(tagToAdd);
+ }
+ } else {
+ setInputValue(newValue);
+ }
+ };
+
+ const handleContainerClick = () => {
+ inputRef.current?.focus();
+ };
+
+ return (
+
+ {/* Render tags */}
+ {value.map((tag, index) => (
+
+ {tag}
+
+
+ ))}
+
+ {/* Input field */}
+
+
+ );
+ }
+);
+
+TagInput.displayName = 'TagInput';
diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts
index d52a5e42..09abe69a 100644
--- a/src/contexts/DeploySettingsContext.ts
+++ b/src/contexts/DeploySettingsContext.ts
@@ -32,7 +32,25 @@ export interface NsiteProvider extends BaseDeployProvider {
blossomServers: string[];
}
-export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
+export interface CloudflareProvider extends BaseDeployProvider {
+ type: 'cloudflare';
+ apiKey: string;
+ accountId: string;
+ baseURL?: string;
+ baseDomain?: string;
+ proxy?: boolean;
+}
+
+export interface DenoDeployProvider extends BaseDeployProvider {
+ type: 'deno';
+ apiKey: string;
+ organizationId: string;
+ baseURL?: string;
+ baseDomain?: string;
+ proxy?: boolean;
+}
+
+export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface DeploySettings {
providers: DeployProvider[];
diff --git a/src/hooks/useDiscoverPlugins.test.ts b/src/hooks/useDiscoverPlugins.test.ts
new file mode 100644
index 00000000..d694d27f
--- /dev/null
+++ b/src/hooks/useDiscoverPlugins.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest';
+import type { NostrEvent } from '@nostrify/nostrify';
+
+describe('useDiscoverPlugins', () => {
+ it('should validate NIP-34 event structure', () => {
+ // Example of a valid NIP-34 repository announcement event
+ const validEvent: NostrEvent = {
+ id: 'test-event-id',
+ pubkey: 'test-pubkey',
+ created_at: Math.floor(Date.now() / 1000),
+ kind: 30617,
+ tags: [
+ ['d', 'test-plugin'],
+ ['name', 'Test Plugin'],
+ ['description', 'A test Shakespeare plugin'],
+ ['clone', 'https://github.com/user/test-plugin.git'],
+ ['web', 'https://github.com/user/test-plugin'],
+ ['t', 'shakespeare-plugin'],
+ ],
+ content: '',
+ sig: 'test-signature',
+ };
+
+ // Verify the event has the correct kind
+ expect(validEvent.kind).toBe(30617);
+
+ // Verify required tags exist
+ const dTag = validEvent.tags.find(([name]) => name === 'd')?.[1];
+ const nameTag = validEvent.tags.find(([name]) => name === 'name')?.[1];
+ const tTag = validEvent.tags.find(([name, value]) => name === 't' && value === 'shakespeare-plugin');
+
+ expect(dTag).toBe('test-plugin');
+ expect(nameTag).toBe('Test Plugin');
+ expect(tTag).toBeDefined();
+ });
+
+ it('should identify required fields for plugin discovery', () => {
+ const event: NostrEvent = {
+ id: 'test-event-id',
+ pubkey: 'test-pubkey',
+ created_at: Math.floor(Date.now() / 1000),
+ kind: 30617,
+ tags: [
+ ['d', 'minimal-plugin'],
+ ['name', 'Minimal Plugin'],
+ ['t', 'shakespeare-plugin'],
+ ],
+ content: '',
+ sig: 'test-signature',
+ };
+
+ const dTag = event.tags.find(([name]) => name === 'd')?.[1];
+ const nameTag = event.tags.find(([name]) => name === 'name')?.[1];
+
+ // These are the minimum required fields
+ expect(dTag).toBeDefined();
+ expect(nameTag).toBeDefined();
+ });
+
+ it('should handle optional fields gracefully', () => {
+ const event: NostrEvent = {
+ id: 'test-event-id',
+ pubkey: 'test-pubkey',
+ created_at: Math.floor(Date.now() / 1000),
+ kind: 30617,
+ tags: [
+ ['d', 'plugin-without-optional'],
+ ['name', 'Plugin Without Optional Fields'],
+ ['t', 'shakespeare-plugin'],
+ ],
+ content: '',
+ sig: 'test-signature',
+ };
+
+ const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1];
+ const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1];
+ const webTag = event.tags.find(([name]) => name === 'web')?.[1];
+
+ // Optional fields should be undefined
+ expect(descriptionTag).toBeUndefined();
+ expect(cloneTag).toBeUndefined();
+ expect(webTag).toBeUndefined();
+ });
+});
diff --git a/src/hooks/useDiscoverPlugins.ts b/src/hooks/useDiscoverPlugins.ts
new file mode 100644
index 00000000..6c4e469f
--- /dev/null
+++ b/src/hooks/useDiscoverPlugins.ts
@@ -0,0 +1,88 @@
+import { useQuery } from '@tanstack/react-query';
+import { useNostr } from '@nostrify/react';
+import type { NostrEvent } from '@nostrify/nostrify';
+import { useCurrentUser } from './useCurrentUser';
+import { useContacts } from './useContacts';
+
+export interface DiscoveredPlugin {
+ id: string;
+ event: NostrEvent;
+ name: string;
+ description: string;
+ cloneUrl?: string;
+ webUrl?: string;
+ author: string;
+}
+
+/**
+ * Hook to discover Shakespeare plugins on Nostr
+ * Queries NIP-34 git repository announcements with t-tag "shakespeare-plugin"
+ * Filters to only show plugins by the current user and people they follow
+ */
+export function useDiscoverPlugins() {
+ const { nostr } = useNostr();
+ const { user } = useCurrentUser();
+ const { data: contacts } = useContacts(user?.pubkey);
+
+ return useQuery({
+ queryKey: ['discover-plugins', user?.pubkey, contacts],
+ queryFn: async () => {
+ // Build authors list: current user + people they follow
+ const authors: string[] = [];
+ if (user?.pubkey) {
+ authors.push(user.pubkey);
+ }
+ if (contacts && contacts.length > 0) {
+ authors.push(...contacts);
+ }
+
+ // If no authors (user not logged in or no follows), return empty array
+ if (authors.length === 0) {
+ return [];
+ }
+
+ // Query NIP-34 repository announcements (kind 30617) with shakespeare-plugin tag
+ // Filter by authors: current user + people they follow
+ const events = await nostr.query(
+ [
+ {
+ kinds: [30617],
+ authors,
+ '#t': ['shakespeare-plugin'],
+ limit: 100,
+ },
+ ],
+ { signal: AbortSignal.timeout(3000) }
+ );
+
+ // Transform events into DiscoveredPlugin objects
+ const plugins: DiscoveredPlugin[] = events
+ .map((event): DiscoveredPlugin | null => {
+ const dTag = event.tags.find(([name]) => name === 'd')?.[1];
+ const nameTag = event.tags.find(([name]) => name === 'name')?.[1];
+ const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1];
+ const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1];
+ const webTag = event.tags.find(([name]) => name === 'web')?.[1];
+
+ // Skip events without required fields
+ if (!dTag || !nameTag) {
+ return null;
+ }
+
+ return {
+ id: dTag,
+ event,
+ name: nameTag,
+ description: descriptionTag || '',
+ cloneUrl: cloneTag,
+ webUrl: webTag,
+ author: event.pubkey,
+ };
+ })
+ .filter((plugin): plugin is DiscoveredPlugin => plugin !== null);
+
+ return plugins;
+ },
+ staleTime: 5 * 60 * 1000, // 5 minutes
+ });
+}
diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts
index 47e049c7..467bd3a9 100644
--- a/src/hooks/useProjectDeploySettings.ts
+++ b/src/hooks/useProjectDeploySettings.ts
@@ -31,7 +31,21 @@ export interface VercelProjectConfig {
};
}
-export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
+export interface CloudflareProjectConfig {
+ type: 'cloudflare';
+ data: {
+ projectName?: string;
+ };
+}
+
+export interface DenoDeployProjectConfig {
+ type: 'deno';
+ data: {
+ projectName?: string;
+ };
+}
+
+export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig;
export interface ProjectDeploySettings {
providers: Record;
diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts
index 0e4077c6..2b9ce8b3 100644
--- a/src/lib/ProjectsManager.ts
+++ b/src/lib/ProjectsManager.ts
@@ -193,16 +193,17 @@ export class ProjectsManager {
/**
* Copy a directory recursively from source to destination
+ * @param skipGit - Whether to skip the .git directory (default: true)
*/
- private async copyDirectory(sourcePath: string, destPath: string): Promise {
+ private async copyDirectory(sourcePath: string, destPath: string, skipGit = true): Promise {
// Ensure destination directory exists
await this.fs.mkdir(destPath, { recursive: true });
const entries = await this.fs.readdir(sourcePath);
for (const entry of entries) {
- // Skip .git directory
- if (entry === '.git') continue;
+ // Skip .git directory if skipGit is true
+ if (skipGit && entry === '.git') continue;
const sourceFullPath = `${sourcePath}/${entry}`;
const destFullPath = `${destPath}/${entry}`;
@@ -212,7 +213,7 @@ export class ProjectsManager {
if (stat.isDirectory()) {
// Recursively copy subdirectories
- await this.copyDirectory(sourceFullPath, destFullPath);
+ await this.copyDirectory(sourceFullPath, destFullPath, skipGit);
} else if (stat.isFile()) {
// Copy file
const content = await this.fs.readFile(sourceFullPath);
@@ -726,6 +727,56 @@ export class ProjectsManager {
};
}
+ async duplicateProject(sourceId: string, newName?: string): Promise {
+ // Validate that the source project exists
+ const sourceProject = await this.getProject(sourceId);
+ if (!sourceProject) {
+ throw new Error(`Project with ID "${sourceId}" does not exist`);
+ }
+
+ // Generate a unique ID for the new project
+ const baseName = newName || `${sourceId}-copy`;
+ const newId = await this.generateUniqueProjectId(baseName);
+
+ const sourcePath = `${this.dir}/${sourceId}`;
+ const destPath = `${this.dir}/${newId}`;
+
+ try {
+ // Create the destination directory
+ await this.fs.mkdir(destPath, { recursive: true });
+
+ // Copy all files from source to destination (including .git)
+ await this.copyDirectory(sourcePath, destPath, false);
+
+ // Get filesystem stats for timestamps
+ const stats = await this.fs.stat(destPath);
+ const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
+
+ // Automatically request persistent storage after project duplication
+ try {
+ await ensurePersistentStorage();
+ } catch (error) {
+ // Don't fail project duplication if persistent storage request fails
+ console.warn('Failed to request persistent storage after project duplication:', error);
+ }
+
+ return {
+ id: newId,
+ name: this.formatProjectName(newId),
+ path: destPath,
+ lastModified: timestamp,
+ };
+ } catch (error) {
+ // Clean up on error
+ try {
+ await this.deleteDirectory(destPath);
+ } catch (cleanupError) {
+ console.warn('Failed to clean up directory after duplication failure:', cleanupError);
+ }
+ throw error;
+ }
+ }
+
private async deleteDirectory(dirPath: string): Promise {
const files = await this.fs.readdir(dirPath);
diff --git a/src/lib/announceRepository.ts b/src/lib/announceRepository.ts
index 0d6ae314..fff9fa24 100644
--- a/src/lib/announceRepository.ts
+++ b/src/lib/announceRepository.ts
@@ -15,6 +15,8 @@ export interface RepositoryAnnouncementData {
cloneUrls: string[];
/** Relays for patch submissions */
relays?: string[];
+ /** Category tags for the repository */
+ tTags?: string[];
/** Earliest unique commit (root commit) */
earliestCommit?: string;
}
@@ -95,6 +97,14 @@ export function createRepositoryAnnouncementEvent(
}
}
+ // Add t-tags for categorization (each as a separate tag for relay-level filtering)
+ if (data.tTags && data.tTags.length > 0) {
+ const trimmedTags = data.tTags.map(tag => tag.trim().toLowerCase()).filter(tag => tag);
+ for (const tag of trimmedTags) {
+ tags.push(['t', tag]);
+ }
+ }
+
// Add earliest unique commit (euc) for repository identification
if (data.earliestCommit?.trim()) {
tags.push(['r', data.earliestCommit.trim(), 'euc']);
diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts
index ba7b2ffe..bd4c1ab5 100644
--- a/src/lib/configUtils.test.ts
+++ b/src/lib/configUtils.test.ts
@@ -228,6 +228,13 @@ describe('configUtils', () => {
name: 'Shakespeare',
type: 'shakespeare',
},
+ {
+ id: 'provider-4',
+ name: 'My Cloudflare',
+ type: 'cloudflare',
+ apiKey: 'cloudflare-token-789',
+ accountId: 'account-123',
+ },
],
};
diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts
index 566dae6e..1a2a8f3b 100644
--- a/src/lib/configUtils.ts
+++ b/src/lib/configUtils.ts
@@ -106,11 +106,29 @@ const nsiteProviderSchema = baseDeployProviderSchema.extend({
blossomServers: z.array(z.string()),
});
+const cloudflareProviderSchema = baseDeployProviderSchema.extend({
+ type: z.literal('cloudflare'),
+ apiKey: z.string(),
+ accountId: z.string(),
+ baseURL: z.string().optional(),
+ baseDomain: z.string().optional(),
+});
+
+const denoDeployProviderSchema = baseDeployProviderSchema.extend({
+ type: z.literal('deno'),
+ apiKey: z.string(),
+ organizationId: z.string(),
+ baseURL: z.string().optional(),
+ baseDomain: z.string().optional(),
+});
+
const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
vercelProviderSchema,
nsiteProviderSchema,
+ cloudflareProviderSchema,
+ denoDeployProviderSchema,
]);
const deploySettingsSchema = z.object({
diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts
new file mode 100644
index 00000000..5db367c2
--- /dev/null
+++ b/src/lib/deploy/CloudflareAdapter.ts
@@ -0,0 +1,406 @@
+import type { JSRuntimeFS } from '../JSRuntime';
+import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
+import { proxyUrl } from '../proxyUrl';
+
+interface AssetManifest {
+ [path: string]: { hash: string; size: number };
+}
+
+interface InitializeAssetsResponse {
+ buckets: string[][];
+ jwt: string;
+}
+
+interface UploadResponse {
+ jwt?: string;
+}
+
+interface WorkerScript {
+ id: string;
+ etag: string;
+ handlers: string[];
+ modified_on: string;
+ created_on: string;
+ has_assets: boolean;
+}
+
+interface FileInfo {
+ hash: string;
+ content: Uint8Array;
+ size: number;
+ contentType: string;
+}
+
+/**
+ * Cloudflare Workers Deploy Adapter
+ * Uses Cloudflare Workers API with static assets support
+ *
+ * Implements the Workers Assets upload workflow:
+ * 1. Build asset manifest with file hashes
+ * 2. Initialize upload session to get buckets of files to upload
+ * 3. Upload files in buckets using FormData with base64 content
+ * 4. Deploy worker with assets JWT
+ */
+export class CloudflareAdapter implements DeployAdapter {
+ private fs: JSRuntimeFS;
+ private apiKey: string;
+ private accountId: string;
+ private baseURL: string;
+ private baseDomain: string;
+ private projectName?: string;
+ private corsProxy?: string;
+
+ constructor(config: CloudflareDeployConfig) {
+ this.fs = config.fs;
+ this.apiKey = config.apiKey;
+ this.accountId = config.accountId;
+ this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4';
+ this.baseDomain = config.baseDomain || 'workers.dev';
+ this.projectName = config.projectName;
+ this.corsProxy = config.corsProxy;
+ }
+
+ async deploy(options: DeployOptions): Promise {
+ const { projectId, projectPath } = options;
+
+ // Check if dist directory exists and contains index.html
+ const distPath = `${projectPath}/dist`;
+ try {
+ await this.fs.readFile(`${distPath}/index.html`, 'utf8');
+ } catch {
+ throw new Error('No index.html found in dist directory. Please build the project first.');
+ }
+
+ const scriptName = this.projectName || projectId;
+
+ // Step 1: Collect all files and build manifest
+ const files = new Map();
+ await this.collectFiles(distPath, '', files);
+
+ const manifest: AssetManifest = {};
+ for (const [filePath, fileInfo] of files) {
+ // Normalize path with leading slash
+ const normalizedPath = '/' + filePath.replace(/\\/g, '/');
+ manifest[normalizedPath] = {
+ hash: fileInfo.hash,
+ size: fileInfo.size,
+ };
+ }
+
+ // Step 2: Initialize upload session
+ const initResponse = await this.initializeUploadSession(scriptName, manifest);
+
+ // Step 3: Upload files in buckets (in parallel for speed)
+ let completionJwt = initResponse.jwt;
+
+ if (initResponse.buckets.flat().length > 0) {
+ // Create lookup from hash to file info
+ const hashToFile = new Map();
+ for (const [filePath, fileInfo] of files) {
+ hashToFile.set(fileInfo.hash, { path: filePath, info: fileInfo });
+ }
+
+ // Upload all buckets in parallel
+ const uploadResults = await Promise.all(
+ initResponse.buckets.map((bucket) =>
+ this.uploadBucket(initResponse.jwt, bucket, hashToFile)
+ )
+ );
+
+ // Get the completion JWT from the last result that has one
+ const lastJwtResult = [...uploadResults].reverse().find((r) => r.jwt);
+ if (lastJwtResult?.jwt) {
+ completionJwt = lastJwtResult.jwt;
+ }
+ }
+
+ // Step 4: Deploy the worker with assets
+ const deployment = await this.deployWorker(scriptName, completionJwt);
+
+ // Step 5: Enable the workers.dev subdomain for this script
+ await this.enableWorkersDevSubdomain(scriptName);
+
+ // Step 6: Get the account's workers subdomain
+ const subdomain = await this.getWorkersSubdomain();
+
+ // Construct the URL using the configurable base domain
+ const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`;
+
+ return {
+ url: workerUrl,
+ metadata: {
+ scriptId: deployment.id,
+ scriptName: scriptName,
+ provider: 'cloudflare-workers',
+ hasAssets: deployment.has_assets,
+ modifiedOn: deployment.modified_on,
+ },
+ };
+ }
+
+ private async getWorkersSubdomain(): Promise {
+ const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const response = await fetch(targetUrl, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ },
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ const data = await response.json();
+ return data.result.subdomain;
+ }
+
+ private async enableWorkersDevSubdomain(scriptName: string): Promise {
+ const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const response = await fetch(targetUrl, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ enabled: true,
+ previews_enabled: true,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to enable workers.dev subdomain: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+ }
+
+ private async initializeUploadSession(
+ scriptName: string,
+ manifest: AssetManifest
+ ): Promise {
+ const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const response = await fetch(targetUrl, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ manifest }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to initialize upload session: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ const data = await response.json();
+ return data.result;
+ }
+
+ private async uploadBucket(
+ jwt: string,
+ bucket: string[],
+ hashToFile: Map
+ ): Promise {
+ const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const formData = new FormData();
+
+ for (const fileHash of bucket) {
+ const fileData = hashToFile.get(fileHash);
+ if (!fileData) {
+ throw new Error(`File with hash ${fileHash} not found in manifest`);
+ }
+
+ // Convert content to base64
+ const base64Content = this.uint8ArrayToBase64(fileData.info.content);
+
+ // Use content type or "application/null" to signal no content-type header
+ const contentType = fileData.info.contentType || 'application/null';
+
+ // Create a File/Blob with the base64 content
+ const blob = new Blob([base64Content], { type: contentType });
+ formData.append(fileHash, blob, fileHash);
+ }
+
+ const response = await fetch(targetUrl, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${jwt}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to upload assets: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ const data = await response.json();
+ return data.result || {};
+ }
+
+ private async deployWorker(scriptName: string, assetsJwt: string): Promise {
+ const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ // Create a minimal worker script that serves static assets
+ // This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
+ const workerScript = `
+export default {
+ async fetch(request, env) {
+ // This worker only serves static assets
+ // The assets are automatically served by Cloudflare's asset handler
+ return new Response('Not Found', { status: 404 });
+ }
+};
+`;
+
+ const formData = new FormData();
+
+ // Add the worker script as the main module
+ const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
+ formData.append('worker.js', scriptBlob, 'worker.js');
+
+ // Add metadata with assets configuration
+ const metadata = {
+ main_module: 'worker.js',
+ compatibility_date: new Date().toISOString().split('T')[0],
+ assets: {
+ jwt: assetsJwt,
+ config: {
+ html_handling: 'auto-trailing-slash',
+ not_found_handling: 'single-page-application',
+ },
+ },
+ };
+
+ formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
+
+ const response = await fetch(targetUrl, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ const data = await response.json();
+ return data.result;
+ }
+
+ private async collectFiles(
+ dirPath: string,
+ relativePath: string,
+ files: Map
+ ): Promise {
+ try {
+ const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = `${dirPath}/${entry.name}`;
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
+
+ if (entry.isDirectory()) {
+ await this.collectFiles(fullPath, entryRelativePath, files);
+ } else if (entry.isFile()) {
+ try {
+ const fileContent = await this.fs.readFile(fullPath);
+
+ // Convert to Uint8Array
+ let content: Uint8Array;
+ if (typeof fileContent === 'string') {
+ content = new TextEncoder().encode(fileContent);
+ } else {
+ content = fileContent;
+ }
+
+ // Calculate hash (same algorithm as Wrangler uses)
+ const hash = await this.calculateHash(content);
+
+ // Determine content type
+ const contentType = this.getContentType(entry.name);
+
+ files.set(entryRelativePath, {
+ hash,
+ content,
+ size: content.length,
+ contentType,
+ });
+ } catch (error) {
+ console.warn(`Failed to read file ${fullPath}:`, error);
+ }
+ }
+ }
+ } catch (error) {
+ console.warn(`Failed to read directory ${dirPath}:`, error);
+ }
+ }
+
+ private async calculateHash(content: Uint8Array): Promise {
+ // Use xxHash algorithm like Wrangler does, but fall back to SHA-256 for browser compatibility
+ const hashBuffer = await crypto.subtle.digest('SHA-256', content);
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ // Take first 16 bytes (32 hex chars) to match Wrangler's hash length
+ const hashHex = hashArray.slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join('');
+ return hashHex;
+ }
+
+ private uint8ArrayToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ for (let i = 0; i < bytes.length; i++) {
+ binary += String.fromCharCode(bytes[i]);
+ }
+ return btoa(binary);
+ }
+
+ private getContentType(filename: string): string {
+ const ext = filename.split('.').pop()?.toLowerCase() || '';
+ const mimeTypes: Record = {
+ 'html': 'text/html',
+ 'htm': 'text/html',
+ 'css': 'text/css',
+ 'js': 'application/javascript',
+ 'mjs': 'application/javascript',
+ 'json': 'application/json',
+ 'png': 'image/png',
+ 'jpg': 'image/jpeg',
+ 'jpeg': 'image/jpeg',
+ 'gif': 'image/gif',
+ 'svg': 'image/svg+xml',
+ 'ico': 'image/x-icon',
+ 'webp': 'image/webp',
+ 'avif': 'image/avif',
+ 'woff': 'font/woff',
+ 'woff2': 'font/woff2',
+ 'ttf': 'font/ttf',
+ 'eot': 'application/vnd.ms-fontobject',
+ 'otf': 'font/otf',
+ 'txt': 'text/plain',
+ 'xml': 'application/xml',
+ 'pdf': 'application/pdf',
+ 'zip': 'application/zip',
+ 'mp4': 'video/mp4',
+ 'webm': 'video/webm',
+ 'mp3': 'audio/mpeg',
+ 'wav': 'audio/wav',
+ 'ogg': 'audio/ogg',
+ 'wasm': 'application/wasm',
+ };
+ return mimeTypes[ext] || 'application/octet-stream';
+ }
+}
diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts
new file mode 100644
index 00000000..041b0aa6
--- /dev/null
+++ b/src/lib/deploy/DenoDeployAdapter.ts
@@ -0,0 +1,287 @@
+import type { JSRuntimeFS } from '../JSRuntime';
+import type { DeployAdapter, DeployOptions, DeployResult, DenoDeployConfig } from './types';
+import { proxyUrl } from '../proxyUrl';
+
+interface Project {
+ id: string;
+ name: string;
+ createdAt: string;
+ updatedAt: string;
+}
+
+interface Deployment {
+ id: string;
+ projectId: string;
+ status: string;
+ domains: string[];
+ createdAt: string;
+ updatedAt: string;
+}
+
+/**
+ * Deno Deploy Adapter
+ * Uses Deno Deploy API to deploy static sites
+ *
+ * Implements the Deno Deploy workflow:
+ * 1. Create or find existing project
+ * 2. Build asset manifest with file contents
+ * 3. Create deployment with assets
+ * 4. Attach domain to deployment
+ */
+export class DenoDeployAdapter implements DeployAdapter {
+ private fs: JSRuntimeFS;
+ private apiKey: string;
+ private organizationId: string;
+ private baseURL: string;
+ private baseDomain: string;
+ private projectName?: string;
+ private corsProxy?: string;
+
+ constructor(config: DenoDeployConfig) {
+ this.fs = config.fs;
+ this.apiKey = config.apiKey;
+ this.organizationId = config.organizationId;
+ this.baseURL = config.baseURL || 'https://api.deno.com/v1';
+ this.baseDomain = config.baseDomain || 'deno.dev';
+ this.projectName = config.projectName;
+ this.corsProxy = config.corsProxy;
+ }
+
+ async deploy(options: DeployOptions): Promise {
+ const { projectId, projectPath } = options;
+
+ // Check if dist directory exists and contains index.html
+ const distPath = `${projectPath}/dist`;
+ try {
+ await this.fs.readFile(`${distPath}/index.html`, 'utf8');
+ } catch {
+ throw new Error('No index.html found in dist directory. Please build the project first.');
+ }
+
+ const projectName = this.projectName || projectId;
+
+ // Step 1: Get or create project
+ const project = await this.getOrCreateProject(projectName);
+
+ // Step 2: Collect all files and build assets
+ const assets: Record = {};
+ await this.collectFiles(distPath, '', assets);
+
+ // Step 3: Create deployment with assets and domain
+ const domain = `${project.name}.${this.baseDomain}`;
+ const deployment = await this.createDeployment(project.id, assets, domain);
+
+ return {
+ url: `https://${domain}`,
+ metadata: {
+ deploymentId: deployment.id,
+ projectId: project.id,
+ projectName: project.name,
+ provider: 'deno-deploy',
+ status: deployment.status,
+ },
+ };
+ }
+
+ private async getOrCreateProject(projectName: string): Promise {
+ // First, try to find existing project
+ const existingProject = await this.findProject(projectName);
+ if (existingProject) {
+ return existingProject;
+ }
+
+ // Create new project
+ return this.createProject(projectName);
+ }
+
+ private async findProject(projectName: string): Promise {
+ const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const response = await fetch(targetUrl, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ },
+ });
+
+ if (!response.ok) {
+ // If we can't list projects, just return null and try to create
+ return null;
+ }
+
+ const projects: Project[] = await response.json();
+ return projects.find(p => p.name === projectName) || null;
+ }
+
+ private async createProject(projectName: string): Promise {
+ const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ const response = await fetch(targetUrl, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ name: projectName,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to create project: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ return response.json();
+ }
+
+ private async createDeployment(
+ projectId: string,
+ assets: Record,
+ domain: string
+ ): Promise {
+ const url = `${this.baseURL}/projects/${projectId}/deployments`;
+ const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
+
+ // Create a minimal server script that serves static files
+ // For static sites, we use a simple file server entry point
+ const entryPointUrl = 'main.ts';
+
+ // Add the entry point script that serves static files
+ const serverScript = `
+import { serveDir } from "jsr:@std/http/file-server";
+
+Deno.serve((req) => {
+ return serveDir(req, {
+ fsRoot: ".",
+ showIndex: true,
+ enableCors: true,
+ });
+});
+`;
+
+ // Add the server script to assets
+ assets['main.ts'] = {
+ kind: 'file',
+ content: serverScript,
+ encoding: 'utf-8',
+ };
+
+ const response = await fetch(targetUrl, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ entryPointUrl,
+ assets,
+ importMapUrl: null,
+ lockFileUrl: null,
+ compilerOptions: null,
+ envVars: {},
+ // Attach domain during deployment creation instead of separately
+ domains: [domain],
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ throw new Error(`Failed to create deployment: ${response.status} ${response.statusText}. ${errorText}`);
+ }
+
+ return response.json();
+ }
+
+ private async collectFiles(
+ dirPath: string,
+ relativePath: string,
+ assets: Record
+ ): Promise {
+ try {
+ const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = `${dirPath}/${entry.name}`;
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
+
+ if (entry.isDirectory()) {
+ await this.collectFiles(fullPath, entryRelativePath, assets);
+ } else if (entry.isFile()) {
+ try {
+ const fileContent = await this.fs.readFile(fullPath);
+
+ // Determine if file is text or binary based on extension
+ const isText = this.isTextFile(entry.name);
+
+ let content: string;
+ let encoding: 'utf-8' | 'base64';
+
+ if (isText) {
+ if (typeof fileContent === 'string') {
+ content = fileContent;
+ } else {
+ content = new TextDecoder().decode(fileContent);
+ }
+ encoding = 'utf-8';
+ } else {
+ // Binary file - encode as base64
+ let bytes: Uint8Array;
+ if (typeof fileContent === 'string') {
+ bytes = new TextEncoder().encode(fileContent);
+ } else {
+ bytes = fileContent;
+ }
+ content = this.uint8ArrayToBase64(bytes);
+ encoding = 'base64';
+ }
+
+ assets[entryRelativePath] = {
+ kind: 'file',
+ content,
+ encoding,
+ };
+ } catch (error) {
+ console.warn(`Failed to read file ${fullPath}:`, error);
+ }
+ }
+ }
+ } catch (error) {
+ console.warn(`Failed to read directory ${dirPath}:`, error);
+ }
+ }
+
+ private isTextFile(filename: string): boolean {
+ const textExtensions = [
+ 'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx',
+ 'json', 'xml', 'svg', 'txt', 'md', 'yaml', 'yml', 'toml',
+ 'sh', 'bash', 'zsh', 'fish', 'bat', 'cmd', 'ps1',
+ 'py', 'rb', 'php', 'java', 'c', 'cpp', 'h', 'hpp',
+ 'rs', 'go', 'swift', 'kt', 'scala', 'clj', 'ex', 'exs',
+ 'vue', 'svelte', 'astro', 'njk', 'ejs', 'pug', 'hbs',
+ 'graphql', 'gql', 'sql', 'csv', 'tsv', 'log', 'ini', 'cfg',
+ 'env', 'gitignore', 'dockerignore', 'editorconfig',
+ 'prettierrc', 'eslintrc', 'babelrc', 'npmrc',
+ 'map', // source maps
+ ];
+
+ const ext = filename.split('.').pop()?.toLowerCase() || '';
+ // Also check if filename itself is a known text file
+ const textFilenames = [
+ 'dockerfile', 'makefile', 'gemfile', 'rakefile', 'procfile',
+ 'license', 'readme', 'changelog', 'authors', 'contributors',
+ ];
+
+ return textExtensions.includes(ext) || textFilenames.includes(filename.toLowerCase());
+ }
+
+ private uint8ArrayToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ for (let i = 0; i < bytes.length; i++) {
+ binary += String.fromCharCode(bytes[i]);
+ }
+ return btoa(binary);
+ }
+}
diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts
index 830bff96..24bf4795 100644
--- a/src/lib/deploy/index.ts
+++ b/src/lib/deploy/index.ts
@@ -3,3 +3,5 @@ export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
export * from './NsiteAdapter';
+export * from './CloudflareAdapter';
+export * from './DenoDeployAdapter';
diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts
index 5adf4eeb..60222a5d 100644
--- a/src/lib/deploy/types.ts
+++ b/src/lib/deploy/types.ts
@@ -54,3 +54,23 @@ export interface NsiteDeployConfig {
relayUrls: string[];
blossomServers: string[];
}
+
+export interface CloudflareDeployConfig {
+ fs: JSRuntimeFS;
+ apiKey: string;
+ accountId: string;
+ baseURL?: string;
+ baseDomain?: string;
+ projectName?: string;
+ corsProxy?: string;
+}
+
+export interface DenoDeployConfig {
+ fs: JSRuntimeFS;
+ apiKey: string;
+ organizationId: string;
+ baseURL?: string;
+ baseDomain?: string;
+ projectName?: string;
+ corsProxy?: string;
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index b8209af1..92d1c60a 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -93,11 +93,10 @@
"name": "Name",
"id": "ID",
"email": "Email",
- "buildNostrApps": "Build apps with AI",
- "whatToBuild": "What would you like to build?",
+ "buildApps": "Build apps with AI",
"chooseModel": "Choose a model...",
- "selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
- "examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
+ "selectModelToDescribe": "Select a model below to get started...",
+ "examplePrompt": "Describe what you'd like to build...",
"aiSettings": "AI",
"aiSettingsDescription": "Configure AI providers and API keys",
"gitSettings": "Git",
@@ -479,6 +478,26 @@
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
"pluginsDirectory": "Plugins Directory",
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
+ "discoverPlugins": "Discover Plugins",
+ "discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
+ "searchPlugins": "Search plugins...",
+ "noPluginsFound": "No plugins found matching your search.",
+ "noPluginsAvailable": "No plugins available at this time.",
+ "pluginInstalled": "Plugin Installed",
+ "pluginInstalledDescription": "Plugin \"{{name}}\" has been installed successfully.",
+ "pluginInstallFailed": "Failed to Install Plugin",
+ "noCloneUrl": "No Clone URL",
+ "noCloneUrlDescription": "This plugin does not have a clone URL configured.",
+ "installed": "Installed",
+ "install": "Install",
+ "installing": "Installing...",
+ "by": "by",
+ "website": "Website",
+ "loginRequired": "Login Required",
+ "loginToDiscoverPlugins": "Log in with Nostr to discover plugins from people you follow.",
+ "noPluginsFromNetwork": "No Plugins Found",
+ "noPluginsFromNetworkDescription": "No plugins found from people you follow. Follow plugin developers on Nostr to see their plugins here.",
+ "tryDifferentSearch": "Try a different search term.",
"mcpServers": "MCP Servers",
"mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.",
"addMcpServer": "Add MCP Server",
@@ -539,5 +558,12 @@
"selectLabels": "Select labels",
"noLabelsCreated": "No labels created yet",
"createNewLabel": "Create new label",
- "otherProjects": "Other projects"
+ "otherProjects": "Other projects",
+ "duplicateProject": "Duplicate Project",
+ "duplicatingProject": "Duplicating project...",
+ "projectDuplicated": "Project duplicated",
+ "projectDuplicatedDescription": "Project has been duplicated successfully.",
+ "failedToDuplicateProject": "Failed to duplicate project",
+ "newProjectName": "New Project Name",
+ "duplicateProjectDescription": "Create a copy of this project with a new name"
}
diff --git a/src/locales/ha.json b/src/locales/ha.json
index 3a51fc88..5ab28476 100644
--- a/src/locales/ha.json
+++ b/src/locales/ha.json
@@ -89,11 +89,10 @@
"name": "Suna",
"id": "ID",
"email": "Imel",
- "buildNostrApps": "Gina aikace-aikace da AI",
- "whatToBuild": "Me kuke son ginawa?",
+ "buildApps": "Gina aikace-aikace da AI",
"chooseModel": "Zaɓi samfuri...",
- "selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...",
- "examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...",
+ "selectModelToDescribe": "Zaɓi samfuri a ƙasa don farawa...",
+ "examplePrompt": "Bayyana abin da kuke son ginawa...",
"settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.",
"aiSettings": "AI",
"aiSettingsDescription": "Saita masu samar da AI da maɓallan API",
@@ -446,5 +445,32 @@
"selectLabels": "Zaɓi lakabi",
"noLabelsCreated": "Ba a ƙirƙiri lakabi tukuna ba",
"createNewLabel": "Ƙirƙiri sabon lakabi",
- "otherProjects": "Sauran ayyuka"
+ "otherProjects": "Sauran ayyuka",
+ "discoverPlugins": "Gano Plugins",
+ "discoverPluginsDescription": "Bincika kuma shigar da plugins na Shakespeare da aka raba akan hanyar sadarwa ta Nostr.",
+ "searchPlugins": "Bincika plugins...",
+ "noPluginsFound": "Ba a sami plugins da suka dace da bincikenka ba.",
+ "noPluginsAvailable": "Babu plugins a wannan lokaci.",
+ "pluginInstalled": "An Shigar da Plugin",
+ "pluginInstalledDescription": "An shigar da plugin \"{{name}}\" cikin nasara.",
+ "pluginInstallFailed": "An Kasa Shigar da Plugin",
+ "noCloneUrl": "Babu Clone URL",
+ "noCloneUrlDescription": "Wannan plugin ba shi da clone URL da aka saita.",
+ "installed": "An Shigar",
+ "install": "Shigar",
+ "installing": "Ana Shigarwa...",
+ "by": "ta",
+ "website": "Gidan Yanar Gizo",
+ "loginRequired": "Ana Buƙatar Shiga",
+ "loginToDiscoverPlugins": "Shiga tare da Nostr don gano plugins daga mutanen da kuke bi.",
+ "noPluginsFromNetwork": "Ba a Sami Plugin ba",
+ "noPluginsFromNetworkDescription": "Ba a sami plugins daga mutanen da kuke bi ba. Bi masu haɓaka plugins akan Nostr don ganin plugins nasu a nan.",
+ "tryDifferentSearch": "Gwada kalmar bincike daban.",
+ "duplicateProject": "Kwafin Aikin",
+ "duplicatingProject": "Ana kwafin aikin...",
+ "projectDuplicated": "An kwafi aikin",
+ "projectDuplicatedDescription": "An kwafi aikin cikin nasara.",
+ "failedToDuplicateProject": "An kasa kwafin aikin",
+ "newProjectName": "Sunan Sabon Aikin",
+ "duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna"
}
diff --git a/src/locales/ig.json b/src/locales/ig.json
index 78dff1e0..de1b3bd3 100644
--- a/src/locales/ig.json
+++ b/src/locales/ig.json
@@ -89,11 +89,10 @@
"name": "Aha",
"id": "ID",
"email": "Ozi-eletrọniki",
- "buildNostrApps": "Wuo ngwa na AI",
- "whatToBuild": "Gịnị ka ị chọrọ iwu?",
+ "buildApps": "Wuo ngwa na AI",
"chooseModel": "Họrọ ụdịdị...",
- "selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...",
- "examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...",
+ "selectModelToDescribe": "Họrọ ụdịdị n'okpuru iji malite...",
+ "examplePrompt": "Kọwaa ihe ị chọrọ iwu...",
"settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.",
"aiSettings": "AI",
"aiSettingsDescription": "Hazie ndị na-enye AI na igodo API",
@@ -443,5 +442,32 @@
"selectLabels": "Họrọ akara",
"noLabelsCreated": "Emepụtaghị akara ọ bụla",
"createNewLabel": "Mepụta akara ọhụrụ",
- "otherProjects": "Ọrụ ndị ọzọ"
+ "otherProjects": "Ọrụ ndị ọzọ",
+ "discoverPlugins": "Chọpụta Plugins",
+ "discoverPluginsDescription": "Chọgharịa ma wụnye plugins Shakespeare nke ekekọrịtara na netwọk Nostr.",
+ "searchPlugins": "Chọọ plugins...",
+ "noPluginsFound": "Achọtaghị plugins dabara na nchọgharị gị.",
+ "noPluginsAvailable": "Enweghị plugins dị ugbu a.",
+ "pluginInstalled": "Ewubatara Plugin",
+ "pluginInstalledDescription": "Ewubatara plugin \"{{name}}\" nke ọma.",
+ "pluginInstallFailed": "Ọ Dara Ada Ịwụnye Plugin",
+ "noCloneUrl": "Enweghị Clone URL",
+ "noCloneUrlDescription": "Plugin a enweghị clone URL edoziri.",
+ "installed": "Ewubatara",
+ "install": "Wụnye",
+ "installing": "Na-ewunye...",
+ "by": "site na",
+ "website": "Webụsaịtị",
+ "loginRequired": "Achọrọ Nbanye",
+ "loginToDiscoverPlugins": "Banye na Nostr iji chọpụta plugins sitere na ndị ị na-eso.",
+ "noPluginsFromNetwork": "Achọtaghị Plugins",
+ "noPluginsFromNetworkDescription": "Achọtaghị plugins sitere na ndị ị na-eso. Soro ndị mmepe plugin na Nostr iji hụ plugins ha ebe a.",
+ "tryDifferentSearch": "Gbalịa okwu nchọgharị dị iche.",
+ "duplicateProject": "Mepụta Ọrụ",
+ "duplicatingProject": "Na-emepụta ọrụ...",
+ "projectDuplicated": "Emepụtara ọrụ",
+ "projectDuplicatedDescription": "Emepụtara ọrụ nke ọma.",
+ "failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
+ "newProjectName": "Aha Ọrụ Ọhụrụ",
+ "duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ"
}
diff --git a/src/locales/pt.json b/src/locales/pt.json
index e0cbdd3c..01aa8395 100644
--- a/src/locales/pt.json
+++ b/src/locales/pt.json
@@ -89,11 +89,10 @@
"name": "Nome",
"id": "ID",
"email": "Email",
- "buildNostrApps": "Construa aplicativos com IA",
- "whatToBuild": "O que você gostaria de construir?",
+ "buildApps": "Construa aplicativos com IA",
"chooseModel": "Escolha um modelo...",
- "selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...",
- "examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...",
+ "selectModelToDescribe": "Selecione um modelo abaixo para começar...",
+ "examplePrompt": "Descreva o que você gostaria de construir...",
"settingsDescription": "Gerencie as configurações e preferências da aplicação.",
"aiSettings": "IA",
"aiSettingsDescription": "Configure provedores de IA e chaves de API",
@@ -455,5 +454,32 @@
"selectLabels": "Selecionar etiquetas",
"noLabelsCreated": "Nenhuma etiqueta criada ainda",
"createNewLabel": "Criar nova etiqueta",
- "otherProjects": "Outros projetos"
+ "otherProjects": "Outros projetos",
+ "discoverPlugins": "Descobrir Plugins",
+ "discoverPluginsDescription": "Navegue e instale plugins do Shakespeare compartilhados na rede Nostr.",
+ "searchPlugins": "Buscar plugins...",
+ "noPluginsFound": "Nenhum plugin encontrado correspondente à sua busca.",
+ "noPluginsAvailable": "Nenhum plugin disponível no momento.",
+ "pluginInstalled": "Plugin Instalado",
+ "pluginInstalledDescription": "Plugin \"{{name}}\" foi instalado com sucesso.",
+ "pluginInstallFailed": "Falha ao Instalar Plugin",
+ "noCloneUrl": "Sem URL de Clone",
+ "noCloneUrlDescription": "Este plugin não tem uma URL de clone configurada.",
+ "installed": "Instalado",
+ "install": "Instalar",
+ "installing": "Instalando...",
+ "by": "por",
+ "website": "Site",
+ "loginRequired": "Login Necessário",
+ "loginToDiscoverPlugins": "Faça login com Nostr para descobrir plugins de pessoas que você segue.",
+ "noPluginsFromNetwork": "Nenhum Plugin Encontrado",
+ "noPluginsFromNetworkDescription": "Nenhum plugin encontrado de pessoas que você segue. Siga desenvolvedores de plugins no Nostr para ver seus plugins aqui.",
+ "tryDifferentSearch": "Tente um termo de busca diferente.",
+ "duplicateProject": "Duplicar Projeto",
+ "duplicatingProject": "Duplicando projeto...",
+ "projectDuplicated": "Projeto duplicado",
+ "projectDuplicatedDescription": "O projeto foi duplicado com sucesso.",
+ "failedToDuplicateProject": "Falha ao duplicar projeto",
+ "newProjectName": "Nome do Novo Projeto",
+ "duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome"
}
diff --git a/src/locales/yo.json b/src/locales/yo.json
index 3a220ade..2bdd9e7e 100644
--- a/src/locales/yo.json
+++ b/src/locales/yo.json
@@ -89,11 +89,10 @@
"name": "Orukọ",
"id": "ID",
"email": "Imeeli",
- "buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
- "whatToBuild": "Kini o fẹ kọ?",
+ "buildApps": "Kọ awọn ohun elo pẹlu AI",
"chooseModel": "Yan awoṣe...",
- "selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...",
- "examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...",
+ "selectModelToDescribe": "Yan awoṣe ni isalẹ lati bẹrẹ...",
+ "examplePrompt": "Ṣapejuwe ohun ti o fẹ kọ...",
"settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.",
"aiSettings": "AI",
"aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API",
@@ -443,5 +442,32 @@
"selectLabels": "Yan àmì",
"noLabelsCreated": "A kò tí ì ṣẹ̀dá àmì kankan",
"createNewLabel": "Ṣẹ̀dá àmì tuntun",
- "otherProjects": "Àwọn iṣẹ́ mìíràn"
+ "otherProjects": "Àwọn iṣẹ́ mìíràn",
+ "discoverPlugins": "Ṣawari Awọn Plugins",
+ "discoverPluginsDescription": "Ṣayẹwo ati fi sori ẹrọ awọn plugins Shakespeare ti a pin lori nẹtiwọọki Nostr.",
+ "searchPlugins": "Wa awọn plugins...",
+ "noPluginsFound": "Ko si awọn plugins ti o baamu wiwa rẹ.",
+ "noPluginsAvailable": "Ko si awọn plugins ti o wa ni akoko yii.",
+ "pluginInstalled": "Plugin Ti Fi Sori Ẹrọ",
+ "pluginInstalledDescription": "A ti fi plugin \"{{name}}\" sori ẹrọ ni aṣeyọri.",
+ "pluginInstallFailed": "O Kuna Lati Fi Plugin Sori Ẹrọ",
+ "noCloneUrl": "Ko Si Clone URL",
+ "noCloneUrlDescription": "Plugin yii ko ni clone URL ti a ṣeto.",
+ "installed": "Ti Fi Sori Ẹrọ",
+ "install": "Fi Sori Ẹrọ",
+ "installing": "N Fi Sori Ẹrọ...",
+ "by": "nipasẹ",
+ "website": "Oju opo wẹẹbu",
+ "loginRequired": "Wiwọle Nilo",
+ "loginToDiscoverPlugins": "Wọle pẹlu Nostr lati ṣawari awọn plugins lati ọdọ awọn eniyan ti o ntẹle.",
+ "noPluginsFromNetwork": "Ko Ri Plugins",
+ "noPluginsFromNetworkDescription": "Ko ri awọn plugins lati ọdọ awọn eniyan ti o ntẹle. Tẹle awọn olupilẹṣẹ plugin lori Nostr lati rii awọn plugins wọn nibi.",
+ "tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran.",
+ "duplicateProject": "Ṣe Ẹda Iṣẹ Akanṣe",
+ "duplicatingProject": "N ṣe ẹda iṣẹ akanṣe...",
+ "projectDuplicated": "Iṣẹ akanṣe ti ṣe ẹda",
+ "projectDuplicatedDescription": "Iṣẹ akanṣe ti ṣe ẹda ni aṣeyọri.",
+ "failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
+ "newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
+ "duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index ae006857..a6d4d390 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -89,11 +89,10 @@
"name": "名称",
"id": "ID",
"email": "邮箱",
- "buildNostrApps": "使用AI构建应用",
- "whatToBuild": "您想构建什么?",
+ "buildApps": "使用AI构建应用",
"chooseModel": "选择模型...",
- "selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...",
- "examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...",
+ "selectModelToDescribe": "请选择下方的模型以开始...",
+ "examplePrompt": "描述您想要构建的内容...",
"settingsDescription": "管理您的应用程序设置和偏好。",
"aiSettings": "AI",
"aiSettingsDescription": "配置AI提供商和API密钥",
@@ -455,5 +454,32 @@
"selectLabels": "选择标签",
"noLabelsCreated": "尚未创建标签",
"createNewLabel": "创建新标签",
- "otherProjects": "其他项目"
+ "otherProjects": "其他项目",
+ "discoverPlugins": "发现插件",
+ "discoverPluginsDescription": "浏览并安装在 Nostr 网络上共享的 Shakespeare 插件。",
+ "searchPlugins": "搜索插件...",
+ "noPluginsFound": "未找到与您搜索匹配的插件。",
+ "noPluginsAvailable": "目前没有可用的插件。",
+ "pluginInstalled": "插件已安装",
+ "pluginInstalledDescription": "插件 \"{{name}}\" 已成功安装。",
+ "pluginInstallFailed": "安装插件失败",
+ "noCloneUrl": "无克隆 URL",
+ "noCloneUrlDescription": "此插件未配置克隆 URL。",
+ "installed": "已安装",
+ "install": "安装",
+ "installing": "安装中...",
+ "by": "作者",
+ "website": "网站",
+ "loginRequired": "需要登录",
+ "loginToDiscoverPlugins": "使用 Nostr 登录以发现您关注的人的插件。",
+ "noPluginsFromNetwork": "未找到插件",
+ "noPluginsFromNetworkDescription": "未找到您关注的人的插件。在 Nostr 上关注插件开发者以在此处查看他们的插件。",
+ "tryDifferentSearch": "尝试不同的搜索词。",
+ "duplicateProject": "复制项目",
+ "duplicatingProject": "正在复制项目...",
+ "projectDuplicated": "项目已复制",
+ "projectDuplicatedDescription": "项目已成功复制。",
+ "failedToDuplicateProject": "复制项目失败",
+ "newProjectName": "新项目名称",
+ "duplicateProjectDescription": "使用新名称创建此项目的副本"
}
diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx
index 43181dd9..9f23a23a 100644
--- a/src/pages/AISettings.tsx
+++ b/src/pages/AISettings.tsx
@@ -1,6 +1,6 @@
import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit } from 'lucide-react';
+import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, ExternalLink } from 'lucide-react';
import {
DndContext,
closestCenter,
@@ -420,24 +420,13 @@ export function AISettings() {
return (
-
-
- }
- />
-
{preset.name}
-
- {(preset.apiKeysURL && preset.id !== "routstr") && (
-
- )}
+
+ }
+ />
+
{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] && (
+
+ )}
+
)}