import { spawn } from 'node:child_process';
export function splitLines(buffer, chunk) {
    const parts = (buffer + chunk).split('\n');
    const rest = parts.pop() ?? '';
    const lines = parts.map((part) => part.trim()).filter((part) => part.length > 0);
    return { lines, rest };
}
class ChildProcessSetupHandle {
    child;
    lineHandler = null;
    exitHandler = null;
    buffer = '';
    constructor(child) {
        this.child = child;
        this.child.stdout.setEncoding('utf-8');
        this.child.stdout.on('data', (chunk) => {
            this.consume(chunk);
        });
        this.child.on('close', (code) => {
            this.flush();
            this.exitHandler?.(code);
        });
        this.child.on('error', () => {
            this.exitHandler?.(null);
        });
    }
    get pid() {
        return this.child.pid ?? null;
    }
    onLine(handler) {
        this.lineHandler = handler;
    }
    onExit(handler) {
        this.exitHandler = handler;
    }
    writeLine(line) {
        if (this.child.stdin.writable) {
            this.child.stdin.write(`${line}\n`);
        }
    }
    kill() {
        this.child.kill();
    }
    consume(chunk) {
        const { lines, rest } = splitLines(this.buffer, chunk);
        this.buffer = rest;
        for (const line of lines) {
            this.lineHandler?.(line);
        }
    }
    flush() {
        const remaining = this.buffer.trim();
        this.buffer = '';
        if (remaining.length > 0) {
            this.lineHandler?.(remaining);
        }
    }
}
export class SetupProcessChildProcessGateway {
    options;
    constructor(options) {
        this.options = options;
    }
    spawn(options) {
        const args = [this.options.cliPath, 'setup', '--json'];
        const projectPath = options?.projectPath ?? null;
        if (projectPath !== null) {
            args.push(projectPath);
        }
        const child = spawn(process.execPath, args, {
            stdio: ['pipe', 'pipe', 'pipe'],
            env: { ...process.env },
        });
        return new ChildProcessSetupHandle(child);
    }
}
//# sourceMappingURL=setupProcess.childProcess.gateway.js.map