|
| 1 | +import path from 'path'; |
| 2 | +import { __ } from '@wordpress/i18n'; |
| 3 | +import { PreviewCommandLoggerAction as LoggerAction } from 'common/logger-actions'; |
| 4 | +import { |
| 5 | + isDaemonRunning, |
| 6 | + startDaemon, |
| 7 | + isProxyProcessRunning, |
| 8 | + startProxyProcess, |
| 9 | +} from 'cli/lib/pm2-manager'; |
| 10 | +import { isRunningAsRoot, getElevatedPrivilegesMessage } from 'cli/lib/sudo-exec'; |
| 11 | +import { Logger, LoggerError } from 'cli/logger'; |
| 12 | +import { StudioArgv } from 'cli/types'; |
| 13 | + |
| 14 | +export async function runCommand(): Promise< void > { |
| 15 | + const logger = new Logger< LoggerAction >(); |
| 16 | + |
| 17 | + try { |
| 18 | + // Step 1: Ensure PM2 daemon is running |
| 19 | + if ( ! isDaemonRunning() ) { |
| 20 | + logger.reportStart( LoggerAction.LOAD, __( 'Starting PM2 daemon...' ) ); |
| 21 | + await startDaemon(); |
| 22 | + logger.reportSuccess( __( 'PM2 daemon started' ) ); |
| 23 | + } |
| 24 | + |
| 25 | + // Step 2: Check if proxy is already running |
| 26 | + const isRunning = await isProxyProcessRunning(); |
| 27 | + if ( isRunning ) { |
| 28 | + logger.reportSuccess( __( 'HTTP proxy already running' ) ); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + // Step 3: Check for elevated privileges |
| 33 | + if ( ! isRunningAsRoot() ) { |
| 34 | + throw new Error( getElevatedPrivilegesMessage() ); |
| 35 | + } |
| 36 | + |
| 37 | + // Step 4: Start proxy via PM2 |
| 38 | + logger.reportStart( LoggerAction.LOAD, __( 'Starting HTTP proxy server...' ) ); |
| 39 | + |
| 40 | + // Get the proxy daemon path (cli/proxy-daemon.ts compiled to dist) |
| 41 | + // __dirname is dist/cli when running the bundled CLI |
| 42 | + const proxyDaemonPath = path.resolve( __dirname, 'proxy-daemon.js' ); |
| 43 | + |
| 44 | + await startProxyProcess( proxyDaemonPath ); |
| 45 | + |
| 46 | + logger.reportSuccess( __( 'HTTP proxy server started' ) ); |
| 47 | + } catch ( error ) { |
| 48 | + if ( error instanceof LoggerError ) { |
| 49 | + logger.reportError( error ); |
| 50 | + } else { |
| 51 | + const loggerError = new LoggerError( __( 'Failed to start site infrastructure' ), error ); |
| 52 | + logger.reportError( loggerError ); |
| 53 | + } |
| 54 | + process.exit( 1 ); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export const registerCommand = ( yargs: StudioArgv ) => { |
| 59 | + return yargs.command( { |
| 60 | + command: 'start', |
| 61 | + describe: __( 'Start the HTTP proxy for custom domains (requires sudo)' ), |
| 62 | + handler: async () => { |
| 63 | + await runCommand(); |
| 64 | + }, |
| 65 | + } ); |
| 66 | +}; |
0 commit comments