export interface CanonicalEventEmitterOptions { /** Resolves only after the target has accepted this complete protocol line. */ write: (line: string) => void | Promise; channelUrl?: string; channelTimeoutMs?: number; post?: ( url: string, line: string, signal: AbortSignal, ) => Promise<{ ok: boolean; status: number }>; } export const DEFAULT_CANONICAL_EVENT_CHANNEL_TIMEOUT_MS = 5_000; /** * The sole post-commit writer for a Monitor-attached stdout protocol stream. * It accepts already-presented records; ordinary logs and runtime components * never receive this writer. */ export class CanonicalEventEmitter { constructor(private readonly options: CanonicalEventEmitterOptions) {} async emit(record: Record): Promise { const line = `${JSON.stringify(record)}\n`; // CanonicalMonitor may acknowledge only after the write callback resolves; // Writable.write() returning true is not itself a delivery acknowledgement. await this.options.write(line); if (!this.options.channelUrl) return; const post = this.options.post ?? (async (url: string, body: string, signal: AbortSignal) => { const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal, }); return { ok: response.ok, status: response.status }; }); const timeoutMs = this.options.channelTimeoutMs ?? DEFAULT_CANONICAL_EVENT_CHANNEL_TIMEOUT_MS; const controller = new AbortController(); let timer: ReturnType | undefined; const timeout = new Promise((_resolve, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error(`Monitor channel timed out after ${timeoutMs}ms.`)); }, timeoutMs); }); try { const response = await Promise.race([ post(this.options.channelUrl, line, controller.signal), timeout, ]); if (!response.ok) { throw new Error(`Monitor channel returned HTTP ${response.status}.`); } } finally { if (timer) clearTimeout(timer); } } } /** Keep the raw process stdout handle in this one composition-root factory. */ export function createProcessCanonicalEventEmitter( options: Pick< CanonicalEventEmitterOptions, 'channelUrl' | 'channelTimeoutMs' | 'post' > = {}, ): CanonicalEventEmitter { return new CanonicalEventEmitter({ ...options, write: (line) => new Promise((resolve, reject) => { process.stdout.write(line, (error) => { if (error) reject(error); else resolve(); }); }), }); }