import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs'; import { dirname } from 'path'; /** * One factual local Event accepted before the Runtime is available. * This is a narrow crash-safe bridge, not a second Event journal: the owner * must commit it through EventIngress and then clear it by sourceEventId. */ export interface PendingEventHandoff { type: string; payload: Record; sourceId: string; sourceEventId: string; occurredAt: string; } function valid(value: unknown): value is PendingEventHandoff { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const row = value as Record; return typeof row.type === 'string' && row.type.length > 0 && !!row.payload && typeof row.payload === 'object' && !Array.isArray(row.payload) && typeof row.sourceId === 'string' && row.sourceId.length > 0 && typeof row.sourceEventId === 'string' && row.sourceEventId.length > 0 && typeof row.occurredAt === 'string' && row.occurredAt.length > 0; } export class FilePendingEventHandoff { constructor(readonly path: string) {} read(): PendingEventHandoff | undefined { try { const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as unknown; return valid(parsed) ? structuredClone(parsed) : undefined; } catch { return undefined; } } write(value: PendingEventHandoff): void { if (!valid(value)) throw new TypeError('Invalid pending Event handoff.'); mkdirSync(dirname(this.path), { recursive: true }); const temporary = `${this.path}.${process.pid}.tmp`; writeFileSync(temporary, JSON.stringify(value), { encoding: 'utf8', mode: 0o600 }); try { renameSync(temporary, this.path); } catch { try { unlinkSync(this.path); } catch {} renameSync(temporary, this.path); } } clear(expectedSourceEventId: string): boolean { if (this.read()?.sourceEventId !== expectedSourceEventId) return false; try { unlinkSync(this.path); return true; } catch { return false; } } }