Add APK Builder deploy provider

Adds support for building Android APKs from web projects via a self-hosted
Capacitor-based build service.

- Add APKBuilderAdapter for communicating with build server
- Add APKBuilderDeployForm component for app name/package ID config
- Add zip command for creating archives in terminal
- Integrate APK Builder into deploy settings and deploy flow

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
This commit is contained in:
Derek RossandClaude Opus 4.5 committed 2026-01-03 15:35:12 -05:00
1 parent cb3fb88a75
commit 72c9fc6989
14 files changed
+833 -13

No files matched your search

+23 -4
View File
@@ -22,7 +22,7 @@ import { Link } from 'react-router-dom';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
name: string;
description: string;
requiresNostr?: boolean;
@@ -32,6 +32,7 @@ interface PresetProvider {
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
buildServerUrlLabel?: string;
proxy?: boolean;
}
@@ -50,7 +51,7 @@ interface AddProviderDialogProps {
oauthHook: OAuthHook | null;
forceManualEntry: boolean;
onSetForceManualEntry: (force: boolean) => void;
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
}
function getProviderUrl(preset: PresetProvider): string | null {
@@ -67,6 +68,8 @@ function getProviderUrl(preset: PresetProvider): string | null {
return 'https://deno.com';
case 'nsite':
return null;
case 'apkbuilder':
return null;
default:
return null;
}
@@ -86,6 +89,7 @@ export function AddProviderDialog({
const [apiKey, setApiKey] = useState('');
const [accountId, setAccountId] = useState('');
const [organizationId, setOrganizationId] = useState('');
const [buildServerUrl, setBuildServerUrl] = useState('');
const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
@@ -93,10 +97,11 @@ export function AddProviderDialog({
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey, accountId, organizationId);
onAdd(apiKey, accountId, organizationId, buildServerUrl);
setApiKey('');
setAccountId('');
setOrganizationId('');
setBuildServerUrl('');
onOpenChange(false);
};
@@ -225,6 +230,19 @@ export function AddProviderDialog({
urlTitle="Find ID"
/>
)}
{preset.type === 'apkbuilder' && (
<ExternalInput
type="text"
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
value={buildServerUrl}
onChange={(e) => setBuildServerUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
handleAdd();
}
}}
/>
)}
<ExternalInput
type="password"
placeholder={preset.apiKeyLabel || t('enterApiKey')}
@@ -257,7 +275,8 @@ export function AddProviderDialog({
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
(preset.type === 'cloudflare' && !accountId.trim()) ||
(preset.type === 'deno' && !organizationId.trim())
(preset.type === 'deno' && !organizationId.trim()) ||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
}
>
{t('add')}
+47 -1
View File
@@ -19,7 +19,7 @@ import { ExternalFavicon } from '@/components/ExternalFavicon';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
name: string;
description: string;
requiresNostr?: boolean;
@@ -29,6 +29,7 @@ interface PresetProvider {
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
buildServerUrlLabel?: string;
proxy?: boolean;
}
@@ -97,6 +98,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul
// nsite uses Rocket icon fallback
return null;
case 'apkbuilder':
// APK Builder - check for custom buildServerUrl
if ('buildServerUrl' in provider && provider.buildServerUrl) {
return provider.buildServerUrl;
}
return null;
default:
return null;
}
@@ -183,6 +191,44 @@ export function ProviderConfigDialog({
/>
</div>
</>
) : localProvider.type === 'apkbuilder' ? (
<>
<div className="grid gap-2">
<Label htmlFor="provider-buildServerUrl">
{preset?.buildServerUrlLabel || 'Build Server URL'} <span className="text-destructive">*</span>
</Label>
<Input
id="provider-buildServerUrl"
placeholder="https://apk-builder.example.com"
value={localProvider.buildServerUrl || ''}
onChange={(e) => setLocalProvider({ ...localProvider, buildServerUrl: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">
{preset?.apiKeyLabel || 'API Key'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="provider-apiKey"
placeholder="Enter API Key"
value={localProvider.apiKey}
onChange={(e) => setLocalProvider({ ...localProvider, apiKey: e.target.value })}
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="provider-proxy"
checked={localProvider.proxy || false}
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
/>
<Label
htmlFor="provider-proxy"
className="text-sm font-normal cursor-pointer"
>
Use CORS Proxy
</Label>
</div>
</>
) : localProvider.type === 'nsite' ? (
<>
<div className="grid gap-2">
@@ -0,0 +1,198 @@
import { useState, useEffect, useCallback } from 'react';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { proxyUrl } from '@/lib/proxyUrl';
interface APKBuilderDeployFormProps {
buildServerUrl: string;
apiKey: string;
projectId: string;
projectName?: string;
savedAppName?: string;
savedPackageId?: string;
onConfigChange: (appName: string, packageId: string) => void;
corsProxy?: string;
}
interface ServerHealth {
status: 'ok' | 'error';
version?: string;
queue?: {
running: number;
queued: number;
};
}
export function APKBuilderDeployForm({
buildServerUrl,
apiKey,
projectId,
projectName,
savedAppName,
savedPackageId,
onConfigChange,
corsProxy,
}: APKBuilderDeployFormProps) {
const [appName, setAppName] = useState(savedAppName || projectName || projectId);
const [packageId, setPackageId] = useState(savedPackageId || '');
const [packageIdError, setPackageIdError] = useState<string | null>(null);
const [serverHealth, setServerHealth] = useState<ServerHealth | null>(null);
const [isCheckingServer, setIsCheckingServer] = useState(true);
// Generate default package ID from project name
useEffect(() => {
if (!savedPackageId && !packageId) {
const safeName = (projectName || projectId)
.toLowerCase()
.replace(/[^a-z0-9]/g, '');
setPackageId(`com.app.${safeName}`);
}
}, [projectName, projectId, savedPackageId, packageId]);
// Check server health
const checkServerHealth = useCallback(async () => {
setIsCheckingServer(true);
try {
const url = `${buildServerUrl}/health`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: {
'X-API-Key': apiKey,
},
});
if (response.ok) {
const data = await response.json();
setServerHealth({ status: 'ok', ...data });
} else {
setServerHealth({ status: 'error' });
}
} catch {
setServerHealth({ status: 'error' });
} finally {
setIsCheckingServer(false);
}
}, [buildServerUrl, apiKey, corsProxy]);
useEffect(() => {
checkServerHealth();
}, [checkServerHealth]);
// Validate package ID
const validatePackageId = (value: string): boolean => {
// Android package ID rules:
// - Must have at least two segments (e.g., com.example)
// - Each segment must start with a letter
// - Can only contain letters, numbers, and underscores
const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i;
return pattern.test(value);
};
// Handle package ID change with validation
const handlePackageIdChange = (value: string) => {
setPackageId(value);
if (value && !validatePackageId(value)) {
setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)');
} else {
setPackageIdError(null);
}
};
// Notify parent of config changes
useEffect(() => {
if (appName && packageId && !packageIdError) {
onConfigChange(appName, packageId);
}
}, [appName, packageId, packageIdError, onConfigChange]);
return (
<div className="space-y-4">
{/* Server Status */}
<div className="rounded-lg border p-3">
<div className="flex items-center gap-2">
{isCheckingServer ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : serverHealth?.status === 'ok' ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<XCircle className="h-4 w-4 text-red-500" />
)}
<div className="flex-1">
<p className="text-sm font-medium">
{isCheckingServer
? 'Checking build server...'
: serverHealth?.status === 'ok'
? 'Build server connected'
: 'Build server unavailable'}
</p>
{serverHealth?.status === 'ok' && serverHealth.queue && (
<p className="text-xs text-muted-foreground">
{serverHealth.queue.running > 0
? `${serverHealth.queue.running} build(s) in progress`
: 'Ready to build'}
{serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`}
</p>
)}
</div>
</div>
</div>
{serverHealth?.status === 'error' && (
<Alert variant="destructive">
<AlertDescription>
Cannot connect to build server. Check your server URL and API key in Deploy Settings.
</AlertDescription>
</Alert>
)}
{/* App Name */}
<div className="space-y-2">
<Label htmlFor="app-name">App Name</Label>
<Input
id="app-name"
value={appName}
onChange={(e) => setAppName(e.target.value)}
placeholder="My App"
/>
<p className="text-xs text-muted-foreground">
This name appears on the Android home screen
</p>
</div>
{/* Package ID */}
<div className="space-y-2">
<Label htmlFor="package-id">Package ID</Label>
<Input
id="package-id"
value={packageId}
onChange={(e) => handlePackageIdChange(e.target.value)}
placeholder="com.example.myapp"
className={packageIdError ? 'border-red-500' : ''}
/>
{packageIdError ? (
<p className="text-xs text-red-500">{packageIdError}</p>
) : (
<p className="text-xs text-muted-foreground">
Unique identifier for your app (e.g., com.yourcompany.appname)
</p>
)}
</div>
{/* Build Info */}
<div className="rounded-lg bg-muted/50 p-3 space-y-1">
<p className="text-xs text-muted-foreground">
<strong>Build type:</strong> Debug APK (sideloading)
</p>
<p className="text-xs text-muted-foreground">
<strong>Output:</strong> Downloadable .apk file
</p>
<p className="text-xs text-muted-foreground">
App icon will be auto-detected from your project
</p>
</div>
</div>
);
}
+73 -1
View File
@@ -21,6 +21,7 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
@@ -29,6 +30,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
import { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter';
/**
* Helper function to get provider URL for favicon
@@ -68,6 +70,9 @@ function getProviderUrl(provider: DeployProvider): string | null {
case 'nsite':
return null;
case 'apkbuilder':
return null; // No favicon for custom build server
default:
return null;
}
@@ -124,6 +129,11 @@ interface DenoDeployFormData {
projectName: string;
}
interface APKBuilderFormData {
appName: string;
packageId: string;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -161,6 +171,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
appName: projectName || projectId,
packageId: '',
});
// Load project settings when component mounts
useEffect(() => {
@@ -284,6 +298,29 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'apkbuilder') {
const apkBuilderProvider = selectedProvider;
if (!apkBuilderProvider.buildServerUrl) {
throw new Error('APK Builder server URL is required');
}
if (!apkBuilderProvider.apiKey) {
throw new Error('APK Builder API key is required');
}
if (!apkBuilderForm.appName) {
throw new Error('App name is required');
}
if (!apkBuilderForm.packageId) {
throw new Error('Package ID is required');
}
adapter = new APKBuilderAdapter({
fs,
buildServerUrl: apkBuilderProvider.buildServerUrl,
apiKey: apkBuilderProvider.apiKey,
appName: apkBuilderForm.appName,
packageId: apkBuilderForm.packageId,
corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -343,6 +380,15 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'apkbuilder') {
await updateProjectSettings(selectedProviderId, {
type: 'apkbuilder',
url: result.url,
data: {
appName: apkBuilderForm.appName,
packageId: apkBuilderForm.packageId,
},
});
}
setDeployResult(result);
@@ -364,6 +410,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
setApkBuilderForm({ appName: projectName || projectId, packageId: '' });
onClose();
};
@@ -395,6 +442,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDenoDeployForm({ projectName });
}, []);
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string) => {
setApkBuilderForm({ appName, packageId });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -500,6 +551,26 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
);
}
if (selectedProvider.type === 'apkbuilder') {
const apkBuilderProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined;
const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined;
return (
<APKBuilderDeployForm
buildServerUrl={apkBuilderProvider.buildServerUrl}
apiKey={apkBuilderProvider.apiKey}
projectId={projectId}
projectName={projectName}
savedAppName={savedAppName}
savedPackageId={savedPackageId}
onConfigChange={handleApkBuilderConfigChange}
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -673,7 +744,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId))
}
className="w-full"
>
+8 -1
View File
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface APKBuilderProvider extends BaseDeployProvider {
type: 'apkbuilder';
buildServerUrl: string;
apiKey: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
export interface DeploySettings {
providers: DeployProvider[];
+11
View File
@@ -52,6 +52,15 @@ const denoDeployProjectConfigSchema = z.object({
}),
});
const apkBuilderProjectConfigSchema = z.object({
type: z.literal('apkbuilder'),
url: z.string(),
data: z.object({
appName: z.string(),
packageId: z.string(),
}),
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
nsiteProjectConfigSchema,
@@ -59,6 +68,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
apkBuilderProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -72,6 +82,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
export type APKBuilderProjectConfig = z.infer<typeof apkBuilderProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
+2 -1
View File
@@ -29,4 +29,5 @@ export { UniqCommand } from './uniq';
export { WcCommand } from './wc';
export { WhoamiCommand } from './whoami';
export { WhichCommand } from './which';
export { UnzipCommand } from './unzip';
export { UnzipCommand } from './unzip';
export { ZipCommand } from './zip';
+226
View File
@@ -0,0 +1,226 @@
import { join, dirname, basename, normalize } from "path-browserify";
import JSZip from "jszip";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'zip' command
* Create ZIP archives from files and directories
*/
export class ZipCommand implements ShellCommand {
name = 'zip';
description = 'Create ZIP archives';
usage = 'zip [-r] [-q] archive.zip file1 [file2 ...]\n -r Recurse into directories\n -q Quiet mode';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
}
let archivePath = '';
let recursive = false;
let quiet = false;
const filesToAdd: string[] = [];
// Parse command line options
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-r') {
recursive = true;
} else if (arg === '-q') {
quiet = true;
} else if (arg === '-rq' || arg === '-qr') {
recursive = true;
quiet = true;
} else if (arg.startsWith('-')) {
// Check for combined flags like -rq
const flags = arg.slice(1);
let validFlags = true;
for (const flag of flags) {
if (flag === 'r') recursive = true;
else if (flag === 'q') quiet = true;
else {
validFlags = false;
break;
}
}
if (!validFlags) {
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
}
} else if (!archivePath) {
// First non-option is the archive path
archivePath = arg;
} else {
// Remaining arguments are files to add
filesToAdd.push(arg);
}
}
if (!archivePath) {
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
}
if (filesToAdd.length === 0) {
return createErrorResult(`${this.name}: no files to add\nUsage: ${this.usage}`);
}
// Ensure archive has .zip extension
if (!archivePath.toLowerCase().endsWith('.zip')) {
archivePath += '.zip';
}
try {
// Resolve archive path
const absoluteArchivePath = this.resolvePath(archivePath, cwd);
// Security check
if (!this.isPathAllowed(absoluteArchivePath, cwd)) {
return createErrorResult(`${this.name}: cannot create archive outside allowed paths`);
}
// Create parent directory if needed
const parentDir = dirname(absoluteArchivePath);
try {
await this.fs.stat(parentDir);
} catch {
await this.fs.mkdir(parentDir, { recursive: true });
}
const zip = new JSZip();
const addedFiles: string[] = [];
const errors: string[] = [];
// Add each file/directory to the archive
for (const filePath of filesToAdd) {
const absolutePath = this.resolvePath(filePath, cwd);
try {
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
if (recursive) {
await this.addDirectoryToZip(zip, absolutePath, basename(absolutePath), addedFiles, quiet);
} else {
errors.push(`${this.name}: ${filePath}: Is a directory (use -r to include)`);
}
} else if (stats.isFile()) {
const content = await this.fs.readFile(absolutePath);
const entryName = basename(absolutePath);
zip.file(entryName, content);
if (!quiet) {
addedFiles.push(` adding: ${entryName}`);
}
}
} catch {
errors.push(`${this.name}: ${filePath}: No such file or directory`);
}
}
if (addedFiles.length === 0 && errors.length > 0) {
return createErrorResult(errors.join('\n'));
}
// Generate the ZIP file
const zipContent = await zip.generateAsync({
type: 'uint8array',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
});
// Write the ZIP file
await this.fs.writeFile(absoluteArchivePath, zipContent);
// Build output
let output = '';
if (!quiet) {
output = addedFiles.join('\n');
if (output) {
output += '\n';
}
const sizeKB = (zipContent.length / 1024).toFixed(1);
output += `Created: ${archivePath} (${sizeKB} KB)`;
}
if (errors.length > 0) {
return createErrorResult(output + (output ? '\n' : '') + errors.join('\n'));
}
return createSuccessResult(output);
} catch (error) {
if (error instanceof Error) {
return createErrorResult(`${this.name}: ${error.message}`);
}
return createErrorResult(`${this.name}: Unknown error`);
}
}
/**
* Recursively add a directory to the ZIP archive
*/
private async addDirectoryToZip(
zip: JSZip,
dirPath: string,
zipPath: string,
addedFiles: string[],
quiet: boolean
): Promise<void> {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
const entryZipPath = join(zipPath, entry.name);
if (entry.isDirectory()) {
// Add directory entry and recurse
zip.folder(entryZipPath);
await this.addDirectoryToZip(zip, fullPath, entryZipPath, addedFiles, quiet);
} else if (entry.isFile()) {
try {
const content = await this.fs.readFile(fullPath);
zip.file(entryZipPath, content);
if (!quiet) {
addedFiles.push(` adding: ${entryZipPath}`);
}
} catch {
// Skip files we can't read
}
}
}
}
/**
* Resolve a path relative to cwd
*/
private resolvePath(filePath: string, cwd: string): string {
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
return normalize(filePath);
}
return normalize(join(cwd, filePath));
}
/**
* Check if a path is within allowed directories (cwd or /tmp)
*/
private isPathAllowed(targetPath: string, cwd: string): boolean {
const normalizedPath = normalize(targetPath);
const normalizedCwd = normalize(cwd);
const tmpPath = '/tmp';
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
return absolutePath.startsWith(absoluteCwd + '/') ||
absolutePath === absoluteCwd ||
absolutePath.startsWith(tmpPath + '/') ||
absolutePath === tmpPath;
}
}
+7
View File
@@ -129,6 +129,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
baseDomain: z.string().optional(),
});
const apkBuilderProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('apkbuilder'),
buildServerUrl: z.string().url(),
apiKey: z.string(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
@@ -136,6 +142,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
apkBuilderProviderSchema,
]);
const deploySettingsSchema = z.object({
+179
View File
@@ -0,0 +1,179 @@
import JSZip from 'jszip';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface APKBuildStatus {
id: string;
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
progress: number;
error?: string;
apkSize?: number;
logs?: string[];
}
/**
* APK Builder Deploy Adapter
* Builds Android APKs from web projects using a Capacitor build service
*/
export class APKBuilderAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private buildServerUrl: string;
private apiKey: string;
private appName: string;
private packageId: string;
private corsProxy?: string;
private onProgress?: (status: APKBuildStatus) => void;
constructor(config: APKBuilderDeployConfig) {
this.fs = config.fs;
this.buildServerUrl = config.buildServerUrl.replace(/\/$/, '');
this.apiKey = config.apiKey;
this.appName = config.appName;
this.packageId = config.packageId;
this.corsProxy = config.corsProxy;
this.onProgress = config.onProgress;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectPath } = options;
const distPath = `${projectPath}/dist`;
// Verify dist exists
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No dist folder found. Build the project first using the Build button.');
}
// Create ZIP of dist folder
const zip = new JSZip();
const distFolder = zip.folder('dist');
if (!distFolder) {
throw new Error('Failed to create ZIP folder');
}
await this.addDirectoryToZip(distPath, distFolder);
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Submit build request
const buildId = await this.submitBuild(zipBlob);
// Poll for completion
const result = await this.waitForBuild(buildId);
return result;
}
private async submitBuild(zipBlob: Blob): Promise<string> {
const url = `${this.buildServerUrl}/api/build`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const formData = new FormData();
formData.append('project', zipBlob, 'project.zip');
formData.append('config', JSON.stringify({
appName: this.appName,
packageId: this.packageId,
}));
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'X-API-Key': this.apiKey,
},
body: formData,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.buildId;
}
private async waitForBuild(buildId: string): Promise<DeployResult> {
const maxWait = 10 * 60 * 1000; // 10 minutes
const pollInterval = 3000; // 3 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
const status = await this.getStatus(buildId);
if (this.onProgress) {
this.onProgress(status);
}
if (status.status === 'complete') {
const downloadUrl = `${this.buildServerUrl}/api/build/${buildId}/download?apiKey=${encodeURIComponent(this.apiKey)}`;
return {
url: downloadUrl,
metadata: {
buildId,
type: 'apk',
appName: this.appName,
packageId: this.packageId,
apkSize: status.apkSize,
},
};
}
if (status.status === 'failed') {
throw new Error(status.error || 'APK build failed');
}
if (status.status === 'cancelled') {
throw new Error('APK build was cancelled');
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('APK build timed out after 10 minutes');
}
private async getStatus(buildId: string): Promise<APKBuildStatus> {
const url = `${this.buildServerUrl}/api/build/${buildId}/status`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'X-API-Key': this.apiKey,
},
});
if (!response.ok) {
throw new Error(`Failed to get build status: ${response.status}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
+1
View File
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './APKBuilderAdapter';
+22
View File
@@ -74,3 +74,25 @@ export interface DenoDeployConfig {
projectName?: string;
corsProxy?: string;
}
export interface APKBuilderDeployConfig {
fs: JSRuntimeFS;
/** URL of the APK build server */
buildServerUrl: string;
/** API key for the build server */
apiKey: string;
/** Display name of the Android app */
appName: string;
/** Android package ID (e.g., com.example.myapp) */
packageId: string;
/** Optional CORS proxy */
corsProxy?: string;
/** Optional progress callback */
onProgress?: (status: {
id: string;
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
progress: number;
error?: string;
logs?: string[];
}) => void;
}
+3 -1
View File
@@ -35,7 +35,8 @@ import {
UnzipCommand,
WcCommand,
WhoamiCommand,
WhichCommand
WhichCommand,
ZipCommand
} from "../commands";
interface ShellToolParams {
@@ -98,6 +99,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new TrCommand(fs));
this.registerCommand(new UniqCommand(fs));
this.registerCommand(new UnzipCommand(fs));
this.registerCommand(new ZipCommand(fs));
this.registerCommand(new WcCommand(fs));
this.registerCommand(new WhoamiCommand());
+33 -4
View File
@@ -32,7 +32,7 @@ import { CSS } from '@dnd-kit/utilities';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
name: string;
description: string;
requiresNostr?: boolean;
@@ -42,6 +42,7 @@ interface PresetProvider {
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
buildServerUrlLabel?: string;
proxy?: boolean;
}
@@ -201,6 +202,15 @@ const PRESET_PROVIDERS: PresetProvider[] = [
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
{
id: 'apkbuilder',
type: 'apkbuilder',
name: 'APK Builder',
description: 'Build Android APKs from your web app',
buildServerUrlLabel: 'Build Server URL',
apiKeyLabel: 'API Key',
proxy: true,
},
];
// Helper function to generate custom provider ID
@@ -267,6 +277,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul
// nsite uses Rocket icon fallback
return null;
case 'apkbuilder':
// For APK Builder, check for custom buildServerUrl
if ('buildServerUrl' in provider && provider.buildServerUrl) {
return provider.buildServerUrl;
}
return null;
default:
return null;
}
@@ -320,7 +337,7 @@ export function DeploySettings() {
setAddDialogOpen(true);
};
const handleAddPresetProvider = (preset: PresetProvider, apiKey: string, accountId?: string, organizationId?: string) => {
const handleAddPresetProvider = (preset: PresetProvider, apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => {
// For Shakespeare, just check if user is logged in
if (preset.requiresNostr && !user) {
return;
@@ -399,6 +416,18 @@ export function DeploySettings() {
organizationId: organizationId.trim(),
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'apkbuilder') {
if (!buildServerUrl?.trim() || !apiKey?.trim()) {
return;
}
newProvider = {
id: preset.id,
name: preset.name,
type: 'apkbuilder',
buildServerUrl: buildServerUrl.trim(),
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -536,8 +565,8 @@ export function DeploySettings() {
onSetForceManualEntry={(force) =>
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
}
onAdd={(apiKey, accountId, organizationId) =>
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId)
onAdd={(apiKey, accountId, organizationId, buildServerUrl) =>
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl)
}
/>
)}