Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: Xcode multi-platform template with deploy & screenshot scripts (#129)

[._.]/ Adam Eivy31040a1ccdd0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ff3b78528d..c32ed6aea9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,13 @@
+## Added
+
+- **Xcode Multi-Platform template** — new "Xcode Multi-Platform" app template scaffolds a SwiftUI project with iOS, macOS, and watchOS targets via XcodeGen
+ - Generic `deploy.sh` with `--ios`, `--macos`, `--watch`, `--all` flags for TestFlight deployment
+ - Generic `take_screenshots.sh` and `take_screenshots_macos.sh` for App Store screenshot automation
+ - UI test target with `ScreenshotTests.swift` stubs for XCUITest-based screenshot capture
+ - Shared module for cross-platform code, macOS entitlements, watchOS companion app
+- **Xcode script health check** — PortOS now detects missing management scripts (deploy, screenshots) in Xcode-managed apps and surfaces a banner in the app detail overview with one-click install
+- Deploy panel now includes `--watch` (watchOS) flag option
+
## Fixed
- Submodule status API (`/api/git/submodules/status`) always returned empty array — `stdout.trim()` was stripping the leading space status character from `git submodule status` output, causing the regex parser to fail
diff --git a/client/src/components/apps/DeployPanel.jsx b/client/src/components/apps/DeployPanel.jsx
index 901f83ca99..ac3a74d9af 100644
--- a/client/src/components/apps/DeployPanel.jsx
+++ b/client/src/components/apps/DeployPanel.jsx
@@ -6,11 +6,12 @@ import { useAppDeploy } from '../../hooks/useAppDeploy';
const FLAG_OPTIONS = [
{ value: '--ios', label: 'iOS' },
{ value: '--macos', label: 'macOS' },
+ { value: '--watch', label: 'watchOS' },
{ value: '--all', label: 'All Platforms' },
{ value: '--skip-tests', label: 'Skip Tests' },
];
-const PLATFORM_FLAGS = new Set(['--ios', '--macos', '--all']);
+const PLATFORM_FLAGS = new Set(['--ios', '--macos', '--watch', '--all']);
export default function DeployPanel({ appId, appName }) {
const { output, isDeploying, error, result, startDeploy, clearDeploy } = useAppDeploy();
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index ec5ffe7104..b2e1994ae4 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo } from 'react';
-import { FolderOpen, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Tag } from 'lucide-react';
+import { FolderOpen, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Tag, AlertTriangle, Rocket, Camera } from 'lucide-react';
import toast from '../../ui/Toast';
import { NON_PM2_TYPES } from '../constants';
import BrailleSpinner from '../../BrailleSpinner';
@@ -10,12 +10,19 @@ import SlashDoPanel from '../SlashDoPanel';
import { useAppOperation } from '../../../hooks/useAppOperation';
import * as api from '../../../services/api';
+const SCRIPT_ICONS = {
+ 'deploy.sh': Rocket,
+ 'take_screenshots.sh': Camera,
+ 'take_screenshots_macos.sh': Camera
+};
+
export default function OverviewTab({ app, onRefresh }) {
const [editingApp, setEditingApp] = useState(null);
const [refreshingConfig, setRefreshingConfig] = useState(false);
const [archiving, setArchiving] = useState(false);
const [jiraTickets, setJiraTickets] = useState(null);
const [loadingTickets, setLoadingTickets] = useState(false);
+ const [installingScripts, setInstallingScripts] = useState(false);
const onComplete = useMemo(() => () => onRefresh(), [onRefresh]);
const { steps, isOperating, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete });
@@ -43,6 +50,24 @@ export default function OverviewTab({ app, onRefresh }) {
const handleStandardize = () => startStandardize(app.id);
+ const missingScripts = app.xcodeScripts?.missing || [];
+
+ const handleInstallScripts = async (scriptNames) => {
+ setInstallingScripts(true);
+ const result = await api.installXcodeScripts(app.id, scriptNames).catch(() => null);
+ setInstallingScripts(false);
+ if (!result) return; // request() already showed error toast
+
+ if (result.installed?.length) {
+ toast.success(`Installed: ${result.installed.join(', ')}`);
+ onRefresh();
+ }
+
+ if (result.errors?.length) {
+ toast.error(`Some scripts could not be installed: ${result.errors.join(', ')}`);
+ }
+ };
+
const handleArchive = async () => {
setArchiving(true);
await api.archiveApp(app.id).catch(() => null);
@@ -90,6 +115,51 @@ export default function OverviewTab({ app, onRefresh }) {
)}
</div>
+ {/* Missing Xcode Scripts Banner */}
+ {missingScripts.length > 0 && (
+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-4">
+ <div className="flex items-start gap-3">
+ <AlertTriangle size={18} className="text-port-warning shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <div className="text-sm font-medium text-port-warning mb-2">
+ Missing management scripts
+ </div>
+ <div className="flex flex-wrap gap-2 mb-3">
+ {missingScripts.map(s => {
+ const Icon = SCRIPT_ICONS[s.name] || Terminal;
+ return (
+ <span key={s.name} className="inline-flex items-center gap-1.5 px-2 py-1 bg-port-card border border-port-border rounded text-xs text-gray-300">
+ <Icon size={12} />
+ <span className="font-mono">{s.name}</span>
+ <span className="text-gray-500">— {s.description}</span>
+ </span>
+ );
+ })}
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={() => handleInstallScripts(missingScripts.map(s => s.name))}
+ disabled={installingScripts}
+ className="px-3 py-1.5 bg-port-warning/20 text-port-warning hover:bg-port-warning/30 rounded text-xs font-medium disabled:opacity-50"
+ >
+ {installingScripts ? 'Installing...' : 'Install All'}
+ </button>
+ {missingScripts.length > 1 && missingScripts.map(s => (
+ <button
+ key={s.name}
+ onClick={() => handleInstallScripts([s.name])}
+ disabled={installingScripts}
+ className="px-2 py-1.5 bg-port-border hover:bg-port-border/80 text-gray-300 rounded text-xs disabled:opacity-50"
+ >
+ Install {s.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
{/* Start Commands */}
{app.startCommands?.length > 0 && (
<div>
diff --git a/client/src/pages/Templates.jsx b/client/src/pages/Templates.jsx
index d98fe61036..ff85a22a7f 100644
--- a/client/src/pages/Templates.jsx
+++ b/client/src/pages/Templates.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
-import { Layers, Code, Server, Globe, Smartphone, Plus } from 'lucide-react';
+import { Layers, Code, Server, Globe, Smartphone, MonitorSmartphone, Plus } from 'lucide-react';
import * as api from '../services/api';
import DirectoryPicker from '../components/DirectoryPicker';
@@ -9,7 +9,8 @@ const ICONS = {
code: Code,
server: Server,
globe: Globe,
- smartphone: Smartphone
+ smartphone: Smartphone,
+ 'monitor-smartphone': MonitorSmartphone
};
export default function Templates() {
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 9bef46f7fd..35a138d611 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -68,6 +68,10 @@ export const getAppLogs = (id, lines = 100, processName) => {
return request(`/apps/${id}/logs?${params}`);
};
+export const installXcodeScripts = (id, scripts) => request(`/apps/${id}/xcode-scripts/install`, {
+ method: 'POST',
+ body: JSON.stringify({ scripts })
+});
export const getAppDocuments = (id) => request(`/apps/${id}/documents`);
export const getAppDocument = (id, filename) => request(`/apps/${id}/documents/${filename}`);
export const saveAppDocument = (id, filename, content, commitMessage) =>
diff --git a/server/routes/apps.js b/server/routes/apps.js
index f9d1eaf563..e46f57d128 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -18,6 +18,7 @@ import { safeJSONParse } from '../lib/fileUtils.js';
import { parseEcosystemFromPath, usesPm2 } from '../services/streamingDetect.js';
import { detectAppIcon, getIconContentType } from '../services/appIconDetect.js';
import { hasDeployScript } from '../services/appDeployer.js';
+import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';
const router = Router();
@@ -71,7 +72,7 @@ router.get('/', asyncHandler(async (req, res) => {
const enriched = await Promise.all(apps.map(async (app) => {
// Non-PM2 apps skip PM2 enrichment entirely
if (!usesPm2(app.type)) {
- return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app) };
+ return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) };
}
const pm2Home = app.pm2Home || null;
@@ -125,7 +126,8 @@ router.get('/', asyncHandler(async (req, res) => {
apiPort,
pm2Status: statuses,
overallStatus,
- hasDeployScript: hasDeployScript(app)
+ hasDeployScript: hasDeployScript(app),
+ xcodeScripts: checkScripts(app)
};
}));
@@ -183,7 +185,25 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {
appVersion = pkg?.version || null;
}
- res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, pm2Status: statuses, appVersion, hasDeployScript: hasDeployScript(app) });
+ res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, pm2Status: statuses, appVersion, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });
+}));
+
+// POST /api/apps/:id/xcode-scripts/install - Install missing management scripts
+// Restrict the request payload to the known, fixed set of script names so that
+// arbitrary or oversized arrays are rejected at the validation layer.
+const installScriptsSchema = z.object({
+ scripts: z.array(z.enum(XCODE_SCRIPT_NAMES)).min(1).max(XCODE_SCRIPT_NAMES.length)
+});
+router.post('/:id/xcode-scripts/install', loadApp, asyncHandler(async (req, res) => {
+ const { scripts } = validateRequest(installScriptsSchema, req.body);
+ if (!req.loadedApp.repoPath || !existsSync(req.loadedApp.repoPath)) {
+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });
+ }
+ const result = await installScripts(req.loadedApp, scripts);
+ if (result.errors.length && !result.installed.length) {
+ throw new ServerError(result.errors.join(', '), { status: 400, code: 'INSTALL_FAILED' });
+ }
+ res.json(result);
}));
// GET /api/apps/:id/icon - Serve the app's detected icon image
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 6ff70c16d6..0779774476 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -58,12 +58,26 @@ vi.mock('../services/git.js', () => ({
commit: vi.fn()
}));
+vi.mock('../services/xcodeScripts.js', () => ({
+ checkScripts: vi.fn().mockReturnValue({ missing: [], present: [] }),
+ installScripts: vi.fn(),
+ XCODE_TEAM_ID: 'TEST_TEAM',
+ XCODE_BUNDLE_PREFIX: 'net.test',
+ XCODE_SCRIPT_NAMES: ['deploy.sh', 'take_screenshots.sh', 'take_screenshots_macos.sh'],
+ toBundleId: vi.fn(),
+ toTargetName: vi.fn(),
+ generateDeployScript: vi.fn(),
+ generateScreenshotScript: vi.fn(),
+ generateMacScreenshotScript: vi.fn()
+}));
+
// Import mocked modules
import * as appsService from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
import * as history from '../services/history.js';
import * as streamingDetect from '../services/streamingDetect.js';
import { detectAppIcon, getIconContentType } from '../services/appIconDetect.js';
+import { installScripts } from '../services/xcodeScripts.js';
import { writeFileSync, mkdirSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -639,4 +653,89 @@ describe('Apps Routes', () => {
expect(response.status).toBe(404);
});
});
+
+ describe('POST /api/apps/:id/xcode-scripts/install', () => {
+ it('should install requested scripts successfully', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });
+ installScripts.mockResolvedValue({ installed: ['deploy.sh'], skipped: [], errors: [] });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: ['deploy.sh'] });
+
+ expect(response.status).toBe(200);
+ expect(response.body.installed).toEqual(['deploy.sh']);
+ });
+
+ it('should return 400 when all scripts fail', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });
+ installScripts.mockResolvedValue({ installed: [], skipped: [], errors: ['some failure'] });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: ['deploy.sh'] });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INSTALL_FAILED');
+ });
+
+ it('should return 400 when scripts array contains an unknown name', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: ['bad.sh'] });
+
+ // Unknown script names are now rejected by the Zod enum validator
+ expect(response.status).toBe(400);
+ });
+
+ it('should return 400 when scripts array is empty', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: [] });
+
+ expect(response.status).toBe(400);
+ });
+
+ it('should return 404 when app not found', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app)
+ .post('/api/apps/app-999/xcode-scripts/install')
+ .send({ scripts: ['deploy.sh'] });
+
+ expect(response.status).toBe(404);
+ });
+
+ it('should return partial success with errors', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });
+ installScripts.mockResolvedValue({
+ installed: ['deploy.sh'],
+ skipped: [],
+ errors: ['Script take_screenshots_macos.sh does not apply to ios-native apps']
+ });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: ['deploy.sh', 'take_screenshots_macos.sh'] });
+
+ expect(response.status).toBe(200);
+ expect(response.body.installed).toEqual(['deploy.sh']);
+ expect(response.body.errors).toHaveLength(1);
+ });
+
+ it('should return 400 when repoPath does not exist', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/nonexistent/path' });
+
+ const response = await request(app)
+ .post('/api/apps/app-001/xcode-scripts/install')
+ .send({ scripts: ['deploy.sh'] });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('PATH_NOT_FOUND');
+ });
+ });
});
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 94a078f863..4ab5a776fd 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -12,6 +12,8 @@ import { ensureDir } from '../lib/fileUtils.js';
import { scaffoldVite } from './scaffoldVite.js';
import { scaffoldExpress } from './scaffoldExpress.js';
import { scaffoldIOS } from './scaffoldIOS.js';
+import { scaffoldXcode } from './scaffoldXcode.js';
+import { toTargetName } from '../services/xcodeScripts.js';
import { scaffoldPortOS } from './scaffoldPortOS.js';
const execAsync = promisify(exec);
@@ -126,6 +128,15 @@ router.get('/templates', asyncHandler(async (req, res) => {
icon: 'smartphone',
features: ['SwiftUI', 'SwiftData', 'XcodeGen', 'TestFlight CI/CD', 'On-device processing'],
ports: { ui: false, api: false }
+ },
+ {
+ id: 'xcode-multiplatform',
+ name: 'Xcode Multi-Platform',
+ description: 'SwiftUI app for iOS + macOS + watchOS with deploy & screenshot scripts',
+ type: 'xcode',
+ icon: 'monitor-smartphone',
+ features: ['SwiftUI', 'iOS + macOS + watchOS', 'XcodeGen', 'TestFlight Deploy', 'Screenshot Automation', 'UI Tests'],
+ ports: { ui: false, api: false }
}
];
@@ -213,7 +224,8 @@ async function scaffoldApp(req, res) {
'vite-express': { api: true, ui: true },
'vite-react': { api: false, ui: true },
'express-api': { api: true, ui: false },
- 'ios-native': { api: false, ui: false }
+ 'ios-native': { api: false, ui: false },
+ 'xcode-multiplatform': { api: false, ui: false }
};
const needs = templateNeedsPorts[template] || { api: false, ui: false };
@@ -259,6 +271,8 @@ async function scaffoldApp(req, res) {
await scaffoldExpress(repoPath, dirName, apiPort, addStep);
} else if (template === 'ios-native') {
await scaffoldIOS(repoPath, name, dirName, addStep);
+ } else if (template === 'xcode-multiplatform') {
+ await scaffoldXcode(repoPath, name, dirName, addStep);
} else if (template === 'portos-stack') {
await scaffoldPortOS(repoPath, name, dirName, uiPort, apiPort, addStep);
}
@@ -403,8 +417,8 @@ module.exports = {
addStep('Create PM2 config', 'done');
}
- // Run npm install (skip for iOS — no npm)
- if (template !== 'ios-native') {
+ // Run npm install (skip for Xcode projects — no npm)
+ if (template !== 'ios-native' && template !== 'xcode-multiplatform') {
const installCmd = template === 'portos-stack' ? 'npm run install:all' : 'npm install';
const { stderr: installErr } = await execAsync(installCmd, { cwd: repoPath, windowsHide: true })
.catch(err => ({ stderr: err.message }));
@@ -421,14 +435,18 @@ module.exports = {
// Create .gitignore
let gitignoreContent;
- if (template === 'ios-native') {
+ if (template === 'ios-native' || template === 'xcode-multiplatform') {
gitignoreContent = `# Build output
build/
+.build/
DerivedData/
# Environment files
.env
+# Screenshots config (generated by take_screenshots.sh)
+.screenshot_config.json
+
# OS files
.DS_Store
@@ -505,7 +523,8 @@ Thumbs.db
'vite-react': 'vite',
'vite-express': 'vite+express',
'express-api': 'single-node-server',
- 'ios-native': 'ios-native'
+ 'ios-native': 'ios-native',
+ 'xcode-multiplatform': 'xcode'
};
let pm2Names;
@@ -519,9 +538,15 @@ Thumbs.db
pm2Names = [`${dirName}-ui`, `${dirName}-api`];
startCmds = ['npm run dev:all'];
} else if (template === 'ios-native') {
+ const tn = toTargetName(name);
+ pm2Names = [];
+ startCmds = [`open ${tn}.xcodeproj`];
+ buildCmd = `xcodebuild build -project ${tn}.xcodeproj -scheme ${tn} -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO`;
+ } else if (template === 'xcode-multiplatform') {
+ const tn = toTargetName(name);
pm2Names = [];
- startCmds = [`open ${name.replace(/[^a-zA-Z0-9_]/g, '_')}.xcodeproj`];
- buildCmd = `xcodebuild build -project ${name.replace(/[^a-zA-Z0-9_]/g, '_')}.xcodeproj -scheme ${name.replace(/[^a-zA-Z0-9_]/g, '_')} -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO`;
+ startCmds = [`open ${tn}.xcodeproj`];
+ buildCmd = `xcodebuild build -project ${tn}.xcodeproj -scheme ${tn} -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO`;
} else {
pm2Names = [dirName];
startCmds = ['npm run dev'];
diff --git a/server/routes/scaffoldIOS.js b/server/routes/scaffoldIOS.js
index 1934a2495c..915358f4f4 100644
--- a/server/routes/scaffoldIOS.js
+++ b/server/routes/scaffoldIOS.js
@@ -3,18 +3,19 @@ import { join } from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
+import { XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, toBundleId, toTargetName } from '../services/xcodeScripts.js';
const execAsync = promisify(exec);
export async function scaffoldIOS(repoPath, name, dirName, addStep) {
- const bundleId = `net.shadowpuppet.${name.replace(/[^a-zA-Z0-9]/g, '')}`;
- const teamId = 'TYQ32QCF6K';
- const targetName = name.replace(/[^a-zA-Z0-9_]/g, '_');
+ const bundleId = toBundleId(name);
+ const teamId = XCODE_TEAM_ID;
+ const targetName = toTargetName(name);
// project.yml (XcodeGen source of truth)
await writeFile(join(repoPath, 'project.yml'), `name: ${targetName}
options:
- bundleIdPrefix: net.shadowpuppet
+ bundleIdPrefix: ${XCODE_BUNDLE_PREFIX}
deploymentTarget:
iOS: "17.0"
xcodeVersion: "16.0"
diff --git a/server/routes/scaffoldXcode.js b/server/routes/scaffoldXcode.js
new file mode 100644
index 0000000000..5082653d4c
--- /dev/null
+++ b/server/routes/scaffoldXcode.js
@@ -0,0 +1,457 @@
+import { writeFile, chmod } from 'fs/promises';
+import { join } from 'path';
+import { exec } from 'child_process';
+import { promisify } from 'util';
+import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
+import {
+ XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, XCODE_ENV_EXAMPLE,
+ toBundleId, toTargetName,
+ generateDeployScript, generateScreenshotScript, generateMacScreenshotScript
+} from '../services/xcodeScripts.js';
+
+const execAsync = promisify(exec);
+
+/**
+ * Scaffold a multi-platform Xcode project (iOS + macOS + watchOS)
+ * with XcodeGen, deploy script, and screenshot automation.
+ */
+export async function scaffoldXcode(repoPath, name, dirName, addStep) {
+ const bundleId = toBundleId(name);
+ const teamId = XCODE_TEAM_ID;
+ const targetName = toTargetName(name);
+ const watchTarget = `${targetName}_Watch`;
+
+ // project.yml — XcodeGen source of truth with iOS, macOS, and watchOS targets
+ await writeFile(join(repoPath, 'project.yml'), `name: ${targetName}
+options:
+ bundleIdPrefix: ${XCODE_BUNDLE_PREFIX}
+ deploymentTarget:
+ iOS: "17.0"
+ macOS: "14.0"
+ watchOS: "10.0"
+ xcodeVersion: "16.0"
+ generateEmptyDirectories: true
+
+settings:
+ base:
+ DEVELOPMENT_TEAM: ${teamId}
+ MARKETING_VERSION: "1.0.0"
+ CURRENT_PROJECT_VERSION: 1
+ SWIFT_VERSION: "5.9"
+
+targets:
+ # --- iOS Target ---
+ ${targetName}:
+ type: application
+ platform: iOS
+ sources:
+ - path: ${targetName}
+ excludes:
+ - Preview Content/PreviewAssets.xcassets
+ - path: ${targetName}/Preview Content/PreviewAssets.xcassets
+ buildPhase: none
+ - path: Shared
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}
+ INFOPLIST_FILE: ${targetName}/Info.plist
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
+ INFOPLIST_KEY_UISupportedInterfaceOrientations: "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
+ INFOPLIST_KEY_UILaunchScreen_Generation: true
+ DEVELOPMENT_ASSET_PATHS: "\\"${targetName}/Preview Content\\""
+ GENERATE_INFOPLIST_FILE: true
+ scheme:
+ testTargets:
+ - ${targetName}Tests
+ - ${targetName}UITests
+
+ # --- macOS Target ---
+ ${targetName} macOS:
+ type: application
+ platform: macOS
+ sources:
+ - path: ${targetName}
+ excludes:
+ - Preview Content/PreviewAssets.xcassets
+ - Info.plist
+ - path: Shared
+ entitlements:
+ path: ${targetName}-macOS.entitlements
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}
+ PRODUCT_NAME: ${targetName}
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
+ GENERATE_INFOPLIST_FILE: true
+
+ # --- watchOS Target ---
+ ${watchTarget}:
+ type: application
+ platform: watchOS
+ sources:
+ - path: ${watchTarget}
+ - path: Shared
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}.watchkitapp
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ INFOPLIST_KEY_WKCompanionAppBundleIdentifier: ${bundleId}
+ GENERATE_INFOPLIST_FILE: true
+ dependencies:
+ - target: ${targetName}
+ embed: false
+
+ # --- Unit Tests ---
+ ${targetName}Tests:
+ type: bundle.unit-test
+ platform: iOS
+ sources:
+ - path: ${targetName}Tests
+ dependencies:
+ - target: ${targetName}
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}Tests
+ GENERATE_INFOPLIST_FILE: true
+ TEST_HOST: "$(BUILT_PRODUCTS_DIR)/${targetName}.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/${targetName}"
+ BUNDLE_LOADER: "$(TEST_HOST)"
+
+ # --- UI Tests (screenshot automation) ---
+ ${targetName}UITests:
+ type: bundle.ui-testing
+ platform: iOS
+ sources:
+ - path: ${targetName}UITests
+ dependencies:
+ - target: ${targetName}
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}UITests
+ GENERATE_INFOPLIST_FILE: true
+ TEST_TARGET_NAME: ${targetName}
+`);
+
+ // Create source directories
+ const srcDir = join(repoPath, targetName);
+ const sharedDir = join(repoPath, 'Shared');
+ const watchDir = join(repoPath, watchTarget);
+ const previewDir = join(srcDir, 'Preview Content');
+ const testsDir = join(repoPath, `${targetName}Tests`);
+ const uiTestsDir = join(repoPath, `${targetName}UITests`);
+
+ await ensureDirs([srcDir, sharedDir, watchDir, previewDir, testsDir, uiTestsDir]);
+
+ // Info.plist (iOS)
+ await writeFile(join(srcDir, 'Info.plist'), `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict/>
+</plist>
+`);
+
+ // macOS entitlements
+ await writeFile(join(repoPath, `${targetName}-macOS.entitlements`), `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
+`);
+
+ // Shared module (cross-platform models/logic)
+ await writeFile(join(sharedDir, 'AppConstants.swift'), `import Foundation
+
+enum AppConstants {
+ static let appName = "${targetName}"
+ static let bundleId = "${bundleId}"
+}
+`);
+
+ // iOS/macOS App entry point (multi-platform)
+ await writeFile(join(srcDir, `${targetName}App.swift`), `import SwiftUI
+
+@main
+struct ${targetName}App: App {
+ var body: some Scene {
+ WindowGroup {
+ ContentView()
+ }
+ #if os(macOS)
+ .defaultSize(width: 900, height: 600)
+ #endif
+ }
+}
+`);
+
+ // ContentView with platform conditionals
+ await writeFile(join(srcDir, 'ContentView.swift'), `import SwiftUI
+
+struct ContentView: View {
+ var body: some View {
+ #if os(macOS)
+ NavigationSplitView {
+ List {
+ NavigationLink("Home", destination: HomeView())
+ }
+ .navigationSplitViewColumnWidth(min: 180, ideal: 200)
+ } detail: {
+ HomeView()
+ }
+ #else
+ NavigationStack {
+ HomeView()
+ }
+ #endif
+ }
+}
+
+struct HomeView: View {
+ var body: some View {
+ VStack(spacing: 20) {
+ Image(systemName: "app.fill")
+ .font(.system(size: 60))
+ .foregroundStyle(.blue)
+
+ Text(AppConstants.appName)
+ .font(.largeTitle)
+ .fontWeight(.bold)
+
+ Text("Built with PortOS")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ .navigationTitle(AppConstants.appName)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+}
+`);
+
+ // watchOS App
+ await writeFile(join(watchDir, `${watchTarget}App.swift`), `import SwiftUI
+
+@main
+struct ${watchTarget}App: App {
+ var body: some Scene {
+ WindowGroup {
+ WatchContentView()
+ }
+ }
+}
+`);
+
+ await writeFile(join(watchDir, 'WatchContentView.swift'), `import SwiftUI
+
+struct WatchContentView: View {
+ var body: some View {
+ VStack(spacing: 8) {
+ Image(systemName: "app.fill")
+ .font(.title)
+ .foregroundStyle(.blue)
+
+ Text(AppConstants.appName)
+ .font(.headline)
+ }
+ }
+}
+`);
+
+ // Asset catalogs
+ await ensureDir(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset'));
+ await writeFile(join(srcDir, 'Assets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
+ await writeFile(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), `{
+ "images": [{"idiom": "universal", "platform": "ios", "size": "1024x1024"}],
+ "info": {"version": 1, "author": "xcode"}
+}`);
+
+ await ensureDir(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset'));
+ await writeFile(join(watchDir, 'Assets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
+ await writeFile(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), `{
+ "images": [{"idiom": "universal", "platform": "watchos", "size": "1024x1024"}],
+ "info": {"version": 1, "author": "xcode"}
+}`);
+
+ await ensureDir(join(previewDir, 'PreviewAssets.xcassets'));
+ await writeFile(join(previewDir, 'PreviewAssets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
+
+ // Unit tests
+ await writeFile(join(testsDir, `${targetName}Tests.swift`), `import XCTest
+@testable import ${targetName}
+
+final class ${targetName}Tests: XCTestCase {
+ func testAppLaunches() {
+ XCTAssertTrue(true, "App scaffold is functional")
+ }
+}
+`);
+
+ // UI Tests with screenshot stubs
+ await writeFile(join(uiTestsDir, 'ScreenshotTests.swift'), `import XCTest
+
+final class ScreenshotTests: XCTestCase {
+
+ private var app: XCUIApplication!
+ private var config: [String: Any] = [:]
+
+ override func setUpWithError() throws {
+ continueAfterFailure = false
+ app = XCUIApplication()
+
+ let projectPath = ProcessInfo.processInfo.environment["PROJECT_DIR"]
+ ?? URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().path
+ let configPaths = [
+ "\\(projectPath)/.screenshot_config.json",
+ "/tmp/${targetName.toLowerCase()}_screenshot_config.json"
+ ]
+
+ for path in configPaths {
+ if let data = FileManager.default.contents(atPath: path),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
+ config = json
+ break
+ }
+ }
+
+ if let locale = config["locale"] as? String {
+ app.launchArguments += ["-AppleLanguages", "(\\(locale))", "-AppleLocale", locale]
+ }
+ if let currency = config["currency"] as? String {
+ app.launchArguments += ["-currencyCode", currency]
+ }
+ }
+
+ // MARK: - iPhone Screenshots
+
+ func testCaptureIPhoneScreenshots() throws {
+ app.launch()
+ let outputDir = screenshotOutputDir(device: config["device"] as? String ?? "iphone_6.7")
+ let targetScreen = config["target_screen"] as? String ?? ""
+
+ if targetScreen.isEmpty || targetScreen == "01_home" {
+ takeScreenshot(named: "01_home", outputDir: outputDir)
+ }
+ }
+
+ // MARK: - iPad Screenshots
+
+ func testCaptureIPadScreenshots() throws {
+ app.launch()
+ let outputDir = screenshotOutputDir(device: config["device"] as? String ?? "ipad_13")
+ let targetScreen = config["target_screen"] as? String ?? ""
+
+ if targetScreen.isEmpty || targetScreen == "01_home" {
+ takeScreenshot(named: "01_home", outputDir: outputDir)
+ }
+ }
+
+ // MARK: - Helpers
+
+ private func screenshotOutputDir(device: String) -> String {
+ let base = config["output_dir"] as? String ?? "screenshots"
+ let locale = config["locale"] as? String ?? "en"
+ return "\\(base)/\\(locale)/\\(device)"
+ }
+
+ private func takeScreenshot(named name: String, outputDir: String) {
+ let screenshot = app.screenshot()
+ let fm = FileManager.default
+ try? fm.createDirectory(atPath: outputDir, withIntermediateDirectories: true, attributes: nil)
+ let path = "\\(outputDir)/\\(name).png"
+ try? screenshot.pngRepresentation.write(to: URL(fileURLWithPath: path))
+ }
+}
+`);
+
+ // .env.example
+ await writeFile(join(repoPath, '.env.example'), XCODE_ENV_EXAMPLE);
+
+ // Scripts (from generators in xcodeScripts service)
+ await writeFile(join(repoPath, 'deploy.sh'), generateDeployScript(targetName, bundleId));
+ await writeFile(join(repoPath, 'take_screenshots.sh'), generateScreenshotScript(targetName, bundleId));
+ await writeFile(join(repoPath, 'take_screenshots_macos.sh'), generateMacScreenshotScript(targetName, bundleId));
+
+ if (process.platform !== 'win32') {
+ await Promise.all([
+ chmod(join(repoPath, 'deploy.sh'), 0o755),
+ chmod(join(repoPath, 'take_screenshots.sh'), 0o755),
+ chmod(join(repoPath, 'take_screenshots_macos.sh'), 0o755),
+ ]);
+ }
+
+ // CLAUDE.md
+ await writeFile(join(repoPath, 'CLAUDE.md'), `# ${name}
+
+Multi-platform native app built with SwiftUI (iOS + macOS + watchOS) and XcodeGen.
+
+## Tech Stack
+
+- **SwiftUI** + **SwiftData** (iOS 17.0+, macOS 14.0+, watchOS 10.0+)
+- **XcodeGen** for project generation (\`project.yml\` is the source of truth, not the \`.xcodeproj\`)
+- Bundle ID: \`${bundleId}\`, Team: \`${teamId}\`
+
+## Build Commands
+
+\`\`\`bash
+# Generate Xcode project (required after changing project.yml)
+xcodegen generate
+
+# Build iOS
+xcodebuild build -project ${targetName}.xcodeproj -scheme ${targetName} \\
+ -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
+
+# Build macOS
+xcodebuild build -project ${targetName}.xcodeproj -scheme "${targetName} macOS" \\
+ CODE_SIGNING_ALLOWED=NO
+
+# Run tests
+xcodebuild test -project ${targetName}.xcodeproj -scheme ${targetName} \\
+ -only-testing:${targetName}Tests \\
+ -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
+\`\`\`
+
+## TestFlight Deployment
+
+Local deploy via \`./deploy.sh\`:
+
+\`\`\`bash
+./deploy.sh # iOS only (default)
+./deploy.sh --macos # macOS only
+./deploy.sh --watch # watchOS only
+./deploy.sh --all # all platforms
+./deploy.sh --skip-tests # skip tests for faster iteration
+\`\`\`
+
+Requires \`.env\` file with App Store Connect API credentials (see \`.env.example\`).
+
+## Screenshot Automation
+
+\`\`\`bash
+./take_screenshots.sh # iOS/iPad, all languages
+./take_screenshots.sh en # single language
+./take_screenshots.sh --iphone-only
+./take_screenshots_macos.sh # macOS screenshots
+\`\`\`
+
+Screenshots are saved to \`screenshots/{locale}/{device}/\` for upload to App Store Connect.
+`);
+
+ addStep('Create multi-platform Xcode project', 'done');
+
+ // Run xcodegen if available
+ const { stderr: xgenErr } = await execAsync('xcodegen generate', { cwd: repoPath, windowsHide: true })
+ .catch(err => ({ stderr: err.message }));
+
+ if (xgenErr && !xgenErr.includes('Created project')) {
+ addStep('Generate Xcode project', 'error', xgenErr);
+ } else {
+ addStep('Generate Xcode project', 'done');
+ }
+}
diff --git a/server/services/appDeployer.js b/server/services/appDeployer.js
index e4bb218503..7b2d090aef 100644
--- a/server/services/appDeployer.js
+++ b/server/services/appDeployer.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { NON_PM2_TYPES } from './streamingDetect.js';
-export const DEPLOY_FLAGS = ['--ios', '--macos', '--all', '--skip-tests'];
+export const DEPLOY_FLAGS = ['--ios', '--macos', '--watch', '--all', '--skip-tests'];
const VALID_FLAGS = new Set(DEPLOY_FLAGS);
const FLUSH_INTERVAL_MS = 80;
@@ -24,7 +24,7 @@ export function hasDeployScript(app) {
* Run deploy.sh for an Xcode app with real-time output streaming.
*
* @param {object} app - App object with repoPath, type, name
- * @param {string[]} flags - CLI flags (--ios, --macos, --all, --skip-tests)
+ * @param {string[]} flags - CLI flags (--ios, --macos, --watch, --all, --skip-tests)
* @param {function} emit - Callback (type, data) for streaming output
* @returns {Promise<{success: boolean, code: number}>}
*/
diff --git a/server/services/xcodeScripts.js b/server/services/xcodeScripts.js
new file mode 100644
index 0000000000..cb5fdd0c64
--- /dev/null
+++ b/server/services/xcodeScripts.js
@@ -0,0 +1,1023 @@
+import { existsSync } from 'fs';
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { exec, execFile } from 'child_process';
+import { promisify } from 'util';
+
+const execAsync = promisify(exec);
+const execFileAsync = promisify(execFile);
+
+// Xcode-based app types (excludes 'swift' which is SPM-only, no .xcodeproj)
+const XCODE_TYPES = new Set(['ios-native', 'macos-native', 'xcode']);
+
+// Shared Xcode project constants
+export const XCODE_TEAM_ID = 'TYQ32QCF6K';
+export const XCODE_BUNDLE_PREFIX = 'net.shadowpuppet';
+export const toBundleId = (name) => {
+ const sanitized = name.replace(/[^a-zA-Z0-9]/g, '');
+ return `${XCODE_BUNDLE_PREFIX}.${sanitized || 'app'}`;
+};
+/**
+ * Convert an arbitrary app name into a valid Swift / Xcode target identifier.
+ * Identifiers must start with a letter or underscore and contain only
+ * [A-Za-z0-9_]. Names that sanitize to empty or start with a digit are
+ * prefixed with `App` so the generated Swift compiles cleanly.
+ */
+export const toTargetName = (name) => {
+ const sanitized = (name ?? '')
+ .trim()
+ .replace(/[^a-zA-Z0-9_]/g, '_')
+ .replace(/_+/g, '_')
+ .replace(/^_+|_+$/g, '');
+ if (!sanitized) return 'App';
+ return /^[A-Za-z_]/.test(sanitized) ? sanitized : `App_${sanitized}`;
+};
+
+// Quote values that contain spaces because deploy.sh sources this file with
+// `source .env`; an unquoted value with spaces would be split on whitespace.
+export const XCODE_ENV_EXAMPLE = `TEAM_ID=${XCODE_TEAM_ID}
+APPSTORE_API_KEY_ID=YOUR_KEY_ID
+APPSTORE_ISSUER_ID=YOUR_ISSUER_ID
+APPSTORE_API_PRIVATE_KEY_PATH="~/Library/Mobile Documents/com~apple~CloudDocs/AppDev/AuthKey_XXXXXXXXXX.p8"
+`;
+
+/**
+ * Generate the generic deploy.sh script content.
+ * Supports --ios, --macos, --watch, --all, --skip-tests flags.
+ * Works with both XcodeGen (project.yml) and raw .xcodeproj projects.
+ */
+export function generateDeployScript(targetName, _bundleId) {
+ return `#!/bin/bash
+set -euo pipefail
+
+# ${targetName} - Local TestFlight Deploy
+# Usage: ./deploy.sh [--skip-tests] [--ios] [--macos] [--watch] [--all]
+# Default (no platform flag): iOS only
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+cd "$SCRIPT_DIR"
+
+# Load environment
+if [ -f .env ]; then
+ set -a
+ source .env
+ set +a
+else
+ echo "❌ .env file not found. Copy .env.example to .env and fill in values."
+ exit 1
+fi
+
+KEY_PATH="$APPSTORE_API_PRIVATE_KEY_PATH"
+# Expand ~ to $HOME (~ doesn't expand inside double quotes)
+KEY_PATH="\${KEY_PATH/#~/\$HOME}"
+
+if [ ! -f "$KEY_PATH" ]; then
+ echo "❌ API key not found at: $KEY_PATH"
+ exit 1
+fi
+
+# Ensure altool can find the key (it only checks specific directories)
+mkdir -p ~/.private_keys
+KEY_FILENAME="AuthKey_\${APPSTORE_API_KEY_ID}.p8"
+if [ ! -f ~/.private_keys/"$KEY_FILENAME" ]; then
+ ln -sf "$KEY_PATH" ~/.private_keys/"$KEY_FILENAME"
+ echo "🔑 Symlinked API key to ~/.private_keys/"
+fi
+
+# Detect project type: XcodeGen (project.yml) or raw .xcodeproj
+if [ -f project.yml ]; then
+ PROJECT_MODE="xcodegen"
+else
+ PROJECT_MODE="xcodeproj"
+fi
+
+PROJECT="${targetName}.xcodeproj"
+BUILD_DIR="$SCRIPT_DIR/build"
+
+# Parse flags
+SKIP_TESTS=false
+BUILD_IOS=false
+BUILD_MACOS=false
+BUILD_WATCH=false
+for arg in "$@"; do
+ case "$arg" in
+ --skip-tests) SKIP_TESTS=true ;;
+ --ios) BUILD_IOS=true ;;
+ --macos) BUILD_MACOS=true ;;
+ --watch) BUILD_WATCH=true ;;
+ --all) BUILD_IOS=true; BUILD_MACOS=true; BUILD_WATCH=true ;;
+ esac
+done
+# Default to iOS if no platform specified
+if ! $BUILD_IOS && ! $BUILD_MACOS && ! $BUILD_WATCH; then
+ BUILD_IOS=true
+fi
+
+# Auto-increment build number
+if [ "$PROJECT_MODE" = "xcodegen" ]; then
+ CURRENT_BUILD=$(grep CURRENT_PROJECT_VERSION project.yml | head -1 | awk '{print $2}')
+ NEW_BUILD=$((CURRENT_BUILD + 1))
+ echo "📦 Build number: $CURRENT_BUILD → $NEW_BUILD"
+ /usr/bin/sed -i '' "s/CURRENT_PROJECT_VERSION: \${CURRENT_BUILD}/CURRENT_PROJECT_VERSION: \${NEW_BUILD}/" project.yml
+
+ echo "⚙️ Regenerating Xcode project..."
+ xcodegen generate
+else
+ CURRENT_BUILD=$(grep -m1 'CURRENT_PROJECT_VERSION = ' "$PROJECT/project.pbxproj" | awk '{print $3}' | tr -d ';')
+ NEW_BUILD=$((CURRENT_BUILD + 1))
+ echo "📦 Build number: $CURRENT_BUILD → $NEW_BUILD"
+ /usr/bin/sed -i '' "s/CURRENT_PROJECT_VERSION = \${CURRENT_BUILD};/CURRENT_PROJECT_VERSION = \${NEW_BUILD};/g" "$PROJECT/project.pbxproj"
+fi
+
+# Run tests (unless skipped; only when building iOS since tests use iOS simulator)
+if ! $SKIP_TESTS && $BUILD_IOS; then
+ echo "🧪 Running tests..."
+ DESTINATION=$(
+ SIMINFO=$(xcrun simctl list devices available -j | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+for runtime, devices in data.get('devices', {}).items():
+ if 'iOS' not in runtime:
+ continue
+ parts = runtime.replace('com.apple.CoreSimulator.SimRuntime.iOS-', '').split('-')
+ os_ver = '.'.join(parts)
+ for d in devices:
+ name = d.get('name', '')
+ if d.get('isAvailable') and 'iPhone 16' in name and 'Plus' not in name and 'Pro' not in name and 'e' != name[-1:]:
+ print(f'{name},{os_ver}')
+ sys.exit(0)
+for runtime, devices in data.get('devices', {}).items():
+ if 'iOS' not in runtime:
+ continue
+ parts = runtime.replace('com.apple.CoreSimulator.SimRuntime.iOS-', '').split('-')
+ os_ver = '.'.join(parts)
+ for d in devices:
+ if d.get('isAvailable') and 'iPhone' in d.get('name', ''):
+ print(f\\"{d['name']},{os_ver}\\")
+ sys.exit(0)
+" 2>/dev/null)
+ SIM_NAME="\${SIMINFO%%,*}"
+ SIM_OS="\${SIMINFO##*,}"
+ if [ -n "$SIM_NAME" ] && [ -n "$SIM_OS" ]; then
+ echo "platform=iOS Simulator,name=$SIM_NAME,OS=$SIM_OS"
+ else
+ echo "platform=iOS Simulator,name=iPhone 16"
+ fi
+ )
+ xcodebuild test \\
+ -project "$PROJECT" \\
+ -scheme "${targetName}" \\
+ -only-testing:${targetName}Tests \\
+ -destination "$DESTINATION" \\
+ -configuration Debug \\
+ CODE_SIGNING_ALLOWED=NO \\
+ -quiet
+ echo "✅ Tests passed"
+fi
+
+# Clean build directory
+rm -rf "$BUILD_DIR"
+
+PLATFORMS_BUILT=0
+
+# --- iOS Build & Upload ---
+if $BUILD_IOS; then
+ ARCHIVE_IOS="$BUILD_DIR/${targetName}_iOS.xcarchive"
+ EXPORT_IOS="$BUILD_DIR/export_ios"
+
+ echo "📦 Archiving iOS..."
+ xcodebuild archive \\
+ -project "$PROJECT" \\
+ -scheme "${targetName}" \\
+ -configuration Release \\
+ -destination 'generic/platform=iOS' \\
+ -archivePath "$ARCHIVE_IOS" \\
+ CODE_SIGNING_ALLOWED=NO \\
+ CODE_SIGN_IDENTITY="" \\
+ CODE_SIGNING_REQUIRED=NO \\
+ -quiet
+ echo "✅ iOS archive complete"
+
+ cat > "$BUILD_DIR/exportOptions_ios.plist" <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>method</key><string>app-store-connect</string>
+ <key>teamID</key><string>$TEAM_ID</string>
+ <key>signingStyle</key><string>automatic</string>
+</dict>
+</plist>
+EOF
+
+ echo "📤 Exporting iOS IPA..."
+ xcodebuild -exportArchive \\
+ -archivePath "$ARCHIVE_IOS" \\
+ -exportOptionsPlist "$BUILD_DIR/exportOptions_ios.plist" \\
+ -exportPath "$EXPORT_IOS" \\
+ -allowProvisioningUpdates \\
+ -authenticationKeyPath "$KEY_PATH" \\
+ -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
+ -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
+ -quiet
+ echo "✅ iOS IPA exported"
+
+ IPA_PATH="$EXPORT_IOS/${targetName}.ipa"
+ if [ ! -f "$IPA_PATH" ]; then
+ echo "❌ iOS IPA not found at $IPA_PATH"
+ ls -la "$EXPORT_IOS/"
+ exit 1
+ fi
+
+ echo "🚀 Uploading iOS to TestFlight..."
+ xcrun altool --upload-app \\
+ --file "$IPA_PATH" \\
+ --type ios \\
+ --apiKey "$APPSTORE_API_KEY_ID" \\
+ --apiIssuer "$APPSTORE_ISSUER_ID" \\
+ --transport DAV
+ echo "✅ iOS upload complete!"
+ PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))
+
+ if $BUILD_MACOS || $BUILD_WATCH; then
+ echo "⏳ Waiting 60s before next upload to avoid Apple CDN contention..."
+ sleep 60
+ fi
+fi
+
+# --- macOS Build & Upload ---
+if $BUILD_MACOS; then
+ ARCHIVE_MACOS="$BUILD_DIR/${targetName}_macOS.xcarchive"
+ EXPORT_MACOS="$BUILD_DIR/export_macos"
+
+ echo "📦 Archiving macOS..."
+ xcodebuild archive \\
+ -project "$PROJECT" \\
+ -scheme "${targetName} macOS" \\
+ -configuration Release \\
+ -destination 'generic/platform=macOS' \\
+ -archivePath "$ARCHIVE_MACOS" \\
+ -allowProvisioningUpdates \\
+ -authenticationKeyPath "$KEY_PATH" \\
+ -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
+ -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
+ -quiet
+ echo "✅ macOS archive complete"
+
+ cat > "$BUILD_DIR/exportOptions_macos.plist" <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>method</key><string>app-store-connect</string>
+ <key>teamID</key><string>$TEAM_ID</string>
+ <key>signingStyle</key><string>automatic</string>
+</dict>
+</plist>
+EOF
+
+ echo "📤 Exporting macOS pkg..."
+ xcodebuild -exportArchive \\
+ -archivePath "$ARCHIVE_MACOS" \\
+ -exportOptionsPlist "$BUILD_DIR/exportOptions_macos.plist" \\
+ -exportPath "$EXPORT_MACOS" \\
+ -allowProvisioningUpdates \\
+ -authenticationKeyPath "$KEY_PATH" \\
+ -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
+ -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
+ -quiet
+ echo "✅ macOS pkg exported"
+
+ PKG_PATH=$(find "$EXPORT_MACOS" -name "*.pkg" | head -1)
+ if [ -z "$PKG_PATH" ]; then
+ echo "❌ macOS package not found in $EXPORT_MACOS"
+ ls -la "$EXPORT_MACOS/"
+ exit 1
+ fi
+
+ echo "🚀 Uploading macOS to TestFlight..."
+ xcrun altool --upload-app \\
+ --file "$PKG_PATH" \\
+ --type macos \\
+ --apiKey "$APPSTORE_API_KEY_ID" \\
+ --apiIssuer "$APPSTORE_ISSUER_ID"
+ echo "✅ macOS upload complete!"
+ PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))
+
+ if $BUILD_WATCH; then
+ echo "⏳ Waiting 60s before next upload to avoid Apple CDN contention..."
+ sleep 60
+ fi
+fi
+
+# --- watchOS Build & Upload ---
+if $BUILD_WATCH; then
+ ARCHIVE_WATCH="$BUILD_DIR/${targetName}_watchOS.xcarchive"
+ EXPORT_WATCH="$BUILD_DIR/export_watchos"
+
+ echo "📦 Archiving watchOS..."
+ xcodebuild archive \\
+ -project "$PROJECT" \\
+ -scheme "${targetName}_Watch" \\
+ -configuration Release \\
+ -destination 'generic/platform=watchOS' \\
+ -archivePath "$ARCHIVE_WATCH" \\
+ -allowProvisioningUpdates \\
+ -authenticationKeyPath "$KEY_PATH" \\
+ -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
+ -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
+ -quiet
+ echo "✅ watchOS archive complete"
+
+ cat > "$BUILD_DIR/exportOptions_watchos.plist" <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>method</key><string>app-store-connect</string>
+ <key>teamID</key><string>$TEAM_ID</string>
+ <key>signingStyle</key><string>automatic</string>
+</dict>
+</plist>
+EOF
+
+ echo "📤 Exporting watchOS..."
+ xcodebuild -exportArchive \\
+ -archivePath "$ARCHIVE_WATCH" \\
+ -exportOptionsPlist "$BUILD_DIR/exportOptions_watchos.plist" \\
+ -exportPath "$EXPORT_WATCH" \\
+ -allowProvisioningUpdates \\
+ -authenticationKeyPath "$KEY_PATH" \\
+ -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
+ -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
+ -quiet
+ echo "✅ watchOS exported"
+
+ # watchOS is typically bundled with iOS, but standalone apps need separate upload
+ WCK_PATH=$(find "$EXPORT_WATCH" -name "*.ipa" | head -1)
+ if [ -n "$WCK_PATH" ]; then
+ echo "🚀 Uploading watchOS to TestFlight..."
+ xcrun altool --upload-app \\
+ --file "$WCK_PATH" \\
+ --type ios \\
+ --apiKey "$APPSTORE_API_KEY_ID" \\
+ --apiIssuer "$APPSTORE_ISSUER_ID" \\
+ --transport DAV
+ echo "✅ watchOS upload complete!"
+ else
+ echo "ℹ️ No standalone watchOS IPA (bundled with iOS app)"
+ fi
+ PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))
+fi
+
+echo "✅ Build $NEW_BUILD submitted to TestFlight ($PLATFORMS_BUILT platform(s))."
+
+# Commit the build number bump (if in a git repo with changes)
+if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ if [ "$PROJECT_MODE" = "xcodegen" ]; then
+ git add project.yml "$PROJECT/project.pbxproj" 2>/dev/null || true
+ else
+ git add "$PROJECT/project.pbxproj" 2>/dev/null || true
+ fi
+ git diff --cached --quiet || git commit -m "build: bump to build $NEW_BUILD"
+ echo "📝 Committed build number bump"
+fi
+
+# Clean up
+rm -rf "$BUILD_DIR"
+echo "🧹 Cleaned build artifacts"
+`;
+}
+
+// Shared bash currency_for_locale function (used by both screenshot scripts)
+const CURRENCY_CASE_BLOCK = `currency_for_locale() {
+ case "$1" in
+ en) echo "USD" ;;
+ de|fr|nl|es-ES|it) echo "EUR" ;;
+ sv) echo "SEK" ;;
+ es-MX) echo "MXN" ;;
+ pt-BR) echo "BRL" ;;
+ ja) echo "JPY" ;;
+ zh-Hans) echo "CNY" ;;
+ ko) echo "KRW" ;;
+ *) echo "USD" ;;
+ esac
+}`;
+
+/**
+ * Generate generic iOS/iPad screenshot capture script.
+ * All generators accept (targetName, bundleId) for uniform calling.
+ */
+export function generateScreenshotScript(targetName, bundleId) {
+ return `#!/bin/bash
+#
+# take_screenshots.sh — Capture App Store Connect screenshots for all languages and devices.
+#
+# Usage:
+# ./take_screenshots.sh # all languages, all devices
+# ./take_screenshots.sh en # single language, all devices
+# ./take_screenshots.sh en de fr # specific languages, all devices
+# ./take_screenshots.sh --iphone-only # all languages, iPhone only
+# ./take_screenshots.sh --ipad-only # all languages, iPad only
+# ./take_screenshots.sh --screen 01_home # only capture one screen
+#
+# Requires: ScreenshotTests target in ${targetName}UITests
+#
+
+set -euo pipefail
+
+PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PROJECT="$PROJECT_DIR/${targetName}.xcodeproj"
+SCHEME="${targetName}"
+SCREENSHOTS_DIR="$PROJECT_DIR/screenshots"
+CONFIG_FILE_PROJECT="$PROJECT_DIR/.screenshot_config.json"
+CONFIG_FILE_TMP="/tmp/${targetName.toLowerCase()}_screenshot_config.json"
+DERIVED_DATA="$PROJECT_DIR/.build/DerivedData"
+BUNDLE_ID="${bundleId}"
+
+# Detect installed iOS simulator runtime version
+IOS_VERSION=$(xcrun simctl list runtimes -j 2>/dev/null | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+for r in sorted(data.get('runtimes', []), key=lambda x: x.get('version', ''), reverse=True):
+ if r.get('isAvailable') and 'iOS' in r.get('name', ''):
+ print(r['version']); sys.exit(0)
+print('18.0') # safe fallback
+" 2>/dev/null)
+
+# App Store Connect screenshot device specs
+# Format: "Simulator Name|OS version|folder_name|test_method"
+IPHONE_DEVICE="iPhone 16 Pro Max|\${IOS_VERSION}|iphone_6.7|testCaptureIPhoneScreenshots"
+IPAD_DEVICE="iPad Pro 13-inch (M4)|\${IOS_VERSION}|ipad_13|testCaptureIPadScreenshots"
+
+# Supported languages (add your app's localizations here)
+ALL_LANGUAGES=("en")
+
+# Currency code per locale
+${CURRENCY_CASE_BLOCK}
+
+# Parse arguments
+LANGUAGES=()
+DEVICES=()
+SCREEN=""
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --iphone-only) DEVICES=("$IPHONE_DEVICE") ; shift ;;
+ --ipad-only) DEVICES=("$IPAD_DEVICE") ; shift ;;
+ --screen) SCREEN="$2" ; shift 2 ;;
+ --help|-h)
+ echo "Usage: $0 [--iphone-only|--ipad-only] [--screen <name>] [lang1 lang2 ...]"
+ echo ""
+ echo "Languages: \${ALL_LANGUAGES[*]}"
+ echo "Devices: iPhone 16 Pro Max (6.7\\"), iPad Pro 13\\" (M4)"
+ exit 0
+ ;;
+ *)
+ LANGUAGES+=("$1") ; shift ;;
+ esac
+done
+
+# Defaults
+[[ \${#LANGUAGES[@]} -eq 0 ]] && LANGUAGES=("\${ALL_LANGUAGES[@]}")
+[[ \${#DEVICES[@]} -eq 0 ]] && DEVICES=("$IPHONE_DEVICE" "$IPAD_DEVICE")
+
+TOTAL_LANGS=\${#LANGUAGES[@]}
+TOTAL_DEVICES=\${#DEVICES[@]}
+TOTAL_RUNS=$((TOTAL_LANGS * TOTAL_DEVICES))
+CURRENT_RUN=0
+FAILED=()
+
+echo "=========================================="
+echo " ${targetName} App Store Screenshot Capture"
+echo "=========================================="
+echo " Languages: \${LANGUAGES[*]}"
+echo " Devices: $TOTAL_DEVICES"
+echo " Total runs: $TOTAL_RUNS"
+[[ -n "$SCREEN" ]] && echo " Screen: $SCREEN"
+echo " Output: $SCREENSHOTS_DIR/{locale}/{device}/"
+echo "=========================================="
+echo ""
+
+write_config() {
+ local locale="$1"
+ local device="$2"
+ local output="$3"
+ local currency
+ currency=$(currency_for_locale "$locale")
+ cat > "$CONFIG_FILE_PROJECT" <<JSONEOF
+{
+ "locale": "$locale",
+ "device": "$device",
+ "output_dir": "$output",
+ "currency": "$currency",
+ "target_screen": "$SCREEN"
+}
+JSONEOF
+ cp "$CONFIG_FILE_PROJECT" "$CONFIG_FILE_TMP" 2>/dev/null || true
+}
+
+# Build test bundles (once per device)
+for device_spec in "\${DEVICES[@]}"; do
+ IFS='|' read -r DEVICE_NAME DEVICE_OS DEVICE_FOLDER TEST_METHOD <<< "$device_spec"
+
+ echo "🔨 Building test bundle for $DEVICE_NAME..."
+ xcodebuild build-for-testing \\
+ -project "$PROJECT" \\
+ -scheme "$SCHEME" \\
+ -destination "platform=iOS Simulator,name=$DEVICE_NAME,OS=$DEVICE_OS" \\
+ -derivedDataPath "$DERIVED_DATA" \\
+ CODE_SIGNING_ALLOWED=NO \\
+ -quiet 2>&1 || {
+ echo "❌ Build failed for $DEVICE_NAME"
+ exit 1
+ }
+ echo "✅ Build complete for $DEVICE_NAME"
+ echo ""
+done
+
+# Boot simulators and pre-grant notification permissions
+for device_spec in "\${DEVICES[@]}"; do
+ IFS='|' read -r DEVICE_NAME _ _ _ <<< "$device_spec"
+ echo "🚀 Booting $DEVICE_NAME simulator..."
+ xcrun simctl boot "$DEVICE_NAME" 2>/dev/null || true
+done
+sleep 3
+for device_spec in "\${DEVICES[@]}"; do
+ IFS='|' read -r DEVICE_NAME _ _ _ <<< "$device_spec"
+ xcrun simctl privacy "$DEVICE_NAME" grant notifications "$BUNDLE_ID" 2>/dev/null || true
+done
+
+# Capture screenshots
+for device_spec in "\${DEVICES[@]}"; do
+ IFS='|' read -r DEVICE_NAME DEVICE_OS DEVICE_FOLDER TEST_METHOD <<< "$device_spec"
+
+ for LANG in "\${LANGUAGES[@]}"; do
+ CURRENT_RUN=$((CURRENT_RUN + 1))
+ echo "📸 [$CURRENT_RUN/$TOTAL_RUNS] $LANG on $DEVICE_NAME..."
+
+ write_config "$LANG" "$DEVICE_FOLDER" "$SCREENSHOTS_DIR"
+
+ if xcodebuild test-without-building \\
+ -project "$PROJECT" \\
+ -scheme "$SCHEME" \\
+ -destination "platform=iOS Simulator,name=$DEVICE_NAME,OS=$DEVICE_OS" \\
+ -derivedDataPath "$DERIVED_DATA" \\
+ -only-testing:"${targetName}UITests/ScreenshotTests/$TEST_METHOD" \\
+ CODE_SIGNING_ALLOWED=NO \\
+ -quiet 2>&1; then
+ echo " ✅ $LANG / $DEVICE_FOLDER complete"
+ else
+ echo " ⚠️ $LANG / $DEVICE_FOLDER had failures (screenshots may still be saved)"
+ FAILED+=("$LANG/$DEVICE_FOLDER")
+ fi
+ done
+done
+
+# Clean up config files
+rm -f "$CONFIG_FILE_PROJECT" "$CONFIG_FILE_TMP"
+
+# Summary
+echo ""
+echo "=========================================="
+echo " Screenshot Capture Complete"
+echo "=========================================="
+
+TOTAL_SCREENSHOTS=$(find "$SCREENSHOTS_DIR" -name "*.png" -newer "$PROJECT_DIR/take_screenshots.sh" 2>/dev/null | wc -l | tr -d ' ')
+echo " Screenshots captured: $TOTAL_SCREENSHOTS"
+echo " Output directory: $SCREENSHOTS_DIR/"
+echo ""
+
+for LANG in "\${LANGUAGES[@]}"; do
+ for device_spec in "\${DEVICES[@]}"; do
+ IFS='|' read -r _ _ DEVICE_FOLDER _ <<< "$device_spec"
+ DIR="$SCREENSHOTS_DIR/$LANG/$DEVICE_FOLDER"
+ if [[ -d "$DIR" ]]; then
+ COUNT=$(ls "$DIR"/*.png 2>/dev/null | wc -l | tr -d ' ')
+ echo " $LANG/$DEVICE_FOLDER: $COUNT screenshots"
+ fi
+ done
+done
+
+if [[ \${#FAILED[@]} -gt 0 ]]; then
+ echo ""
+ echo "⚠️ Runs with failures:"
+ for f in "\${FAILED[@]}"; do
+ echo " - $f"
+ done
+fi
+
+echo ""
+echo "Done! Upload screenshots to App Store Connect via Transporter or the web UI."
+`;
+}
+
+/**
+ * Generate generic macOS screenshot capture script.
+ * Accepts (targetName, bundleId) for uniform calling — bundleId unused here.
+ */
+export function generateMacScreenshotScript(targetName, _bundleId) {
+ return `#!/bin/bash
+#
+# take_screenshots_macos.sh — Capture macOS App Store screenshots for all languages.
+#
+# Prerequisites:
+# Your terminal app needs TWO macOS permissions (System Settings → Privacy & Security):
+# 1. Screen Recording — to capture the app window
+# 2. Accessibility — to navigate the sidebar via AppleScript
+# Grant these, then re-run the script.
+#
+# Usage:
+# ./take_screenshots_macos.sh # all languages
+# ./take_screenshots_macos.sh en de # specific languages
+#
+
+set -euo pipefail
+
+PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PROJECT="$PROJECT_DIR/${targetName}.xcodeproj"
+SCHEME="${targetName} macOS"
+SCREENSHOTS_DIR="$PROJECT_DIR/screenshots"
+DERIVED_DATA="$PROJECT_DIR/.build/DerivedData"
+APP_PATH="$DERIVED_DATA/Build/Products/Debug/${targetName}.app"
+
+# Supported languages (add your app's localizations here)
+ALL_LANGUAGES=("en")
+
+# Currency per locale
+${CURRENCY_CASE_BLOCK}
+
+# Parse arguments
+LANGUAGES=()
+for arg in "$@"; do
+ case "$arg" in
+ --help|-h)
+ echo "Usage: $0 [lang1 lang2 ...]"
+ echo "Languages: \${ALL_LANGUAGES[*]}"
+ echo ""
+ echo "Requires Screen Recording + Accessibility permissions for your terminal."
+ exit 0
+ ;;
+ *) LANGUAGES+=("$arg") ;;
+ esac
+done
+[[ \${#LANGUAGES[@]} -eq 0 ]] && LANGUAGES=("\${ALL_LANGUAGES[@]}")
+
+# macOS App Store screenshot size: 1280x800 minimum, Retina preferred
+WINDOW_WIDTH=1440
+WINDOW_HEIGHT=900
+
+echo "=========================================="
+echo " ${targetName} macOS Screenshot Capture"
+echo "=========================================="
+echo " Languages: \${LANGUAGES[*]}"
+echo " Window: \${WINDOW_WIDTH}x\${WINDOW_HEIGHT}"
+echo " Output: $SCREENSHOTS_DIR/{locale}/macos/"
+echo "=========================================="
+echo ""
+
+# Build macOS app
+echo "🔨 Building macOS app..."
+xcodebuild build \\
+ -project "$PROJECT" \\
+ -scheme "$SCHEME" \\
+ -derivedDataPath "$DERIVED_DATA" \\
+ CODE_SIGNING_ALLOWED=NO \\
+ -quiet 2>&1 || {
+ echo "❌ Build failed"
+ exit 1
+ }
+echo "✅ Build complete"
+echo ""
+
+if [[ ! -d "$APP_PATH" ]]; then
+ echo "❌ App not found at $APP_PATH"
+ exit 1
+fi
+
+# Get window ID via CGWindowListCopyWindowInfo
+get_window_id() {
+ swift -e '
+ import Cocoa
+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
+ guard let windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else { exit(1) }
+ for w in windowList {
+ let owner = w[kCGWindowOwnerName as String] as? String ?? ""
+ if owner == "${targetName}" {
+ if let num = w[kCGWindowNumber as String] as? Int { print(num); break }
+ }
+ }
+ ' 2>/dev/null
+}
+
+# Position and resize window
+setup_window() {
+ osascript -e "
+ tell application \\"System Events\\"
+ tell process \\"${targetName}\\"
+ if (count of windows) > 0 then
+ set position of first window to {100, 100}
+ set size of first window to {\${WINDOW_WIDTH}, \${WINDOW_HEIGHT}}
+ end if
+ end tell
+ end tell" 2>/dev/null
+}
+
+# Click a sidebar item by row number
+click_sidebar() {
+ local row="$1"
+ osascript -e "
+ tell application \\"System Events\\"
+ tell process \\"${targetName}\\"
+ tell outline 1 of scroll area 1 of group 1 of splitter group 1 of group 1 of window 1
+ select row $row
+ end tell
+ end tell
+ end tell" 2>/dev/null || true
+}
+
+# Click at a position in the window (relative to window top-left, in points)
+click_at() {
+ local x="$1" y="$2"
+ osascript -e "
+ tell application \\"${targetName}\\" to activate
+ tell application \\"System Events\\"
+ tell process \\"${targetName}\\"
+ set winPos to position of window 1
+ set absX to (item 1 of winPos) + $x
+ set absY to (item 2 of winPos) + $y
+ click at {absX, absY}
+ end tell
+ end tell" 2>/dev/null || true
+}
+
+# Go back via Cmd+[ keyboard shortcut
+go_back() {
+ osascript -e '
+ tell application "${targetName}" to activate
+ delay 0.3
+ tell application "System Events"
+ key code 33 using command down
+ end tell' 2>/dev/null || true
+}
+
+# Take screenshot of the app window
+capture_window() {
+ local output_path="$1"
+ osascript -e 'tell application "${targetName}" to activate' 2>/dev/null
+ sleep 0.5
+ local wid
+ wid=$(get_window_id)
+ if [[ -n "$wid" ]]; then
+ screencapture -l "$wid" -o -x "$output_path" 2>/dev/null
+ else
+ screencapture -R "100,100,\${WINDOW_WIDTH},\${WINDOW_HEIGHT}" -o -x "$output_path" 2>/dev/null
+ fi
+}
+
+# Capture screenshots for one language
+capture_locale() {
+ local lang="$1"
+ local currency
+ currency=$(currency_for_locale "$lang")
+ local out_dir="$SCREENSHOTS_DIR/$lang/macos"
+ mkdir -p "$out_dir"
+
+ echo "📸 Capturing $lang (currency: $currency)..."
+
+ # Kill any existing instance
+ killall "${targetName}" 2>/dev/null || true
+ sleep 1
+
+ # Launch with locale settings
+ # Customize these args for your app's launch parameters
+ open "$APP_PATH" --args \\
+ -AppleLanguages "($lang)" \\
+ -AppleLocale "$lang"
+
+ sleep 4
+ setup_window
+ sleep 1
+
+ # Capture the main screen
+ # Add additional captures here for your app's screens:
+ # click_sidebar 1 → capture_window "$out_dir/01_home.png"
+ # click_sidebar 2 → capture_window "$out_dir/02_list.png"
+ # etc.
+ capture_window "$out_dir/01_home.png"
+
+ # Quit
+ killall "${targetName}" 2>/dev/null || true
+ sleep 1
+
+ local count
+ count=$(ls "$out_dir"/*.png 2>/dev/null | wc -l | tr -d ' ')
+ echo " ✅ $lang/macos: $count screenshots"
+}
+
+# Capture all locales
+FAILED=()
+for lang in "\${LANGUAGES[@]}"; do
+ if ! capture_locale "$lang"; then
+ FAILED+=("$lang")
+ fi
+done
+
+echo ""
+echo "=========================================="
+echo " macOS Screenshot Capture Complete"
+echo "=========================================="
+for lang in "\${LANGUAGES[@]}"; do
+ dir="$SCREENSHOTS_DIR/$lang/macos"
+ if [[ -d "$dir" ]]; then
+ count=$(ls "$dir"/*.png 2>/dev/null | wc -l | tr -d ' ')
+ echo " $lang/macos: $count screenshots"
+ fi
+done
+
+if [[ \${#FAILED[@]} -gt 0 ]]; then
+ echo ""
+ echo "⚠️ Failed: \${FAILED[*]}"
+fi
+
+echo ""
+echo "Done! Upload to App Store Connect under the macOS platform."
+echo "If sidebar navigation failed, grant Accessibility permission to your terminal."
+`;
+}
+
+/**
+ * Management scripts that should exist in an Xcode project.
+ * Each script declares which app types it applies to so that platform-specific
+ * scripts (e.g. macOS-only screenshot automation) are not required for apps
+ * that have no corresponding target.
+ *
+ * Type semantics:
+ * - 'xcode' : multi-platform (iOS + macOS + watchOS) — all scripts apply
+ * - 'ios-native' : iOS only — deploy + iOS screenshots
+ * - 'macos-native' : macOS only — deploy + macOS screenshots
+ *
+ * Used by scaffold for generation and health check for detection.
+ */
+export const XCODE_MANAGEMENT_SCRIPTS = [
+ {
+ name: 'deploy.sh',
+ description: 'TestFlight deployment',
+ generator: generateDeployScript,
+ appTypes: ['xcode', 'ios-native', 'macos-native']
+ },
+ {
+ name: 'take_screenshots.sh',
+ description: 'iOS/iPad screenshot automation',
+ generator: generateScreenshotScript,
+ appTypes: ['xcode', 'ios-native']
+ },
+ {
+ name: 'take_screenshots_macos.sh',
+ description: 'macOS screenshot automation',
+ generator: generateMacScreenshotScript,
+ appTypes: ['xcode', 'macos-native']
+ }
+];
+
+/**
+ * Return the subset of management scripts that apply to a given app type.
+ */
+export function scriptsForAppType(appType) {
+ return XCODE_MANAGEMENT_SCRIPTS.filter(s => s.appTypes.includes(appType));
+}
+
+/**
+ * The set of script names installable via the API. Used by route validation
+ * to fail fast on bogus payloads instead of relying on installScripts to
+ * report unknowns one-by-one.
+ */
+export const XCODE_SCRIPT_NAMES = XCODE_MANAGEMENT_SCRIPTS.map(s => s.name);
+
+/**
+ * Check which management scripts are missing from an Xcode app's repo.
+ * Only scripts that apply to the app's type are considered.
+ * Returns { missing: [{name, description}], present: [{name, description}] }
+ */
+export function checkScripts(app) {
+ if (!app?.repoPath || !XCODE_TYPES.has(app.type) || !existsSync(app.repoPath)) {
+ return { missing: [], present: [] };
+ }
+
+ const missing = [];
+ const present = [];
+
+ for (const script of scriptsForAppType(app.type)) {
+ const path = join(app.repoPath, script.name);
+ if (existsSync(path)) {
+ present.push({ name: script.name, description: script.description });
+ } else {
+ missing.push({ name: script.name, description: script.description });
+ }
+ }
+
+ return { missing, present };
+}
+
+/**
+ * Derive the target name and bundle ID from an Xcode project at repoPath.
+ * Checks project.yml first, then falls back to .xcodeproj name, then app name.
+ */
+async function deriveProjectInfo(repoPath, appName) {
+ if (process.platform === 'win32') {
+ return { targetName: toTargetName(appName), bundleId: toBundleId(appName) };
+ }
+
+ const projectYml = join(repoPath, 'project.yml');
+ if (existsSync(projectYml)) {
+ const content = await readFile(projectYml, 'utf-8');
+ // Strip wrapping quotes from YAML scalar values
+ const stripQuotes = (s) => s?.replace(/^["']|["']$/g, '');
+ // Validate parsed values are safe for bash interpolation
+ const isValidTarget = (s) => /^[A-Za-z0-9_ -]+$/.test(s);
+ const isValidBundleId = (s) => /^[A-Za-z0-9.-]+$/.test(s);
+ const nameMatch = content.match(/^name:\s*(.+)$/m);
+ const rawName = stripQuotes(nameMatch?.[1]?.trim());
+ const projectName = rawName && isValidTarget(rawName) ? rawName : null;
+ // Find PRODUCT_BUNDLE_IDENTIFIER entries, skip test/watch targets
+ const bundleIds = [...content.matchAll(/PRODUCT_BUNDLE_IDENTIFIER:\s*(.+)$/gm)]
+ .map(m => stripQuotes(m[1].trim()))
+ .filter(id => id && isValidBundleId(id) && !id.includes('Tests') && !id.includes('watchkitapp'));
+ const bundleId = bundleIds[0] || (projectName ? toBundleId(projectName) : toBundleId(appName));
+ return {
+ targetName: projectName || toTargetName(appName),
+ bundleId
+ };
+ }
+
+ // Try .xcodeproj directory name
+ const { stdout } = await execAsync('ls -d *.xcodeproj 2>/dev/null || true', { cwd: repoPath });
+ const xcodeproj = stdout.trim().split('\n')[0];
+ if (xcodeproj) {
+ const target = xcodeproj.replace('.xcodeproj', '');
+ if (/^[A-Za-z0-9_ -]+$/.test(target)) {
+ return { targetName: target, bundleId: toBundleId(target) };
+ }
+ }
+
+ return { targetName: toTargetName(appName), bundleId: toBundleId(appName) };
+}
+
+/**
+ * Install missing management scripts into an Xcode app's repo.
+ * Only installs scripts that don't already exist (never overwrites).
+ */
+export async function installScripts(app, scriptNames) {
+ if (!app?.repoPath || !XCODE_TYPES.has(app.type)) {
+ return { installed: [], skipped: [], errors: ['Not an Xcode app'] };
+ }
+
+ const { targetName, bundleId } = await deriveProjectInfo(app.repoPath, app.name);
+
+ const installed = [];
+ const skipped = [];
+ const errors = [];
+ const installedPaths = [];
+
+ for (const scriptName of scriptNames) {
+ const scriptDef = XCODE_MANAGEMENT_SCRIPTS.find(s => s.name === scriptName);
+ if (!scriptDef) {
+ errors.push(`Unknown script: ${scriptName}`);
+ continue;
+ }
+ if (!scriptDef.appTypes.includes(app.type)) {
+ errors.push(`Script ${scriptName} does not apply to ${app.type} apps`);
+ continue;
+ }
+
+ const destPath = join(app.repoPath, scriptName);
+ if (existsSync(destPath)) {
+ skipped.push(scriptName);
+ continue;
+ }
+
+ await writeFile(destPath, scriptDef.generator(targetName, bundleId));
+ installedPaths.push(destPath);
+ installed.push(scriptName);
+ }
+
+ // Batch chmod for all installed scripts
+ if (installedPaths.length) {
+ if (process.platform === 'win32') {
+ errors.push('Scripts installed but chmod is not supported on Windows');
+ } else {
+ await execFileAsync('chmod', ['+x', ...installedPaths]).catch(err => {
+ errors.push(`chmod failed: ${err.message}`);
+ });
+ }
+ }
+
+ // Create .env.example if deploy.sh was installed and none exists
+ if (installed.includes('deploy.sh') && !existsSync(join(app.repoPath, '.env.example'))) {
+ await writeFile(join(app.repoPath, '.env.example'), XCODE_ENV_EXAMPLE);
+ }
+
+ return { installed, skipped, errors };
+}
diff --git a/server/services/xcodeScripts.test.js b/server/services/xcodeScripts.test.js
new file mode 100644
index 0000000000..98a72dfcfb
--- /dev/null
+++ b/server/services/xcodeScripts.test.js
@@ -0,0 +1,475 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Hoisted mocks so promisify wraps the same fns we control in tests
+const hoisted = vi.hoisted(() => ({
+ execMock: vi.fn(),
+ execFileMock: vi.fn()
+}));
+
+// Mock fs and child_process before importing
+vi.mock('fs', () => ({
+ existsSync: vi.fn()
+}));
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(),
+ writeFile: vi.fn()
+}));
+vi.mock('child_process', () => ({
+ exec: hoisted.execMock,
+ execFile: hoisted.execFileMock
+}));
+// promisify just returns the (already async) mock we control
+vi.mock('util', () => ({
+ promisify: (fn) => fn
+}));
+
+import {
+ toBundleId, toTargetName, XCODE_BUNDLE_PREFIX,
+ checkScripts, installScripts,
+ generateDeployScript, generateScreenshotScript, generateMacScreenshotScript
+} from './xcodeScripts.js';
+import { existsSync } from 'fs';
+import { readFile, writeFile } from 'fs/promises';
+
+describe('xcodeScripts', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('toBundleId', () => {
+ it('should generate valid bundle ID from name', () => {
+ expect(toBundleId('MyApp')).toBe(`${XCODE_BUNDLE_PREFIX}.MyApp`);
+ });
+
+ it('should strip non-alphanumeric characters', () => {
+ expect(toBundleId('My App!')).toBe(`${XCODE_BUNDLE_PREFIX}.MyApp`);
+ });
+
+ it('should fall back to "app" when name has no alphanumeric characters', () => {
+ expect(toBundleId('---')).toBe(`${XCODE_BUNDLE_PREFIX}.app`);
+ });
+
+ it('should handle empty string', () => {
+ expect(toBundleId('')).toBe(`${XCODE_BUNDLE_PREFIX}.app`);
+ });
+ });
+
+ describe('toTargetName', () => {
+ it('should replace non-alphanumeric/underscore chars with underscore', () => {
+ expect(toTargetName('My App')).toBe('My_App');
+ });
+
+ it('should preserve underscores', () => {
+ expect(toTargetName('My_App')).toBe('My_App');
+ });
+
+ it('should handle already clean names', () => {
+ expect(toTargetName('MyApp')).toBe('MyApp');
+ });
+
+ it('should produce a valid Swift identifier for names starting with digits', () => {
+ const targetName = toTargetName('123App');
+ expect(targetName).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/);
+ expect(targetName).not.toBe('123App');
+ expect(targetName).toContain('123App');
+ });
+
+ it('should produce a valid identifier for purely numeric names', () => {
+ const targetName = toTargetName('123');
+ expect(targetName).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/);
+ });
+
+ it('should not sanitize names to only underscores', () => {
+ const targetName = toTargetName('---');
+ expect(targetName).toBe('App');
+ expect(targetName).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/);
+ });
+
+ it('should collapse runs of underscores from substituted characters', () => {
+ // 'My!@#App' -> 'My___App' -> 'My_App'
+ expect(toTargetName('My!@#App')).toBe('My_App');
+ });
+
+ it('should trim leading and trailing whitespace and underscores', () => {
+ expect(toTargetName(' My App ')).toBe('My_App');
+ expect(toTargetName('___MyApp___')).toBe('MyApp');
+ });
+
+ it('should fall back to App for empty or null input', () => {
+ expect(toTargetName('')).toBe('App');
+ expect(toTargetName(null)).toBe('App');
+ expect(toTargetName(undefined)).toBe('App');
+ });
+ });
+
+ describe('checkScripts', () => {
+ it('should return empty arrays for non-Xcode app types', () => {
+ const result = checkScripts({ type: 'node', repoPath: '/tmp/test' });
+ expect(result.missing).toHaveLength(0);
+ expect(result.present).toHaveLength(0);
+ });
+
+ it('should return empty arrays for swift (SPM) app type', () => {
+ const result = checkScripts({ type: 'swift', repoPath: '/tmp/test' });
+ expect(result.missing).toHaveLength(0);
+ expect(result.present).toHaveLength(0);
+ });
+
+ it('should return empty arrays when app has no repoPath', () => {
+ const result = checkScripts({ type: 'xcode' });
+ expect(result.missing).toHaveLength(0);
+ });
+
+ it('should detect missing scripts for xcode apps', () => {
+ // First call checks repoPath exists (true), rest check script files (false)
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'xcode', repoPath: '/tmp/test' });
+ expect(result.missing.length).toBeGreaterThan(0);
+ expect(result.present).toHaveLength(0);
+ });
+
+ it('should detect present scripts for xcode apps', () => {
+ existsSync.mockReturnValue(true);
+ const result = checkScripts({ type: 'xcode', repoPath: '/tmp/test' });
+ expect(result.present.length).toBeGreaterThan(0);
+ expect(result.missing).toHaveLength(0);
+ });
+
+ it('should return empty arrays when repoPath does not exist', () => {
+ existsSync.mockReturnValue(false);
+ const result = checkScripts({ type: 'xcode', repoPath: '/nonexistent' });
+ expect(result.missing).toHaveLength(0);
+ expect(result.present).toHaveLength(0);
+ });
+
+ it('should work for ios-native type', () => {
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'ios-native', repoPath: '/tmp/test' });
+ expect(result.missing.length).toBeGreaterThan(0);
+ });
+
+ it('should work for macos-native type', () => {
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'macos-native', repoPath: '/tmp/test' });
+ expect(result.missing.length).toBeGreaterThan(0);
+ });
+
+ it('should not require macOS screenshot script for ios-native apps', () => {
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'ios-native', repoPath: '/tmp/test' });
+ const names = result.missing.map(m => m.name);
+ expect(names).toContain('deploy.sh');
+ expect(names).toContain('take_screenshots.sh');
+ expect(names).not.toContain('take_screenshots_macos.sh');
+ });
+
+ it('should not require iOS screenshot script for macos-native apps', () => {
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'macos-native', repoPath: '/tmp/test' });
+ const names = result.missing.map(m => m.name);
+ expect(names).toContain('deploy.sh');
+ expect(names).toContain('take_screenshots_macos.sh');
+ expect(names).not.toContain('take_screenshots.sh');
+ });
+
+ it('should require all three scripts for multi-platform xcode apps', () => {
+ existsSync.mockImplementation((path) => path === '/tmp/test');
+ const result = checkScripts({ type: 'xcode', repoPath: '/tmp/test' });
+ const names = result.missing.map(m => m.name);
+ expect(names).toEqual(
+ expect.arrayContaining(['deploy.sh', 'take_screenshots.sh', 'take_screenshots_macos.sh'])
+ );
+ });
+ });
+
+ describe('generateDeployScript', () => {
+ it('should generate a bash script with target name', () => {
+ const script = generateDeployScript('MyApp', 'net.test.MyApp');
+ expect(script).toContain('#!/bin/bash');
+ expect(script).toContain('MyApp');
+ expect(script).toContain('--ios');
+ expect(script).toContain('--macos');
+ expect(script).toContain('--watch');
+ });
+
+ it('should include tilde expansion for KEY_PATH', () => {
+ const script = generateDeployScript('MyApp', 'net.test.MyApp');
+ // Must match a literal ~ (not \~), otherwise ~/... paths won't expand at runtime
+ expect(script).toContain('KEY_PATH="${KEY_PATH/#~/$HOME}"');
+ });
+
+ it('should only run tests when building iOS', () => {
+ const script = generateDeployScript('MyApp', 'net.test.MyApp');
+ expect(script).toContain('$BUILD_IOS; then');
+ });
+ });
+
+ describe('generateScreenshotScript', () => {
+ it('should generate a bash script for iOS screenshots', () => {
+ const script = generateScreenshotScript('MyApp', 'net.test.MyApp');
+ expect(script).toContain('#!/bin/bash');
+ expect(script).toContain('MyApp');
+ expect(script).toContain('net.test.MyApp');
+ });
+
+ it('should include dynamic iOS version detection', () => {
+ const script = generateScreenshotScript('MyApp', 'net.test.MyApp');
+ expect(script).toContain('IOS_VERSION=');
+ expect(script).toContain('simctl list runtimes');
+ });
+ });
+
+ describe('generateMacScreenshotScript', () => {
+ it('should generate a bash script for macOS screenshots', () => {
+ const script = generateMacScreenshotScript('MyApp', 'net.test.MyApp');
+ expect(script).toContain('#!/bin/bash');
+ expect(script).toContain('MyApp');
+ });
+ });
+
+ describe('installScripts', () => {
+ beforeEach(() => {
+ hoisted.execMock.mockReset();
+ hoisted.execFileMock.mockReset();
+ readFile.mockReset();
+ writeFile.mockReset();
+ // Default: chmod succeeds, ls returns nothing
+ hoisted.execFileMock.mockResolvedValue({ stdout: '', stderr: '' });
+ hoisted.execMock.mockResolvedValue({ stdout: '', stderr: '' });
+ writeFile.mockResolvedValue(undefined);
+ });
+
+ it('returns error for non-Xcode app type', async () => {
+ const result = await installScripts({ type: 'node', repoPath: '/tmp/x' }, ['deploy.sh']);
+ expect(result.installed).toHaveLength(0);
+ expect(result.errors).toContain('Not an Xcode app');
+ });
+
+ it('returns error when app has no repoPath', async () => {
+ const result = await installScripts({ type: 'xcode' }, ['deploy.sh']);
+ expect(result.errors).toContain('Not an Xcode app');
+ });
+
+ it('reports unknown script names as errors', async () => {
+ // No project.yml, no .xcodeproj — falls through to appName-based naming
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['nonsense.sh']
+ );
+ expect(result.errors).toContain('Unknown script: nonsense.sh');
+ expect(result.installed).toHaveLength(0);
+ });
+
+ it('refuses to install macOS screenshot script for ios-native app', async () => {
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'ios-native', repoPath: '/tmp/x', name: 'MyApp' },
+ ['take_screenshots_macos.sh']
+ );
+ expect(result.installed).toHaveLength(0);
+ expect(result.errors.some(e => e.includes('does not apply to ios-native'))).toBe(true);
+ });
+
+ it('refuses to install iOS screenshot script for macos-native app', async () => {
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'macos-native', repoPath: '/tmp/x', name: 'MyApp' },
+ ['take_screenshots.sh']
+ );
+ expect(result.installed).toHaveLength(0);
+ expect(result.errors.some(e => e.includes('does not apply to macos-native'))).toBe(true);
+ });
+
+ it('skips scripts that already exist (never overwrites)', async () => {
+ // project.yml does not exist; deploy.sh DOES exist
+ existsSync.mockImplementation((p) => String(p).endsWith('deploy.sh'));
+ const result = await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['deploy.sh']
+ );
+ expect(result.skipped).toContain('deploy.sh');
+ expect(result.installed).toHaveLength(0);
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('installs missing scripts and chmods them', async () => {
+ // No project.yml, no existing scripts, no .env.example
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['deploy.sh', 'take_screenshots.sh']
+ );
+ expect(result.installed).toEqual(['deploy.sh', 'take_screenshots.sh']);
+ expect(result.skipped).toHaveLength(0);
+ expect(result.errors).toHaveLength(0);
+ // writeFile called for each script + .env.example (since deploy.sh installed)
+ expect(writeFile).toHaveBeenCalledTimes(3);
+ // chmod called once with both installed paths
+ expect(hoisted.execFileMock).toHaveBeenCalledWith(
+ 'chmod',
+ expect.arrayContaining(['+x', '/tmp/x/deploy.sh', '/tmp/x/take_screenshots.sh'])
+ );
+ });
+
+ it('does not create .env.example when one already exists', async () => {
+ existsSync.mockImplementation((p) => String(p).endsWith('.env.example'));
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['deploy.sh']
+ );
+ // writeFile only called once (deploy.sh) — not for .env.example
+ expect(writeFile).toHaveBeenCalledTimes(1);
+ const calls = writeFile.mock.calls.map(c => c[0]);
+ expect(calls).not.toContain('/tmp/x/.env.example');
+ });
+
+ it('derives target name and bundle id from project.yml', async () => {
+ existsSync.mockImplementation((p) => String(p).endsWith('project.yml'));
+ readFile.mockResolvedValue([
+ 'name: CustomTarget',
+ 'targets:',
+ ' CustomTarget:',
+ ' settings:',
+ ' PRODUCT_BUNDLE_IDENTIFIER: net.example.CustomTarget',
+ ' CustomTargetTests:',
+ ' settings:',
+ ' PRODUCT_BUNDLE_IDENTIFIER: net.example.CustomTargetTests'
+ ].join('\n'));
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'IgnoredAppName' },
+ ['deploy.sh']
+ );
+
+ // First writeFile call is the deploy script
+ const deployScript = writeFile.mock.calls[0][1];
+ expect(deployScript).toContain('CustomTarget');
+ // Test target bundle id should be skipped — verify the non-test one is used
+ expect(deployScript).not.toContain('IgnoredAppName');
+ });
+
+ it('skips watchkitapp and Tests bundle ids in project.yml parsing', async () => {
+ existsSync.mockImplementation((p) => String(p).endsWith('project.yml'));
+ readFile.mockResolvedValue([
+ 'name: MyApp',
+ ' PRODUCT_BUNDLE_IDENTIFIER: net.example.MyAppTests',
+ ' PRODUCT_BUNDLE_IDENTIFIER: net.example.MyApp.watchkitapp',
+ ' PRODUCT_BUNDLE_IDENTIFIER: net.example.MyApp'
+ ].join('\n'));
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['take_screenshots.sh']
+ );
+
+ const screenshotScript = writeFile.mock.calls[0][1];
+ // The non-Tests, non-watchkit id should be selected
+ expect(screenshotScript).toContain('net.example.MyApp');
+ expect(screenshotScript).not.toContain('watchkitapp');
+ });
+
+ it('strips wrapping quotes from project.yml scalar values', async () => {
+ existsSync.mockImplementation((p) => String(p).endsWith('project.yml'));
+ readFile.mockResolvedValue([
+ 'name: "QuotedName"',
+ ' PRODUCT_BUNDLE_IDENTIFIER: "net.example.Quoted"'
+ ].join('\n'));
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'IgnoredAppName' },
+ ['deploy.sh']
+ );
+
+ const script = writeFile.mock.calls[0][1];
+ // Quotes should be stripped before interpolation — header comment uses
+ // raw target name, so it should appear as `QuotedName`, not `"QuotedName"`.
+ expect(script).toContain('# QuotedName - Local TestFlight Deploy');
+ });
+
+ it('rejects unsafe target names from project.yml and falls back to app name', async () => {
+ existsSync.mockImplementation((p) => String(p).endsWith('project.yml'));
+ // Name with shell metacharacters should be rejected by the safety regex
+ readFile.mockResolvedValue('name: "Bad$Name;rm"\n');
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'SafeApp' },
+ ['deploy.sh']
+ );
+
+ const script = writeFile.mock.calls[0][1];
+ expect(script).toContain('SafeApp');
+ expect(script).not.toContain('Bad$Name');
+ });
+
+ it('falls back to .xcodeproj directory name when project.yml absent', async () => {
+ // No project.yml; deriveProjectInfo executes `ls -d *.xcodeproj`
+ existsSync.mockImplementation(() => false);
+ hoisted.execMock.mockResolvedValue({ stdout: 'FoundProject.xcodeproj\n', stderr: '' });
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'IgnoredAppName' },
+ ['deploy.sh']
+ );
+
+ const script = writeFile.mock.calls[0][1];
+ expect(script).toContain('FoundProject');
+ expect(script).not.toContain('IgnoredAppName');
+ });
+
+ it('falls back to app name when neither project.yml nor .xcodeproj is present', async () => {
+ existsSync.mockImplementation(() => false);
+ hoisted.execMock.mockResolvedValue({ stdout: '', stderr: '' });
+
+ await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'BareApp' },
+ ['deploy.sh']
+ );
+
+ const script = writeFile.mock.calls[0][1];
+ expect(script).toContain('BareApp');
+ });
+
+ it('reports chmod failure as a non-fatal error', async () => {
+ existsSync.mockImplementation(() => false);
+ hoisted.execFileMock.mockRejectedValue(new Error('permission denied'));
+
+ const result = await installScripts(
+ { type: 'xcode', repoPath: '/tmp/x', name: 'MyApp' },
+ ['deploy.sh']
+ );
+
+ expect(result.installed).toContain('deploy.sh');
+ expect(result.errors.some(e => e.includes('chmod failed'))).toBe(true);
+ });
+
+ it('emits Windows-specific message when running on win32', async () => {
+ // Capture the original property descriptor so we can restore it exactly,
+ // and ensure our override is configurable so the restore can replace it.
+ const originalDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', {
+ value: 'win32',
+ configurable: true,
+ writable: true,
+ enumerable: true
+ });
+ try {
+ existsSync.mockImplementation(() => false);
+ const result = await installScripts(
+ { type: 'xcode', repoPath: 'C:/tmp/x', name: 'MyApp' },
+ ['deploy.sh']
+ );
+ // deriveProjectInfo short-circuits on win32 — uses appName directly
+ expect(result.installed).toContain('deploy.sh');
+ expect(result.errors.some(e => e.includes('chmod is not supported on Windows'))).toBe(true);
+ // execFile should NOT have been called for chmod on Windows
+ expect(hoisted.execFileMock).not.toHaveBeenCalled();
+ } finally {
+ // Restore the exact original descriptor so no test state leaks
+ if (originalDescriptor) {
+ Object.defineProperty(process, 'platform', originalDescriptor);
+ }
+ }
+ });
+ });
+});