|
| 1 | +import { execSync } from 'node:child_process'; |
| 2 | + |
| 3 | +interface Simulator { |
| 4 | + name: string; |
| 5 | + udid: string; |
| 6 | + state: string; |
| 7 | + isAvailable: boolean; |
| 8 | +} |
| 9 | + |
| 10 | +export async function openSimulator() { |
| 11 | + try { |
| 12 | + // Get list of available simulators |
| 13 | + const devices = execSync( |
| 14 | + 'xcrun simctl list devices available --json' |
| 15 | + ).toString(); |
| 16 | + const parsedDevices = JSON.parse(devices); |
| 17 | + const runtimes = Object.keys(parsedDevices.devices); |
| 18 | + |
| 19 | + // Collect all available simulators |
| 20 | + const availableSimulators: Simulator[] = []; |
| 21 | + const runningSimulators: Simulator[] = []; |
| 22 | + |
| 23 | + for (const runtime of runtimes) { |
| 24 | + const simulators = parsedDevices.devices[runtime]; |
| 25 | + simulators.forEach((sim: any) => { |
| 26 | + if (sim.isAvailable !== false) { |
| 27 | + // Add if simulator is available |
| 28 | + const simulator = { |
| 29 | + name: `${sim.name} (${runtime})`, |
| 30 | + udid: sim.udid, |
| 31 | + state: sim.state, |
| 32 | + isAvailable: true, |
| 33 | + }; |
| 34 | + |
| 35 | + if (sim.state !== 'Shutdown') { |
| 36 | + runningSimulators.push(simulator); |
| 37 | + } else { |
| 38 | + availableSimulators.push(simulator); |
| 39 | + } |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + const { select, isCancel, log } = await import('@clack/prompts'); |
| 45 | + |
| 46 | + // Log running simulators |
| 47 | + if (runningSimulators.length > 0) { |
| 48 | + log.info('Running simulators:'); |
| 49 | + runningSimulators.forEach((sim) => { |
| 50 | + log.success(` • ${sim.name}`); |
| 51 | + }); |
| 52 | + log.info(''); // Empty line for better readability |
| 53 | + } |
| 54 | + |
| 55 | + if (availableSimulators.length === 0) { |
| 56 | + throw new Error('No available (shutdown) iOS Simulators found'); |
| 57 | + } |
| 58 | + |
| 59 | + // Show prompt to select simulator (only showing shutdown simulators) |
| 60 | + const selectedSimulator = await select({ |
| 61 | + message: 'Select an iOS Simulator', |
| 62 | + options: availableSimulators.map((sim) => ({ |
| 63 | + label: sim.name, |
| 64 | + value: sim.udid, |
| 65 | + })), |
| 66 | + }); |
| 67 | + |
| 68 | + if (isCancel(selectedSimulator)) { |
| 69 | + throw new Error('No iOS Simulator selected'); |
| 70 | + } |
| 71 | + |
| 72 | + // Boot the simulator |
| 73 | + execSync(`xcrun simctl boot ${selectedSimulator}`); |
| 74 | + // Open Simulator.app |
| 75 | + execSync('open -a Simulator'); |
| 76 | + } catch (error) { |
| 77 | + if (error instanceof Error) { |
| 78 | + throw new Error(`Failed to open iOS Simulator: ${error.message}`); |
| 79 | + } |
| 80 | + throw error; |
| 81 | + } |
| 82 | +} |
0 commit comments