import {ChildProcess, spawn} from 'child_process'; import {DevLogger} from './logger'; import * as chalk from 'chalk'; const logger = new DevLogger(); export class App { private baseUrl?: string; public async install() { const response = await fetch(`${this.baseUrl}/lifecycle/install`, {method: 'post'}); const json = (await response.json()) as any; if (!json.success) { throw new Error('App installation failed'); } } public async fetchFunctionEndpoints(): Promise { const response = await fetch(`${this.baseUrl}/functions`); const json = (await response.json()) as any; return Object.values(json); } public start(): Promise { return new Promise((resolve, reject) => { const app = spawn('yarn', ['run', 'start-app'], {shell: true}); process.on('exit', () => app.kill()); let started = false; app.stdout.on('data', (data) => { data.toString().trim().split('\n').forEach((str: string) => { if (!started && str.startsWith('App listening on port')) { started = true; this.baseUrl = `http://localhost:${str.replace('App listening on port ', '')}`; console.log(chalk.gray('App started successfully')); console.log(chalk.gray(`App logs will be piped to ${logger.logFile}`)); resolve(app); } logger.log(str); }); }); app.stderr.on('data', (data) => { data.toString().split('\n').forEach(logger.log); }); app.on('error', (e) => { console.error(e); reject('App failed to start'); }); app.on('close', (code) => { console.log(`app exited with code ${code}`); }); }); } }