585 lines
26 KiB
TypeScript
585 lines
26 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
import { constants as fsConstants, promises as fs } from "node:fs";
|
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
import { environment } from "@raycast/api";
|
|
import type { EntityType, PlaceholderMapping } from "../types";
|
|
import { whitelistKey } from "./project-whitelist";
|
|
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
|
import { restoreOriginalCase } from "./restore-case";
|
|
|
|
export { whitelistKey } from "./project-whitelist";
|
|
export type { ProjectWhitelistEntry } from "./project-whitelist";
|
|
|
|
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
|
|
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
|
export type SkippedProjectFile = { path: string; reason: string };
|
|
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] };
|
|
export type ProjectRun = {
|
|
version: 2;
|
|
origin?: "direct" | "imported";
|
|
id: string;
|
|
projectPath: string;
|
|
projectName: string;
|
|
createdAt: string;
|
|
mapping: PlaceholderMapping;
|
|
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
|
matchModes?: Record<string, "token" | "anywhere">;
|
|
files: RunFile[];
|
|
inPlace?: boolean;
|
|
/** The project source already contains outputs of an earlier in-place run. */
|
|
sourceInPlace?: boolean;
|
|
/** Previous immutable snapshot when a project run was revised after creation. */
|
|
revisedFrom?: string;
|
|
/** Word comment authors were reviewed with the explicit author recognizer. */
|
|
commentAuthorCoverage?: boolean;
|
|
/** Word tracked-change authors and deleted text were reviewed. */
|
|
reviewAuthorCoverage?: boolean;
|
|
/** Visible copy next to the source project; immutable snapshots remain in Raycast support. */
|
|
copyPath?: string;
|
|
};
|
|
|
|
const DOCUMENTS = new Set([".docx", ".xlsx", ".pptx", ".pdf"]);
|
|
const RESTORABLE_DOCUMENTS = new Set([".docx", ".xlsx", ".pptx"]);
|
|
const MARKDOWN_EXTENSIONS = new Set([".md", ".markdown", ".mdx"]);
|
|
const SECRET_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
const EXCLUDES = new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt",
|
|
".venv", "venv", "__pycache__", "target", "vendor", "coverage", ".cache", ".turbo",
|
|
".idea", ".vscode", "Pods", "DerivedData"]);
|
|
|
|
export function canonicalProjectPath(path: string): string {
|
|
return resolve(path);
|
|
}
|
|
|
|
function projectIdFor(path: string): string {
|
|
return createHash("sha1").update(canonicalProjectPath(path)).digest("hex").slice(0, 16);
|
|
}
|
|
|
|
async function isBinary(path: string): Promise<boolean> {
|
|
const file = await fs.open(path, "r");
|
|
try {
|
|
const buffer = Buffer.alloc(8192);
|
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
return buffer.subarray(0, bytesRead).includes(0);
|
|
} finally { await file.close(); }
|
|
}
|
|
|
|
async function isOfficeArchive(path: string): Promise<boolean> {
|
|
const file = await fs.open(path, "r");
|
|
try {
|
|
const header = Buffer.alloc(4);
|
|
const { bytesRead } = await file.read(header, 0, header.length, 0);
|
|
return bytesRead === 4 && header.equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
|
} finally { await file.close(); }
|
|
}
|
|
|
|
export function projectDataRoot(projectPath: string, support = environment.supportPath): string {
|
|
return join(support, "velum-projects", projectIdFor(projectPath));
|
|
}
|
|
|
|
export function rulesPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "rules.json");
|
|
}
|
|
|
|
export function whitelistPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "whitelist.json");
|
|
}
|
|
|
|
export function entityTypesPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "entity-types.json");
|
|
}
|
|
|
|
export async function loadProjectEntityTypes(projectPath: string, support?: string): Promise<EntityType[] | null> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(entityTypesPath(projectPath, support), "utf8")) as unknown;
|
|
if (!Array.isArray(value) || value.some((type) => typeof type !== "string" || !type)) {
|
|
throw new Error("Ungültige Kategorienauswahl für dieses Projekt.");
|
|
}
|
|
return [...new Set(value)];
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function saveProjectEntityTypes(projectPath: string, types: EntityType[], support?: string): Promise<void> {
|
|
const path = entityTypesPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify([...new Set(types)]), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} catch (error) {
|
|
await fs.rm(temp, { force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function loadProjectWhitelist(projectPath: string, support?: string): Promise<ProjectWhitelistEntry[]> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(whitelistPath(projectPath, support), "utf8")) as unknown;
|
|
if (!Array.isArray(value)) throw new Error("Ungültige Projekt-Whitelist.");
|
|
return value.filter((entry): entry is ProjectWhitelistEntry => Boolean(entry) && typeof entry === "object"
|
|
&& typeof entry.type === "string" && typeof entry.original === "string"
|
|
&& entry.type.length > 0 && entry.original.trim().length > 0);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function saveProjectWhitelist(projectPath: string, entries: ProjectWhitelistEntry[], support?: string): Promise<void> {
|
|
const unique = [...new Map(entries.map((entry) => [whitelistKey(entry),
|
|
{ type: entry.type.toUpperCase(), original: entry.original.trim() }])).values()];
|
|
const path = whitelistPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} catch (error) {
|
|
await fs.rm(temp, { force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function loadProjectRules(projectPath: string, support?: string): Promise<ProjectRule[]> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(rulesPath(projectPath, support), "utf8")) as unknown;
|
|
return Array.isArray(value) ? value.filter(isProjectRule) : [];
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function isProjectRule(value: unknown): value is ProjectRule {
|
|
if (!value || typeof value !== "object") return false;
|
|
const rule = value as Record<string, unknown>;
|
|
return ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"].includes(String(rule.type))
|
|
&& typeof rule.value === "string" && rule.value.trim().length >= 2;
|
|
}
|
|
|
|
export function parseProjectRules(input: string): ProjectRule[] {
|
|
const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
|
|
const match = /^(BEGRIFF|PERSON|ORG|ORT|FIRMA|KUNDE):\s*(.+)$/i.exec(line);
|
|
return match
|
|
? { type: match[1].toUpperCase() as ProjectRule["type"], value: match[2].trim() }
|
|
: { type: "BEGRIFF" as const, value: line };
|
|
});
|
|
if (rules.length > 500 || rules.some((rule) => rule.value.length < 2 || rule.value.length > 200)) {
|
|
throw new Error("Maximal 500 Begriffe mit jeweils 2 bis 200 Zeichen sind erlaubt.");
|
|
}
|
|
return rules.filter((rule, index) => rules.findIndex(
|
|
(other) => other.type === rule.type && other.value.toLocaleLowerCase() === rule.value.toLocaleLowerCase(),
|
|
) === index);
|
|
}
|
|
|
|
export async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise<void> {
|
|
const path = rulesPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
await fs.writeFile(path, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
|
|
}
|
|
|
|
export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
|
const result: Record<string, string[]> = {};
|
|
for (const rule of rules) (result[rule.type] ??= []).push(rule.value);
|
|
return result;
|
|
}
|
|
|
|
export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024): Promise<{
|
|
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
|
}> {
|
|
const files: ProjectFile[] = [];
|
|
const skipped: SkippedProjectFile[] = [];
|
|
const skip = (path: string, reason: string) => skipped.push({ path, reason });
|
|
async function walk(directory: string): Promise<void> {
|
|
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
|
const path = join(directory, entry.name);
|
|
const relPath = relative(root, path).split(sep).join("/");
|
|
if (entry.isSymbolicLink()) { skip(relPath, "Symbolischer Link"); continue; }
|
|
if (entry.isDirectory()) {
|
|
if (EXCLUDES.has(entry.name)) { skip(relPath, "Ausgeschlossener Ordner"); continue; }
|
|
await walk(path);
|
|
continue;
|
|
}
|
|
if (!entry.isFile()) continue;
|
|
if (entry.name.startsWith("~$") || entry.name.startsWith("._")) {
|
|
skip(relPath, "Temporäre Office-/macOS-Datei");
|
|
continue;
|
|
}
|
|
if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
|
skip(relPath, "Vertraulicher Dateityp");
|
|
continue;
|
|
}
|
|
const stat = await fs.stat(path);
|
|
if (stat.size > maxSize) { skip(relPath, "Datei zu groß"); continue; }
|
|
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
|
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
|
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
|
continue;
|
|
}
|
|
if (kind === "text") {
|
|
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
|
try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); }
|
|
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
|
}
|
|
files.push({ relPath, absPath: path, kind, size: stat.size });
|
|
}
|
|
}
|
|
await walk(root);
|
|
files.sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
return { files, skipped };
|
|
}
|
|
|
|
export function digest(data: Buffer): string {
|
|
return createHash("sha256").update(data).digest("hex");
|
|
}
|
|
|
|
/** Python API spans count Unicode code points; JavaScript strings use UTF-16 offsets. */
|
|
export function toUtf16Offsets<T extends { start: number; end: number }>(text: string, spans: T[]): T[] {
|
|
const positions = [0];
|
|
let offset = 0;
|
|
for (const character of text) {
|
|
offset += character.length;
|
|
positions.push(offset);
|
|
}
|
|
return spans.map((span) => {
|
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
|
|| span.start < 0 || span.end > positions.length - 1 || span.start >= span.end) {
|
|
throw new Error("Ungültige Trefferposition der Velum-API.");
|
|
}
|
|
return { ...span, start: positions[span.start], end: positions[span.end] };
|
|
});
|
|
}
|
|
|
|
export function replaceSpans(
|
|
source: string,
|
|
spans: Array<{ start: number; end: number; placeholder: string; id: string }>,
|
|
accepted: Set<string>,
|
|
): string {
|
|
let output = source;
|
|
for (const span of [...spans].filter((item) => accepted.has(item.id)).sort((a, b) => b.start - a.start)) {
|
|
if (span.start < 0 || span.end > source.length || span.start >= span.end) throw new Error("Ungültige Trefferposition.");
|
|
output = output.slice(0, span.start) + span.placeholder + output.slice(span.end);
|
|
}
|
|
return output;
|
|
}
|
|
|
|
function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], allowEmbedded = false): {
|
|
pattern: RegExp; originalFor: (match: string) => string | undefined;
|
|
} | undefined {
|
|
const keys = Object.keys(mapping).sort((a, b) => b.length - a.length);
|
|
if (!keys.length) return undefined;
|
|
const foldedKeys = new Map<string, string | null>();
|
|
for (const key of keys) {
|
|
const folded = key.toUpperCase();
|
|
if (foldedKeys.has(folded)) foldedKeys.set(folded, null);
|
|
else foldedKeys.set(folded, key);
|
|
}
|
|
const parts = keys.map((key) => {
|
|
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
return allowEmbedded || matchModes?.[key] === "anywhere"
|
|
? `${escaped}(?!\\d)` : `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
|
|
});
|
|
return {
|
|
pattern: new RegExp(parts.join("|"), "giu"),
|
|
originalFor: (match) => {
|
|
const key = Object.prototype.hasOwnProperty.call(mapping, match)
|
|
? match : foldedKeys.get(match.toUpperCase());
|
|
return key ? restoreOriginalCase(match, key, mapping[key].original) : undefined;
|
|
},
|
|
};
|
|
}
|
|
|
|
export function restoreTextWithCount(source: string, mapping: PlaceholderMapping,
|
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): { text: string; replacements: number } {
|
|
const pattern = restorePattern(mapping, matchModes, allowEmbedded);
|
|
let replacements = 0;
|
|
const text = pattern ? source.replace(pattern.pattern, (match) => {
|
|
const original = pattern.originalFor(match);
|
|
if (original === undefined) return match;
|
|
replacements++;
|
|
return original;
|
|
}) : source;
|
|
return { text, replacements };
|
|
}
|
|
|
|
export function restoreText(source: string, mapping: PlaceholderMapping,
|
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): string {
|
|
return restoreTextWithCount(source, mapping, matchModes, allowEmbedded).text;
|
|
}
|
|
|
|
/** Older snapshots can supply a missing key only when its meaning never changed. */
|
|
export function withUnambiguousHistoricalMappings(current: PlaceholderMapping,
|
|
earlier: PlaceholderMapping[]): PlaceholderMapping {
|
|
const result = { ...current };
|
|
const candidates = new Map<string, PlaceholderMapping[string] | null>();
|
|
for (const mapping of earlier) {
|
|
for (const [key, entry] of Object.entries(mapping)) {
|
|
if (Object.prototype.hasOwnProperty.call(current, key)) continue;
|
|
const previous = candidates.get(key);
|
|
if (previous === null) continue;
|
|
if (previous && (previous.original !== entry.original || previous.type !== entry.type)) {
|
|
candidates.set(key, null);
|
|
} else if (!previous) candidates.set(key, entry);
|
|
}
|
|
}
|
|
for (const [key, entry] of candidates) if (entry) result[key] = entry;
|
|
return result;
|
|
}
|
|
|
|
/** Report recognizable Velum IDs that remain after a Markdown restore. */
|
|
export function unresolvedPlaceholderIds(source: string, mappings: PlaceholderMapping[]): string[] {
|
|
const prefixes = new Set(mappings.flatMap((mapping) => Object.keys(mapping)
|
|
.map((key) => /^([\p{L}]+)_\d+$/u.exec(key)?.[1]).filter((value): value is string => Boolean(value))));
|
|
if (!prefixes.size) return [];
|
|
const alternatives = [...prefixes].sort((a, b) => b.length - a.length)
|
|
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternatives.join("|")})_\\d+(?!\\d)`, "giu");
|
|
return [...new Set(source.match(pattern) ?? [])];
|
|
}
|
|
|
|
export function restorePath(relPath: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string {
|
|
// Filenames can join a placeholder directly to another identifier fragment.
|
|
// Restricting replacements to word boundaries would leave those names masked.
|
|
const pattern = restorePattern(mapping, matchModes, true);
|
|
const segments = safeRelativePath(relPath).split("/").map((segment) => {
|
|
const restored = pattern ? segment.replace(pattern.pattern, (match) => pattern.originalFor(match) ?? match) : segment;
|
|
if (restored.includes("/") || restored.includes("\\") || restored === "." || restored === "..") {
|
|
throw new Error("Rückübersetzter Dateiname enthält einen ungültigen Pfadteil.");
|
|
}
|
|
return restored;
|
|
});
|
|
return safeRelativePath(segments.join("/"));
|
|
}
|
|
|
|
export function safeRelativePath(path: string): string {
|
|
const normalized = path.split("\\").join("/");
|
|
if (!normalized || normalized.startsWith("/") || normalized.split("/").some((part) => part === ".." || part === "." || !part)) {
|
|
throw new Error("Ungültiger Ausgabepfad.");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
export async function createRun(projectPath: string, support = environment.supportPath): Promise<{
|
|
run: ProjectRun; directory: string;
|
|
}> {
|
|
projectPath = canonicalProjectPath(projectPath);
|
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
|
|
const directory = join(projectDataRoot(projectPath, support), "runs", id);
|
|
await fs.mkdir(join(directory, "files"), { recursive: true, mode: 0o700 });
|
|
return {
|
|
directory,
|
|
run: { version: 2, origin: "direct", id, projectPath, projectName: basename(projectPath),
|
|
createdAt: new Date().toISOString(), mapping: {}, files: [] },
|
|
};
|
|
}
|
|
|
|
export async function saveRun(directory: string, run: ProjectRun): Promise<void> {
|
|
const dest = join(directory, "run.json");
|
|
const tmp = `${dest}.tmp`;
|
|
await fs.writeFile(tmp, JSON.stringify(run), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(tmp, dest);
|
|
}
|
|
|
|
export function runCopiesPath(run: ProjectRun, directory: string): string {
|
|
return run.copyPath ?? join(directory, "files");
|
|
}
|
|
|
|
export async function scanRestorableCopyFiles(run: ProjectRun, directory: string, current = true): Promise<{
|
|
root: string; files: ProjectFile[]; skipped: number;
|
|
}> {
|
|
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
|
|
let root = current && inPlace ? canonicalProjectPath(run.projectPath)
|
|
: current ? runCopiesPath(run, directory) : join(directory, "files");
|
|
if (current && !inPlace && run.copyPath) {
|
|
try {
|
|
if (!(await fs.lstat(root)).isDirectory()) throw new Error("Kopienpfad ist kein regulärer Ordner.");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
root = join(directory, "files");
|
|
}
|
|
}
|
|
const scan = await scanProjectFiles(root);
|
|
const files = scan.files.filter((file) => file.kind === "text" || isRestorableDocument(file.relPath));
|
|
return { root, files, skipped: scan.skipped.length + scan.files.length - files.length };
|
|
}
|
|
|
|
/** Publish only output files next to the project, without the private mapping. */
|
|
export async function publishProjectCopies(run: ProjectRun, directory: string): Promise<string> {
|
|
const projectPath = canonicalProjectPath(run.projectPath);
|
|
const parent = dirname(projectPath);
|
|
const target = join(parent, `${basename(projectPath)}-Velum-${run.id}`);
|
|
try {
|
|
await fs.lstat(target);
|
|
throw new Error(`Kopienordner bereits vorhanden: ${target}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
const staging = await fs.mkdtemp(join(parent, `.${basename(projectPath)}-Velum-`));
|
|
try {
|
|
for (const file of run.files) {
|
|
const source = resolveWithin(join(directory, "files"), file.output);
|
|
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Ausgabedatei: ${file.output}`);
|
|
const destination = resolveWithin(staging, file.output);
|
|
await fs.mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(source, destination, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(destination, 0o600);
|
|
}
|
|
await fs.rename(staging, target);
|
|
return target;
|
|
} catch (error) {
|
|
await fs.rm(staging, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function listRuns(projectPath: string, support = environment.supportPath): Promise<Array<{
|
|
run: ProjectRun; directory: string;
|
|
}>> {
|
|
const root = join(projectDataRoot(projectPath, support), "runs");
|
|
let entries;
|
|
try { entries = await fs.readdir(root, { withFileTypes: true }); }
|
|
catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
const runs = [];
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
const directory = join(root, entry.name);
|
|
try {
|
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
|
if (run.version === 2 && canonicalProjectPath(run.projectPath) === canonicalProjectPath(projectPath)) {
|
|
runs.push({ run, directory });
|
|
}
|
|
} catch { /* incomplete run: not offered for restoration */ }
|
|
}
|
|
return runs.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
|
}
|
|
|
|
/** An unchanged output from an in-place run can be carried into the next snapshot. */
|
|
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
|
try {
|
|
const previous = await fs.readFile(resolveWithin(join(directory, "files"), relPath));
|
|
return digest(previous) === currentHash;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function listAllRuns(support = environment.supportPath): Promise<Array<{
|
|
run: ProjectRun; directory: string;
|
|
}>> {
|
|
const root = join(support, "velum-projects");
|
|
let projects;
|
|
try { projects = await fs.readdir(root, { withFileTypes: true }); }
|
|
catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
const results = [];
|
|
for (const project of projects) {
|
|
if (!project.isDirectory()) continue;
|
|
const runsDir = join(root, project.name, "runs");
|
|
let entries;
|
|
try { entries = await fs.readdir(runsDir, { withFileTypes: true }); }
|
|
catch { continue; }
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
const directory = join(runsDir, entry.name);
|
|
try {
|
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
|
if (run.version === 2) results.push({ run, directory });
|
|
} catch { /* incomplete run */ }
|
|
}
|
|
}
|
|
return results.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
|
}
|
|
|
|
export function isRestorableDocument(filename: string): boolean {
|
|
return RESTORABLE_DOCUMENTS.has(extname(filename).toLowerCase());
|
|
}
|
|
|
|
export function isMarkdownFile(filename: string): boolean {
|
|
return MARKDOWN_EXTENSIONS.has(extname(filename).toLowerCase());
|
|
}
|
|
|
|
export function resolveWithin(root: string, relPath: string): string {
|
|
const target = resolve(root, safeRelativePath(relPath));
|
|
if (!target.startsWith(resolve(root) + sep)) throw new Error("Ausgabepfad verlässt den Zielordner.");
|
|
return target;
|
|
}
|
|
|
|
async function assertNoSymlinkParents(root: string, relPath: string): Promise<void> {
|
|
const parts = safeRelativePath(relPath).split("/");
|
|
let parent = resolve(root);
|
|
for (const part of parts.slice(0, -1)) {
|
|
parent = join(parent, part);
|
|
try {
|
|
if ((await fs.lstat(parent)).isSymbolicLink()) throw new Error(`Symbolischer Link im Ausgabepfad: ${relPath}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Replaces selected originals only after every output exists and a private backup is complete. */
|
|
export async function replaceProjectFilesInPlace(projectPath: string, runDirectory: string, files: RunFile[]): Promise<void> {
|
|
const root = resolve(projectPath);
|
|
const sourcePaths = new Set(files.map((file) => resolveWithin(root, file.source)));
|
|
const targetPaths = new Set<string>();
|
|
const sourceModes = new Map<string, number>();
|
|
for (const file of files) {
|
|
const source = resolveWithin(root, file.source);
|
|
const target = resolveWithin(root, file.output);
|
|
if (targetPaths.has(target)) throw new Error(`Doppelter Zielname: ${file.output}`);
|
|
targetPaths.add(target);
|
|
await assertNoSymlinkParents(root, file.output);
|
|
const sourceInfo = await fs.lstat(source);
|
|
if (!sourceInfo.isFile()) throw new Error(`Quelldatei ist keine reguläre Datei: ${file.source}`);
|
|
sourceModes.set(source, sourceInfo.mode & 0o777);
|
|
try {
|
|
await fs.lstat(target);
|
|
if (!sourcePaths.has(target)) throw new Error(`Zielname bereits vorhanden: ${file.output}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
await fs.access(resolveWithin(join(runDirectory, "files"), file.output));
|
|
}
|
|
|
|
const backupRoot = join(runDirectory, "backup");
|
|
for (const file of files) {
|
|
const backup = resolveWithin(backupRoot, file.source);
|
|
await fs.mkdir(dirname(backup), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(root, file.source), backup, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(backup, 0o600);
|
|
}
|
|
|
|
const written: string[] = [];
|
|
try {
|
|
for (const file of files) await fs.unlink(resolveWithin(root, file.source));
|
|
for (const file of files) {
|
|
const target = resolveWithin(root, file.output);
|
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(join(runDirectory, "files"), file.output), target, fsConstants.COPYFILE_EXCL);
|
|
written.push(target);
|
|
await fs.chmod(target, sourceModes.get(resolveWithin(root, file.source)) ?? 0o600);
|
|
}
|
|
} catch (error) {
|
|
for (const target of written) await fs.rm(target, { force: true });
|
|
for (const file of files) {
|
|
const source = resolveWithin(root, file.source);
|
|
try { await fs.lstat(source); }
|
|
catch (missing) {
|
|
if ((missing as NodeJS.ErrnoException).code !== "ENOENT") throw missing;
|
|
await fs.mkdir(dirname(source), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(backupRoot, file.source), source, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(source, sourceModes.get(source) ?? 0o600);
|
|
}
|
|
}
|
|
throw new Error(`Ersetzen fehlgeschlagen; Originale wurden wiederhergestellt. Sicherung: ${backupRoot}. ${(error as Error).message}`);
|
|
}
|
|
}
|