← Files Flows by plugin.spaceARCHIVED FILE
lib/write-document.mjs
2.47 KB · Nov 30, 2026 · 00:17 UTC
import { open, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { documentSourceBytes, MAX_DOCUMENT_BYTES, readDocument, validateDocument } from './document.mjs';
import { withTestScenarios } from './test-scenarios.mjs';
export async function deleteDocument(file, expectedRevision) {
const path = await realpath(file);
const lockPath = `${path}.lock`;
let lock;
try { lock = await open(lockPath, 'wx', 0o600); }
catch (error) { if (error.code === 'EEXIST') throw Object.assign(new Error('Another update is in progress. Try again.'), { status: 409 }); throw error; }
try {
if ((await readDocument(path)).revision !== expectedRevision) throw Object.assign(new Error('The flow changed. Refresh it before deleting.'), { status: 409 });
await rm(path);
} finally { await lock.close(); await rm(lockPath, { force: true }); }
}
export async function updateDocument(file, expectedRevision, change) {
const path = await realpath(file);
const lockPath = `${path}.lock`;
let lock;
try { lock = await open(lockPath, 'wx', 0o600); }
catch (error) { if (error.code === 'EEXIST') throw Object.assign(new Error('Another update is in progress. Try again.'), { status: 409 }); throw error; }
const temporary = `${path}.${randomUUID()}.tmp`;
try {
const current = await readDocument(path);
if (current.revision !== expectedRevision) throw Object.assign(new Error('The flow changed. Reopen settings or repeat the capture with the current document.'), { status: 409 });
const changed = await change(current.document);
const result = validateDocument(changed);
if (!result.valid) throw Object.assign(new Error(result.errors.join('\n')), { status: 422 });
if (documentSourceBytes(changed) > MAX_DOCUMENT_BYTES) throw Object.assign(new Error('Flow source document exceeds 1 MB.'), { status: 422 });
const document = withTestScenarios(changed);
const content = `${JSON.stringify(document, null, 2)}\n`;
await writeFile(temporary, content, { flag: 'wx', mode: (await stat(path)).mode & 0o777 });
// Detect external editor changes made while preparing the update.
if ((await readDocument(path)).revision !== expectedRevision) throw Object.assign(new Error('The flow changed during this update. Try again.'), { status: 409 });
await rename(temporary, path);
return readDocument(path);
} finally { await rm(temporary, { force: true }); await lock.close(); await rm(lockPath, { force: true }); }
}
SHA-256: 88cce6998013d8db08827f74f46a017faa9b8ddb8f54f5848530104cde3b005d