import { randomUUID } from 'node:crypto'; import { mkdir, rename, rm, writeFile } from 'node:fs/promises'; import { dirname, isAbsolute, resolve } from 'node:path'; export function resolveWorkflowPath(cwd: string, path: string): string { return isAbsolute(path) ? path : resolve(cwd, path); } export async function atomicWriteText( cwd: string, path: string, content: string, ): Promise { const target = resolveWorkflowPath(cwd, path); await mkdir(dirname(target), { recursive: true }); const temp = `${target}.tmp-${process.pid}-${randomUUID()}`; try { await writeFile(temp, content, 'utf8'); await rename(temp, target); } finally { await rm(temp, { force: true }).catch(() => undefined); } return target; } export async function atomicWriteJson( cwd: string, path: string, value: unknown, ): Promise { return atomicWriteText(cwd, path, `${JSON.stringify(value, null, 2)}\n`); } export async function ensureWorkflowDir( cwd: string, path: string, ): Promise { const target = resolveWorkflowPath(cwd, path); await mkdir(target, { recursive: true }); return target; } /** A Windows reader can transiently deny rename-over-existing. Retry only * publishing the checkpoint, never the workflow or its external actions. */ export async function publishCheckpoint(write: () => Promise, platform: NodeJS.Platform = process.platform): Promise { for (let attempt = 0; ; attempt++) { try { await write(); return; } catch (error) { const { code, syscall } = error as NodeJS.ErrnoException; if (platform !== 'win32' || syscall !== 'rename' || (code !== 'EPERM' && code !== 'EBUSY') || attempt >= 5) throw error; await new Promise(resolve => setTimeout(resolve, 10 * 2 ** attempt)); } } }