From 8557a9b80925e9965330ecde71ed535527980c01 Mon Sep 17 00:00:00 2001 From: muena Date: Thu, 15 Oct 2026 09:01:44 +0200 Subject: [PATCH] Restore embedded placeholders in Markdown project exports --- src/lib/project-revision.ts | 5 ++-- src/lib/velum-project.ts | 50 ++++++++++++++++++++++++++++++----- src/restore-project-files.tsx | 30 ++++++++++++++------- tests/velum-project.test.ts | 22 +++++++++++++++ 4 files changed, 88 insertions(+), 19 deletions(-) diff --git a/src/lib/project-revision.ts b/src/lib/project-revision.ts index 87f9989..1701850 100644 --- a/src/lib/project-revision.ts +++ b/src/lib/project-revision.ts @@ -3,7 +3,7 @@ import { basename, dirname, join } from "node:path"; import type { PlaceholderMapping } from "../types"; import { canonicalPerson } from "./project-review"; import { - createRun, digest, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies, + createRun, digest, isMarkdownFile, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies, replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText, saveProjectWhitelist, saveRun, } from "./velum-project"; @@ -143,7 +143,8 @@ export async function reviseProjectRun(args: { const output = file.kind === "document" && isRestorableDocument(file.output) ? await rewriteDocument(basename(file.output), data, plan.replacements) : file.kind === "document" ? data - : Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes), "utf8"); + : Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes, + isMarkdownFile(file.output)), "utf8"); await fs.writeFile(target, output, { flag: "wx", mode: 0o600 }); run.files.push({ source: file.output, output: outputPath, kind: file.kind }); } diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index 05b901e..1b79d6e 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -40,6 +40,7 @@ export type ProjectRun = { 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", @@ -264,7 +265,7 @@ export function replaceSpans( return output; } -function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], pathSegment = false): { +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); @@ -277,8 +278,8 @@ function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["mat } const parts = keys.map((key) => { const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return pathSegment || matchModes?.[key] === "anywhere" - ? escaped : `(? { const original = pattern.originalFor(match); @@ -303,8 +304,39 @@ export function restoreTextWithCount(source: string, mapping: PlaceholderMapping return { text, replacements }; } -export function restoreText(source: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string { - return restoreTextWithCount(source, mapping, matchModes).text; +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(); + 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(`(? Promise } ; } -function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean }) { +function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: ProjectRun[] }) { const [files, setFiles] = useState([]); const [sourceRoot, setSourceRoot] = useState(""); const [selected, setSelected] = useState>(new Set()); @@ -173,10 +173,12 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo const parent = join(homedir(), "Downloads", "Velum"); let targetRoot: string | undefined; try { - if (!Object.keys(props.run.mapping).length) throw new Error("Dieser Projektstand hat keine Übersetzungstabelle."); + const mappings = [props.run.mapping, ...props.earlierRuns.map((run) => run.mapping)]; + const mapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1)); + if (!Object.keys(mapping).length) throw new Error("Dieser Projektstand hat keine Übersetzungstabelle."); const names = new Set(); const planned = files.filter((item) => selected.has(item.relPath)).map((file) => ({ - file, restoredName: restorePath(file.relPath, props.run.mapping, props.run.matchModes), + file, restoredName: restorePath(file.relPath, mapping, props.run.matchModes), })); const renamedFiles = planned.filter(({ file, restoredName }) => restoredName !== file.relPath).length; let contentReplacements = 0; @@ -193,9 +195,14 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo const data = await fs.readFile(source); let result: Buffer; if (file.kind === "document") { - result = await depseudonymizeDocument(basename(file.relPath), data, props.run.mapping); + result = await depseudonymizeDocument(basename(file.relPath), data, mapping); } else { - const restored = restoreTextWithCount(data.toString("utf8"), props.run.mapping, props.run.matchModes); + const markdown = isMarkdownFile(file.relPath); + const restored = restoreTextWithCount(data.toString("utf8"), mapping, props.run.matchModes, markdown); + if (markdown) { + const unresolved = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings); + if (unresolved.length) throw new Error(`${file.relPath}: Platzhalter ohne eindeutige Zuordnung: ${unresolved.slice(0, 5).join(", ")}${unresolved.length > 5 ? " …" : ""}. Bitte Projektstand prüfen.`); + } contentReplacements += restored.replacements; result = Buffer.from(restored.text, "utf8"); } @@ -256,12 +263,13 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { return - {props.entries.map(({ run, directory }) => push()} /> + onAction={() => push( entry.run)} />)} /> } /> @@ -269,7 +277,8 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { onAction={() => showInFinder(runCopiesPath(run, directory))} /> {run.copyPath && push()} />} + onAction={() => push( entry.run)} />)} />} } />)} ; @@ -300,7 +309,8 @@ export default function Command() { ...(entries.length > 1 ? [{ text: `${entries.length} Stände` }] : [])]} actions={ push()} /> + onAction={() => push( entry.run)} />)} /> } /> { expect(project.restoreText("BerichtPERSON_01", { PERSON_01: { original: "Max Mustermann", type: "PERSON" }, })).toBe("BerichtPERSON_01"); + expect(project.restoreText("Fachkonzept `PROJEKT_01_Fachkonzept_V03.docx` widerspricht Kommentar PERSON_61 (ID 1088)", { + PROJEKT_01: { original: "Beispielprojekt", type: "PROJEKT" }, + PERSON_61: { original: "Mara Muster", type: "PERSON" }, + }, undefined, true)).toBe("Fachkonzept `Beispielprojekt_Fachkonzept_V03.docx` widerspricht Kommentar Mara Muster (ID 1088)"); + expect(project.restoreText("PERSON_0101 und PERSON_01", { + PERSON_01: { original: "Max Mustermann", type: "PERSON" }, + }, undefined, true)).toBe("PERSON_0101 und Max Mustermann"); expect(project.restorePath("PERSON_0101.txt", { PERSON_01: { original: "Falsch", type: "PERSON" }, PERSON_0101: { original: "Richtig", type: "PERSON" }, @@ -179,6 +186,21 @@ describe("Velum-Projektstände", () => { expect(() => project.safeRelativePath("../geheim.txt")).toThrow(); }); + it("verwendet ältere Zuordnungen nur bei übereinstimmender Bedeutung und meldet übrig gebliebene Markdown-Platzhalter", () => { + const current = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } }; + const older = [ + { PERSON_61: { original: "Mara Muster", type: "PERSON" }, PROJEKT_01: { original: "Projekt Eins", type: "PROJEKT" } }, + { PERSON_61: { original: "Mara Muster", type: "PERSON" }, PROJEKT_01: { original: "Projekt Zwei", type: "PROJEKT" } }, + ]; + const mapping = project.withUnambiguousHistoricalMappings(current, older); + expect(mapping.PERSON_61?.original).toBe("Mara Muster"); + expect(mapping.PROJEKT_01).toBeUndefined(); + const restored = project.restoreText("PERSON_61 und PROJEKT_01", mapping, undefined, true); + expect(restored).toBe("Mara Muster und PROJEKT_01"); + expect(project.unresolvedPlaceholderIds(restored, [current, ...older])).toEqual(["PROJEKT_01"]); + expect(project.isMarkdownFile("Notizen.MD")).toBe(true); + }); + it("übernimmt API-Trefferpositionen auch nach einem Emoji korrekt", () => { const text = "😀 Max"; const spans = project.toUtf16Offsets(text, [{ id: "max", start: 2, end: 5, placeholder: "PERSON_01" }]);