forked from r.muellner/velum-raycast
fix: stream large project texts and scope API capabilities
Analyze UTF-8 text files as bounded batches of complete lines and reassemble only approved spans without loading entire files. Preserve line endings, BOM, Unicode offsets and source-change checks. Scope capability checks to selected file types, report missing features and HTTP failures, and retain the required Office image-policy handling. Cover large files, chunk boundaries, mappings and failure cleanup with regression tests.
This commit is contained in:
55
README.md
55
README.md
@@ -10,6 +10,24 @@ Projektbegriffe werden zeilenweise als `BEGRIFF: KundenSuite` oder `PERSON: Max
|
|||||||
|
|
||||||
`Projektdateien nachbearbeiten` bietet für den aktuellen Projektstand zwei Wege: Zuordnungen nachträglich in Klartext zurückwandeln und als Projekt-Ausnahme speichern sowie Personenplatzhalter nachträglich zusammenführen. Beide Änderungen betreffen Inhalte und Dateinamen; der vorige Stand bleibt als Sicherung erhalten. Bei zuvor direkt ersetzten Projektdateien wird der Ordner nach einer Bestätigung ebenfalls aktualisiert, sofern keine Datei seit dem letzten Stand verändert wurde. Für Projekte mit Kopien entsteht ein neuer Stand außerhalb des Quellordners. Ältere Stände können weiterhin dateiweise als Klartext-Kopien unter `~/Downloads/Velum` exportiert werden. Die Projektfunktion benötigt eine Velum-API mit `/api/project-capabilities`, Trefferprüfung für Dokumente, projektbezogenen `force_masks` und `/api/depseudonymize-document`.
|
`Projektdateien nachbearbeiten` bietet für den aktuellen Projektstand zwei Wege: Zuordnungen nachträglich in Klartext zurückwandeln und als Projekt-Ausnahme speichern sowie Personenplatzhalter nachträglich zusammenführen. Beide Änderungen betreffen Inhalte und Dateinamen; der vorige Stand bleibt als Sicherung erhalten. Bei zuvor direkt ersetzten Projektdateien wird der Ordner nach einer Bestätigung ebenfalls aktualisiert, sofern keine Datei seit dem letzten Stand verändert wurde. Für Projekte mit Kopien entsteht ein neuer Stand außerhalb des Quellordners. Ältere Stände können weiterhin dateiweise als Klartext-Kopien unter `~/Downloads/Velum` exportiert werden. Die Projektfunktion benötigt eine Velum-API mit `/api/project-capabilities`, Trefferprüfung für Dokumente, projektbezogenen `force_masks` und `/api/depseudonymize-document`.
|
||||||
|
|
||||||
|
### Bilder in Office/PDF
|
||||||
|
|
||||||
|
Der Projektdateien-Befehl bietet `placeholder` (Standard bei jedem neuen Aufruf),
|
||||||
|
`remove` und `keep`. Die Auswahl gilt unverändert für Analyse, Trefferprüfung,
|
||||||
|
Wiederholung und endgültige Ausgabe. `keep` zeigt deutliche Warnungen vor der
|
||||||
|
Analyse, vor dem Anwenden und im Ergebnis. Bildinhalte werden nicht analysiert.
|
||||||
|
Der Platzhaltertext lautet: „Bild aus Datenschutzgründen entfernt. Das ursprüngliche
|
||||||
|
Bild wurde im Zuge der Pseudonymisierung entfernt.“ Die Bereinigung übernimmt das
|
||||||
|
Velum-Backend; es sind keine zusätzlichen KI-Modelle erforderlich.
|
||||||
|
|
||||||
|
Der Backend-Fähigkeitsnachweis `document_image_policy` und die bestätigte Bildoption
|
||||||
|
mit Bildzählern sind für Dokumente erforderlich. Ohne diese Bestätigung wird kein
|
||||||
|
Dokument als erfolgreich verarbeitet ausgegeben. Die Wahl wird im Projektstand
|
||||||
|
festgehalten; ältere Office-Stände ohne Bildnachweis oder mit anderer Auswahl
|
||||||
|
werden erneut verarbeitet. Geänderte Bildoptionen stellen bereits entfernte Bilder
|
||||||
|
nicht wieder her. Im Projektstand stehen je Datei die Zähler und Warnungen;
|
||||||
|
der Abschluss zeigt die Summen für den erzeugten Stand einschließlich übernommener Dateien.
|
||||||
|
|
||||||
### Einmalige Übernahme aus KI Datenschutz
|
### Einmalige Übernahme aus KI Datenschutz
|
||||||
|
|
||||||
Velum enthält **keinen** Laufzeit-Zugriff auf die frühere Extension. Das eigenständige Skript `tools/migrate-ki-datenschutz.mjs` wandelt einen bereits anonymisierten KI-Datenschutz-Projektordner samt seiner eingefrorenen Variante-Tabelle in einen Velum-Projektstand um. Es verändert weder den alten Ordner noch die alte Tabelle. Der neue Stand erscheint anschließend unter `Projektdateien nachbearbeiten`; Begriffe nur für dieses Projekt werden als Velum-Projektregeln übernommen. Alle Inhalte bleiben während der Migration lokal und werden nicht an eine API gesendet. Im Terminal protokolliert das Skript nur Zahlen, keine Werte oder Dateinamen.
|
Velum enthält **keinen** Laufzeit-Zugriff auf die frühere Extension. Das eigenständige Skript `tools/migrate-ki-datenschutz.mjs` wandelt einen bereits anonymisierten KI-Datenschutz-Projektordner samt seiner eingefrorenen Variante-Tabelle in einen Velum-Projektstand um. Es verändert weder den alten Ordner noch die alte Tabelle. Der neue Stand erscheint anschließend unter `Projektdateien nachbearbeiten`; Begriffe nur für dieses Projekt werden als Velum-Projektregeln übernommen. Alle Inhalte bleiben während der Migration lokal und werden nicht an eine API gesendet. Im Terminal protokolliert das Skript nur Zahlen, keine Werte oder Dateinamen.
|
||||||
@@ -107,3 +125,40 @@ npm run build # ray build -e dist
|
|||||||
```
|
```
|
||||||
|
|
||||||
Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle).
|
Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle).
|
||||||
|
|
||||||
|
### Diagnose und Speicherbedarf der Projektanalyse
|
||||||
|
|
||||||
|
Die Fähigkeitsprüfung richtet sich nach den ausgewählten Dateien. Textprojekte
|
||||||
|
benötigen `request_force_masks`; Office/PDF zusätzlich die Dokumentprüfung,
|
||||||
|
Wiederherstellung, Autorenprüfung und `document_image_policy`. Fehlt eine
|
||||||
|
Fähigkeit, zeigt Raycast ihren Namen und die angesprochene API-URL. Fehlende
|
||||||
|
Endpunkte (404/405), Anmeldung/Proxy (HTTP-Status oder HTML) und Zeitlimits werden
|
||||||
|
getrennt gemeldet. Die Prüfung hat 15 Sekunden, jede Textanalyse-Anfrage 60 Sekunden Zeit.
|
||||||
|
|
||||||
|
Am 8. November 2026 meldete `https://velum.elycon.solutions/api/project-capabilities`
|
||||||
|
alle bisherigen Projektfähigkeiten, aber kein `document_image_policy`. Die lokale
|
||||||
|
API enthält diese Bildbehandlung bereits. Für Office/PDF muss das Backend daher
|
||||||
|
auf diesen Stand aktualisiert werden; ein höheres Upload-Limit löst den
|
||||||
|
Versionskonflikt nicht. Die Bildprüfung wird nicht umgangen.
|
||||||
|
|
||||||
|
Textdateien werden unabhängig von ihrer Gesamtgröße als UTF-8-Datenstrom gelesen.
|
||||||
|
Analysepakete bestehen aus vollständigen Zeilen und enthalten höchstens 24.000
|
||||||
|
UTF-16-Einheiten samt Wortkontext an den Grenzen. Kleine Dateien teilen sich
|
||||||
|
weiterhin API-Pakete. Zuordnungen gelten über alle Pakete und Dateien hinweg;
|
||||||
|
Unicode-Positionen und die bisherige Auswahl einzelner Vorkommen bleiben erhalten.
|
||||||
|
Eine einzelne Zeile mit mehr als 20.000 UTF-16-Einheiten wird mit Dateiname und
|
||||||
|
Zeilennummer abgelehnt, statt ein Wort zu zerschneiden.
|
||||||
|
|
||||||
|
Die Ausgabe wird aus dem ursprünglichen Datenstrom und ausschließlich den
|
||||||
|
bestätigten Trefferpositionen zusammengesetzt. Zeilenreihenfolge, CRLF/LF/CR,
|
||||||
|
UTF-8-BOM und die letzte Zeile ohne Umbruch bleiben erhalten. Auch Hashprüfungen,
|
||||||
|
das Übernehmen unveränderter Dateien und Prüfungen vor dem Ersetzen lesen große
|
||||||
|
Dateien abschnittsweise. HTTP 413 und Serverfehler werden bei mehrteiligen
|
||||||
|
Paketen durch begrenztes Aufteilen eingegrenzt; Authentifizierungs- und
|
||||||
|
Validierungsfehler werden nicht wiederholt.
|
||||||
|
|
||||||
|
Die 20-MiB-Grenze gilt weiterhin für Office/PDF-Uploads und nicht mehr für
|
||||||
|
Textdateien. Es bleiben höchstens 50.000 Prüftreffer zulässig. Originale werden
|
||||||
|
erst nach der bestehenden Bestätigung und mit den bestehenden Änderungsprüfungen
|
||||||
|
und Backups ersetzt. Bei ungültigem UTF-8, Quelländerungen oder Schreibfehlern
|
||||||
|
wird keine unvollständige Ausgabe veröffentlicht.
|
||||||
|
|||||||
57
src/lib/image-policy.ts
Normal file
57
src/lib/image-policy.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
export type ImagePolicy = "placeholder" | "remove" | "keep";
|
||||||
|
export type DocumentImageReport = {
|
||||||
|
image_policy: ImagePolicy;
|
||||||
|
images_replaced: number;
|
||||||
|
images_removed: number;
|
||||||
|
media_parts_removed: number;
|
||||||
|
warnings: string[];
|
||||||
|
};
|
||||||
|
export const DEFAULT_IMAGE_POLICY: ImagePolicy = "placeholder";
|
||||||
|
export const IMAGE_POLICY_LABELS: Record<ImagePolicy, string> = {
|
||||||
|
placeholder: "Datenschutz-Platzhalter (Standard)",
|
||||||
|
remove: "Bilder vollständig entfernen",
|
||||||
|
keep: "Bilder behalten — Datenschutzrisiko",
|
||||||
|
};
|
||||||
|
export const KEEP_IMAGE_WARNING = "Achtung: Bilder können sensible Informationen enthalten. Sie werden unverändert übernommen und nicht auf personenbezogene Daten geprüft.";
|
||||||
|
|
||||||
|
export function checkedImagePolicy(policy: string): ImagePolicy {
|
||||||
|
if (policy !== "placeholder" && policy !== "remove" && policy !== "keep") {
|
||||||
|
throw new Error("Ungültige Bildbehandlung.");
|
||||||
|
}
|
||||||
|
return policy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sameImagePolicyCoverage(previous: { imagePolicy?: ImagePolicy } | undefined, policy: ImagePolicy): boolean {
|
||||||
|
return previous?.imagePolicy === policy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkedImageReport(value: unknown, policy: ImagePolicy): DocumentImageReport {
|
||||||
|
const report = value as Partial<DocumentImageReport> | null;
|
||||||
|
if (!report || report.image_policy !== policy) {
|
||||||
|
throw new Error("Die Velum-API bestätigt die gewählte Bildbehandlung nicht. Bitte das Backend aktualisieren.");
|
||||||
|
}
|
||||||
|
for (const count of [report.images_replaced, report.images_removed, report.media_parts_removed]) {
|
||||||
|
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
|
||||||
|
throw new Error("Die Velum-API liefert keine gültigen Bildzähler.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Array.isArray(report.warnings) || report.warnings.some((warning) => typeof warning !== "string")) {
|
||||||
|
throw new Error("Die Velum-API liefert keine gültigen Bildwarnungen.");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
image_policy: policy,
|
||||||
|
images_replaced: report.images_replaced!, images_removed: report.images_removed!,
|
||||||
|
media_parts_removed: report.media_parts_removed!,
|
||||||
|
warnings: policy === "keep" && !report.warnings.includes(KEEP_IMAGE_WARNING) ? [KEEP_IMAGE_WARNING, ...report.warnings] : [...report.warnings],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeImages(files: readonly { imageReport?: DocumentImageReport }[]): {
|
||||||
|
replaced: number; removed: number; warnings: string[];
|
||||||
|
} {
|
||||||
|
return {
|
||||||
|
replaced: files.reduce((total, file) => total + (file.imageReport?.images_replaced ?? 0), 0),
|
||||||
|
removed: files.reduce((total, file) => total + (file.imageReport?.images_removed ?? 0), 0),
|
||||||
|
warnings: [...new Set(files.flatMap((file) => file.imageReport?.warnings ?? []))],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
|
import { fileTextParts } from "./project-text-stream";
|
||||||
|
import type { TextAnalysisPart } from "./project-text-stream";
|
||||||
import type {
|
import type {
|
||||||
EntityType,
|
EntityType,
|
||||||
PlaceholderMapping,
|
PlaceholderMapping,
|
||||||
PseudonymizeResponse,
|
PseudonymizeResponse,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import { makeTextBatches, spansBySegment } from "./project-review";
|
import { makeTextBatches, MAX_BATCH_CODEPOINTS, spansBySegment } from "./project-review";
|
||||||
import type { TextBatch } from "./project-review";
|
import type { TextBatch } from "./project-review";
|
||||||
|
|
||||||
type Analyze = (
|
type Analyze = (
|
||||||
@@ -31,7 +33,9 @@ export async function analyzeProjectBatch(
|
|||||||
return { mapping: result.mapping, results: [{ batch, result }] };
|
return { mapping: result.mapping, results: [{ batch, result }] };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
if (!/request failed: 5\d\d\b/i.test(message)) throw error;
|
if (!/request failed: (?:413|5\d\d)\b/i.test(message)) {
|
||||||
|
throw new Error(`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`, { cause: error });
|
||||||
|
}
|
||||||
if (batch.segments.length < 2) {
|
if (batch.segments.length < 2) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
|
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
|
||||||
@@ -83,11 +87,11 @@ export const TEXT_CORE_LENGTH = 10_000;
|
|||||||
const TEXT_CONTEXT_OVERLAP = 384;
|
const TEXT_CONTEXT_OVERLAP = 384;
|
||||||
|
|
||||||
/** Split only at whitespace, retaining context on both sides of every boundary. */
|
/** Split only at whitespace, retaining context on both sides of every boundary. */
|
||||||
export function splitTextForAnalysis(
|
function* iterateTextForAnalysis(
|
||||||
text: string,
|
text: string,
|
||||||
coreLength = TEXT_CORE_LENGTH,
|
coreLength = TEXT_CORE_LENGTH,
|
||||||
overlap = TEXT_CONTEXT_OVERLAP,
|
overlap = TEXT_CONTEXT_OVERLAP,
|
||||||
): Array<{
|
): Generator<{
|
||||||
text: string;
|
text: string;
|
||||||
scanStart: number;
|
scanStart: number;
|
||||||
coreStart: number;
|
coreStart: number;
|
||||||
@@ -95,7 +99,6 @@ export function splitTextForAnalysis(
|
|||||||
}> {
|
}> {
|
||||||
if (coreLength < 2 || overlap < 0)
|
if (coreLength < 2 || overlap < 0)
|
||||||
throw new Error("Ungültige Abschnittsgröße.");
|
throw new Error("Ungültige Abschnittsgröße.");
|
||||||
const parts = [];
|
|
||||||
let coreStart = 0;
|
let coreStart = 0;
|
||||||
while (coreStart < text.length) {
|
while (coreStart < text.length) {
|
||||||
let coreEnd = Math.min(text.length, coreStart + coreLength);
|
let coreEnd = Math.min(text.length, coreStart + coreLength);
|
||||||
@@ -123,15 +126,18 @@ export function splitTextForAnalysis(
|
|||||||
if (scanStart > 0 && /[\uDC00-\uDFFF]/u.test(text[scanStart])) scanStart--;
|
if (scanStart > 0 && /[\uDC00-\uDFFF]/u.test(text[scanStart])) scanStart--;
|
||||||
if (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
|
if (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
|
||||||
scanEnd++;
|
scanEnd++;
|
||||||
parts.push({
|
yield {
|
||||||
text: text.slice(scanStart, scanEnd),
|
text: text.slice(scanStart, scanEnd),
|
||||||
scanStart,
|
scanStart,
|
||||||
coreStart,
|
coreStart,
|
||||||
coreEnd,
|
coreEnd,
|
||||||
});
|
};
|
||||||
coreStart = coreEnd;
|
coreStart = coreEnd;
|
||||||
}
|
}
|
||||||
return parts;
|
}
|
||||||
|
|
||||||
|
export function splitTextForAnalysis(text: string, coreLength = TEXT_CORE_LENGTH, overlap = TEXT_CONTEXT_OVERLAP) {
|
||||||
|
return [...iterateTextForAnalysis(text, coreLength, overlap)];
|
||||||
}
|
}
|
||||||
|
|
||||||
function utf16Positions(text: string): number[] {
|
function utf16Positions(text: string): number[] {
|
||||||
@@ -144,9 +150,9 @@ function utf16Positions(text: string): number[] {
|
|||||||
return positions;
|
return positions;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reconcileSpans(spans: TextSpan[], file: string): TextSpan[] {
|
function reconcileSpans<T extends TextSpan>(spans: T[], file: string): T[] {
|
||||||
const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
||||||
const result: TextSpan[] = [];
|
const result: T[] = [];
|
||||||
for (const span of sorted) {
|
for (const span of sorted) {
|
||||||
const last = result.at(-1);
|
const last = result.at(-1);
|
||||||
if (!last || span.start >= last.end) {
|
if (!last || span.start >= last.end) {
|
||||||
@@ -173,34 +179,39 @@ export async function analyzeProjectTexts(
|
|||||||
mapping: PlaceholderMapping;
|
mapping: PlaceholderMapping;
|
||||||
spansByFile: Map<string, TextSpan[]>;
|
spansByFile: Map<string, TextSpan[]>;
|
||||||
}> {
|
}> {
|
||||||
const chunks: TextChunk[] = [];
|
|
||||||
const spansByFile = new Map(files.map(({ key }) => [key, [] as TextSpan[]]));
|
const spansByFile = new Map(files.map(({ key }) => [key, [] as TextSpan[]]));
|
||||||
for (const file of files) {
|
// Only the current request and its offset metadata stay alive. Do not build
|
||||||
let parts: ReturnType<typeof splitTextForAnalysis>;
|
// arrays of every chunk and every concatenated request for a large file.
|
||||||
try {
|
function* batches(): Generator<{ batch: TextBatch; byKey: Map<string, TextChunk> }> {
|
||||||
parts = splitTextForAnalysis(file.text);
|
let chunks: TextChunk[] = [];
|
||||||
} catch (error) {
|
let length = 0;
|
||||||
throw new Error(`${file.key}: ${(error as Error).message}`, {
|
for (const file of files) {
|
||||||
cause: error,
|
let total = 0;
|
||||||
});
|
try {
|
||||||
}
|
for (const part of iterateTextForAnalysis(file.text)) if (part.coreEnd > part.coreStart) total++;
|
||||||
for (const [index, part] of parts.entries()) {
|
let index = 0;
|
||||||
chunks.push({
|
for (const part of iterateTextForAnalysis(file.text)) {
|
||||||
...part,
|
if (chunks.length && length + 4 + part.text.length > MAX_BATCH_CODEPOINTS) {
|
||||||
key: String(chunks.length),
|
yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||||
file: file.key,
|
chunks = [];
|
||||||
index,
|
length = 0;
|
||||||
total: parts.length,
|
}
|
||||||
});
|
length += (chunks.length ? 4 : 0) + part.text.length;
|
||||||
|
chunks.push({ ...part, key: String(chunks.length), file: file.key, index: index++, total });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if (chunks.length) yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||||
}
|
}
|
||||||
const byKey = new Map(chunks.map((chunk) => [chunk.key, chunk]));
|
let total = 0;
|
||||||
const batches = makeTextBatches(
|
for (const entry of batches()) if (entry.batch.segments.length) total++;
|
||||||
chunks.map(({ key, text }) => ({ key, text })),
|
|
||||||
);
|
|
||||||
let current = mapping;
|
let current = mapping;
|
||||||
for (const [index, batch] of batches.entries()) {
|
let hitCount = 0;
|
||||||
onProgress(index + 1, batches.length);
|
let index = 0;
|
||||||
|
for (const { batch, byKey } of batches()) {
|
||||||
|
onProgress(++index, total);
|
||||||
const analyzed = await analyzeProjectBatch(
|
const analyzed = await analyzeProjectBatch(
|
||||||
batch,
|
batch,
|
||||||
current,
|
current,
|
||||||
@@ -237,6 +248,7 @@ export async function analyzeProjectTexts(
|
|||||||
const end = chunk.scanStart + positions[span.end];
|
const end = chunk.scanStart + positions[span.end];
|
||||||
if (start >= chunk.coreStart && start < chunk.coreEnd) {
|
if (start >= chunk.coreStart && start < chunk.coreEnd) {
|
||||||
spansByFile.get(chunk.file)!.push({ ...span, start, end });
|
spansByFile.get(chunk.file)!.push({ ...span, start, end });
|
||||||
|
if (++hitCount > 50_000) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -246,3 +258,62 @@ export async function analyzeProjectTexts(
|
|||||||
spansByFile.set(file, reconcileSpans(spans, file));
|
spansByFile.set(file, reconcileSpans(spans, file));
|
||||||
return { mapping: current, spansByFile };
|
return { mapping: current, spansByFile };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type StreamTextSpan = TextSpan & { context: string };
|
||||||
|
|
||||||
|
/** Analyze complete-line parts lazily, sharing small requests across file boundaries. */
|
||||||
|
export async function analyzeProjectTextFiles(
|
||||||
|
files: Array<{ key: string; path: string }>, mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[], forceMasks: Record<string, string[]>, analyze: Analyze,
|
||||||
|
onProgress: (file: string, batch: number) => void,
|
||||||
|
): Promise<{ mapping: PlaceholderMapping; spansByFile: Map<string, StreamTextSpan[]> }> {
|
||||||
|
const spansByFile = new Map(files.map((file) => [file.key, [] as StreamTextSpan[]]));
|
||||||
|
type Part = TextAnalysisPart & { key: string; file: string };
|
||||||
|
let parts: Part[] = [];
|
||||||
|
let size = 0;
|
||||||
|
let current = mapping;
|
||||||
|
let batchIndex = 0;
|
||||||
|
let hits = 0;
|
||||||
|
const flush = async () => {
|
||||||
|
if (!parts.length) return;
|
||||||
|
const batch = makeTextBatches(parts)[0];
|
||||||
|
const byKey = new Map(parts.map((part) => [part.key, part]));
|
||||||
|
onProgress(parts[0].file, ++batchIndex);
|
||||||
|
const analyzed = await analyzeProjectBatch(batch, current, entityTypes, forceMasks, analyze,
|
||||||
|
"Textdateien analysieren", (key) => byKey.get(key)?.file ?? key);
|
||||||
|
current = analyzed.mapping;
|
||||||
|
for (const { batch: subBatch, result } of analyzed.results) {
|
||||||
|
for (const [key, spans] of spansBySegment(subBatch, result.spans)) {
|
||||||
|
const part = byKey.get(key)!;
|
||||||
|
const positions = utf16Positions(part.text);
|
||||||
|
for (const span of spans) {
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0
|
||||||
|
|| span.start >= span.end || span.end >= positions.length) throw new Error(`Ungültige Trefferposition der Velum-API: ${part.file}`);
|
||||||
|
const start = part.scanStart + positions[span.start];
|
||||||
|
const end = part.scanStart + positions[span.end];
|
||||||
|
if (start < part.coreStart || start >= part.coreEnd) continue;
|
||||||
|
// Copy the short snippet, allowing the request's source string to be freed.
|
||||||
|
const context = Buffer.from(part.text.slice(Math.max(0, positions[span.start] - 70), positions[span.end] + 70), "utf8").toString("utf8");
|
||||||
|
spansByFile.get(part.file)!.push({ ...span, start, end, context });
|
||||||
|
if (++hits > 50_000) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parts = [];
|
||||||
|
size = 0;
|
||||||
|
};
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
for await (const part of fileTextParts(file.path)) {
|
||||||
|
if (parts.length && size + 4 + part.text.length > MAX_BATCH_CODEPOINTS) await flush();
|
||||||
|
size += (parts.length ? 4 : 0) + part.text.length;
|
||||||
|
parts.push({ ...part, file: file.key, key: String(parts.length) });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await flush();
|
||||||
|
for (const [file, spans] of spansByFile) spansByFile.set(file, reconcileSpans(spans, file));
|
||||||
|
return { mapping: current, spansByFile };
|
||||||
|
}
|
||||||
|
|||||||
38
src/lib/project-capabilities.ts
Normal file
38
src/lib/project-capabilities.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
/** Requirements follow the files that will actually use the API. */
|
||||||
|
export function requiredProjectCapabilities(documents: boolean): string[] {
|
||||||
|
return ["request_force_masks", ...(documents ? [
|
||||||
|
"document_hit_review", "document_review_mapping", "document_restoration",
|
||||||
|
"comment_author_review", "revision_author_review", "document_image_policy",
|
||||||
|
] : [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkProjectCapabilities(
|
||||||
|
url: string, documents: boolean,
|
||||||
|
fetcher: (url: string, init: RequestInit) => Promise<Response>,
|
||||||
|
): Promise<void> {
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetcher(url, { signal: AbortSignal.timeout(15_000) });
|
||||||
|
} catch (error) {
|
||||||
|
const timeout = error instanceof Error && /timeout|abort/i.test(error.name);
|
||||||
|
throw new Error(`Velum: ${timeout ? "Zeitlimit bei der Prüfung der Projektfähigkeiten" : "Projekt-API nicht erreichbar"}: ${url}.`, { cause: error });
|
||||||
|
}
|
||||||
|
if (response.status === 404 || response.status === 405) {
|
||||||
|
throw new Error(`Velum: Projekt-API-Endpunkt fehlt (HTTP ${response.status}): ${url}. Backend aktualisieren oder Basis-URL prüfen.`);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Velum: Projektfähigkeiten nicht abrufbar (HTTP ${response.status}): ${url}. Anmeldung, Proxy und Backend prüfen.`);
|
||||||
|
}
|
||||||
|
if (!(response.headers.get("content-type") ?? "").includes("application/json")) {
|
||||||
|
throw new Error(`Velum: Keine JSON-Antwort für ${url}. Anmeldung oder API-Weiterleitung prüfen.`);
|
||||||
|
}
|
||||||
|
const capabilities: unknown = await response.json();
|
||||||
|
if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
|
||||||
|
throw new Error(`Velum: Ungültige Projektfähigkeiten von ${url}.`);
|
||||||
|
}
|
||||||
|
const missing = requiredProjectCapabilities(documents)
|
||||||
|
.filter((key) => (capabilities as Record<string, unknown>)[key] !== true);
|
||||||
|
if (missing.length) {
|
||||||
|
throw new Error(`Velum: Backend unterstützt die ausgewählten ${documents ? "Office-/PDF-Dateien" : "Textdateien"} noch nicht vollständig. Fehlende API-Fähigkeiten: ${missing.join(", ")}. API: ${url}. Backend aktualisieren.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
157
src/lib/project-text-stream.ts
Normal file
157
src/lib/project-text-stream.ts
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
import { createReadStream, promises as fs } from "node:fs";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
export const TEXT_CORE_LENGTH = 10_000;
|
||||||
|
export const MAX_TEXT_LINE_LENGTH = 20_000;
|
||||||
|
const OVERLAP = 384;
|
||||||
|
|
||||||
|
export async function hashProjectFile(path: string): Promise<string> {
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
for await (const data of createReadStream(path)) hash.update(data);
|
||||||
|
return hash.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preserve BOM, CRLF and Unicode; incomplete UTF-8 sequences carry into the next read. */
|
||||||
|
export async function* decodedText(path: string, hash?: ReturnType<typeof createHash>, highWaterMark = 64 * 1024): AsyncGenerator<string> {
|
||||||
|
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||||
|
for await (const data of createReadStream(path, { highWaterMark })) {
|
||||||
|
const buffer = data as Buffer;
|
||||||
|
hash?.update(buffer);
|
||||||
|
if (buffer.includes(0)) throw new Error("Binärdatei");
|
||||||
|
let text: string;
|
||||||
|
try { text = decoder.decode(buffer, { stream: true }); }
|
||||||
|
catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||||
|
if (text) yield text;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const tail = decoder.decode();
|
||||||
|
if (tail) yield tail;
|
||||||
|
} catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function inspectTextFile(path: string): Promise<string> {
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
for await (const text of decodedText(path, hash)) { if (!text.length) continue; }
|
||||||
|
return hash.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Yield complete lines, retaining their exact delimiters and the final unterminated line. */
|
||||||
|
export async function* textLines(chunks: AsyncIterable<string>, maxLineLength = MAX_TEXT_LINE_LENGTH): AsyncGenerator<string> {
|
||||||
|
let pending = "";
|
||||||
|
let line = 1;
|
||||||
|
const check = (value: string) => {
|
||||||
|
if (value.length > maxLineLength) throw new Error(`Zeile ${line} ist länger als ${maxLineLength} Zeichen. Bitte diese Zeile an Wortgrenzen aufteilen; Velum zerschneidet keine Wörter.`);
|
||||||
|
};
|
||||||
|
for await (const chunk of chunks) {
|
||||||
|
pending += chunk;
|
||||||
|
let start = 0;
|
||||||
|
const endings = /\r\n|\r|\n/g;
|
||||||
|
for (let match = endings.exec(pending); match; match = endings.exec(pending)) {
|
||||||
|
if (match[0] === "\r" && match.index === pending.length - 1) break;
|
||||||
|
const end = match.index + match[0].length;
|
||||||
|
const value = pending.slice(start, end);
|
||||||
|
check(value);
|
||||||
|
yield value;
|
||||||
|
line++;
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
pending = pending.slice(start);
|
||||||
|
check(pending);
|
||||||
|
}
|
||||||
|
if (pending) { check(pending); yield pending; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function* lineCores(path: string): AsyncGenerator<string> {
|
||||||
|
let core = "";
|
||||||
|
for await (const line of textLines(decodedText(path))) {
|
||||||
|
if (core && core.length + line.length > TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||||
|
core += line;
|
||||||
|
if (core.length >= TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||||
|
}
|
||||||
|
if (core) yield core;
|
||||||
|
}
|
||||||
|
|
||||||
|
function leftContext(text: string): string {
|
||||||
|
if (text.length <= OVERLAP) return text;
|
||||||
|
// Start at a complete token; the core itself always contains complete lines.
|
||||||
|
const tail = text.slice(-OVERLAP);
|
||||||
|
const boundary = tail.search(/\s/u);
|
||||||
|
return boundary < 0 ? "" : tail.slice(boundary + 1);
|
||||||
|
}
|
||||||
|
function rightContext(text: string): string {
|
||||||
|
if (text.length <= OVERLAP) return text;
|
||||||
|
const head = text.slice(0, OVERLAP);
|
||||||
|
for (let i = head.length - 1; i >= 0; i--) if (/\s/u.test(head[i])) return head.slice(0, i + 1);
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TextAnalysisPart = { text: string; scanStart: number; coreStart: number; coreEnd: number };
|
||||||
|
|
||||||
|
/** One previous, current and next core at most; no array of the entire source. */
|
||||||
|
export async function* fileTextParts(path: string): AsyncGenerator<TextAnalysisPart> {
|
||||||
|
const cores = lineCores(path)[Symbol.asyncIterator]();
|
||||||
|
let current = await cores.next();
|
||||||
|
let previous = "";
|
||||||
|
let offset = 0;
|
||||||
|
try {
|
||||||
|
while (!current.done) {
|
||||||
|
const next = await cores.next();
|
||||||
|
const left = leftContext(previous);
|
||||||
|
const right = rightContext(next.done ? "" : next.value);
|
||||||
|
yield { text: left + current.value + right, scanStart: offset - left.length,
|
||||||
|
coreStart: offset, coreEnd: offset + current.value.length };
|
||||||
|
offset += current.value.length;
|
||||||
|
previous = current.value;
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
} finally { await cores.return?.(undefined); }
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplacementSpan = { start: number; end: number; placeholder: string; id: string };
|
||||||
|
|
||||||
|
/** Reassemble the original stream, substituting only approved original-coordinate spans. */
|
||||||
|
export async function writeReplacedTextFile(
|
||||||
|
source: string, target: string, spans: ReplacementSpan[], accepted: Set<string>, expectedHash: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const selected = spans.filter((span) => accepted.has(span.id)).sort((a, b) => a.start - b.start);
|
||||||
|
for (let index = 0; index < selected.length; index++) {
|
||||||
|
const span = selected[index];
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.start >= span.end
|
||||||
|
|| (index && span.start < selected[index - 1].end)) throw new Error("Ungültige oder überlappende Trefferposition.");
|
||||||
|
}
|
||||||
|
const inputHash = createHash("sha256");
|
||||||
|
const outputHash = createHash("sha256");
|
||||||
|
const output = await fs.open(target, "wx", 0o600);
|
||||||
|
const write = async (text: string) => {
|
||||||
|
const bytes = Buffer.from(text, "utf8");
|
||||||
|
outputHash.update(bytes);
|
||||||
|
await output.writeFile(bytes);
|
||||||
|
};
|
||||||
|
let offset = 0;
|
||||||
|
let pending = "";
|
||||||
|
let index = 0;
|
||||||
|
let complete = false;
|
||||||
|
try {
|
||||||
|
for await (const chunk of decodedText(source, inputHash)) {
|
||||||
|
pending += chunk;
|
||||||
|
let consumed = 0;
|
||||||
|
while (index < selected.length && selected[index].end <= offset + pending.length) {
|
||||||
|
const span = selected[index++];
|
||||||
|
await write(pending.slice(consumed, span.start - offset));
|
||||||
|
await write(span.placeholder);
|
||||||
|
consumed = span.end - offset;
|
||||||
|
}
|
||||||
|
const flush = index < selected.length ? Math.min(pending.length, selected[index].start - offset) : pending.length;
|
||||||
|
await write(pending.slice(consumed, flush));
|
||||||
|
pending = pending.slice(flush);
|
||||||
|
offset += flush;
|
||||||
|
}
|
||||||
|
if (index !== selected.length || pending) throw new Error("Trefferposition liegt außerhalb der Quelldatei.");
|
||||||
|
if (inputHash.digest("hex") !== expectedHash) throw new Error("Datei wurde seit der Vorschau geändert.");
|
||||||
|
complete = true;
|
||||||
|
return outputHash.digest("hex");
|
||||||
|
} finally {
|
||||||
|
await output.close();
|
||||||
|
if (!complete) await fs.rm(target, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
|
import { hashProjectFile, inspectTextFile } from "./project-text-stream";
|
||||||
import { createHash, randomUUID } from "node:crypto";
|
import { createHash, randomUUID } from "node:crypto";
|
||||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||||
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||||
import { environment } from "@raycast/api";
|
import { environment } from "@raycast/api";
|
||||||
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||||
import { whitelistKey } from "./project-whitelist";
|
import { whitelistKey } from "./project-whitelist";
|
||||||
|
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
||||||
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||||
import { restoreOriginalCase } from "./restore-case";
|
import { restoreOriginalCase } from "./restore-case";
|
||||||
import { mappingForRestoration } from "./mapping-groups";
|
import { mappingForRestoration } from "./mapping-groups";
|
||||||
@@ -14,7 +16,7 @@ export type { ProjectWhitelistEntry } from "./project-whitelist";
|
|||||||
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
|
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 ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
||||||
export type SkippedProjectFile = { path: string; reason: string };
|
export type SkippedProjectFile = { path: string; reason: string };
|
||||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] };
|
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport };
|
||||||
export type ProjectRun = {
|
export type ProjectRun = {
|
||||||
version: 2;
|
version: 2;
|
||||||
origin?: "direct" | "imported";
|
origin?: "direct" | "imported";
|
||||||
@@ -25,6 +27,8 @@ export type ProjectRun = {
|
|||||||
mapping: PlaceholderMapping;
|
mapping: PlaceholderMapping;
|
||||||
/** Categories actually used to analyze the files in this snapshot. */
|
/** Categories actually used to analyze the files in this snapshot. */
|
||||||
entityTypes?: EntityType[];
|
entityTypes?: EntityType[];
|
||||||
|
/** Explicit image handling applied to documents in this snapshot. Unknown means reprocess. */
|
||||||
|
imagePolicy?: ImagePolicy;
|
||||||
/** Hash of each live project file and its immutable output in this run. */
|
/** Hash of each live project file and its immutable output in this run. */
|
||||||
sourceState?: Record<string, { hash: string; output: string }>;
|
sourceState?: Record<string, { hash: string; output: string }>;
|
||||||
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
||||||
@@ -231,7 +235,7 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
export async function scanProjectFiles(root: string, maxSize?: number,
|
||||||
validateText = true): Promise<{
|
validateText = true): Promise<{
|
||||||
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||||
}> {
|
}> {
|
||||||
@@ -258,15 +262,16 @@ export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const stat = await fs.stat(path);
|
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";
|
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||||
|
const limit = maxSize ?? (kind === "document" ? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
|
||||||
|
if (stat.size > limit) { skip(relPath, `Datei zu groß (Grenze: ${limit / 1024 / 1024} MiB)`); continue; }
|
||||||
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
||||||
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (kind === "text" && validateText) {
|
if (kind === "text" && validateText) {
|
||||||
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
||||||
try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); }
|
try { await inspectTextFile(path); }
|
||||||
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
||||||
}
|
}
|
||||||
files.push({ relPath, absPath: path, kind, size: stat.size });
|
files.push({ relPath, absPath: path, kind, size: stat.size });
|
||||||
@@ -589,8 +594,7 @@ export async function listRuns(projectPath: string, support = environment.suppor
|
|||||||
/** An unchanged output from an in-place run can be carried into the next snapshot. */
|
/** 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> {
|
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const previous = await fs.readFile(resolveWithin(join(directory, "files"), relPath));
|
return await hashProjectFile(resolveWithin(join(directory, "files"), relPath)) === currentHash;
|
||||||
return digest(previous) === currentHash;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||||
throw error;
|
throw error;
|
||||||
@@ -728,7 +732,7 @@ export async function replaceProjectFilesInPlace(projectPath: string, runDirecto
|
|||||||
try {
|
try {
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const source = resolveWithin(root, file.source);
|
const source = resolveWithin(root, file.source);
|
||||||
if (expectedHashes && digest(await fs.readFile(source)) !== expectedHashes.get(file.source)) {
|
if (expectedHashes && await hashProjectFile(source) !== expectedHashes.get(file.source)) {
|
||||||
throw new Error(`Projektdatei wurde vor dem Ersetzen erneut geändert: ${file.source}`);
|
throw new Error(`Projektdatei wurde vor dem Ersetzen erneut geändert: ${file.source}`);
|
||||||
}
|
}
|
||||||
await fs.unlink(source);
|
await fs.unlink(source);
|
||||||
|
|||||||
@@ -17,7 +17,11 @@ import {
|
|||||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds, spansBySegment,
|
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds, spansBySegment,
|
||||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||||
} from "./lib/project-review";
|
} from "./lib/project-review";
|
||||||
import { analyzeProjectBatch, analyzeProjectTexts } from "./lib/project-analysis";
|
import { analyzeProjectBatch, analyzeProjectTextFiles } from "./lib/project-analysis";
|
||||||
|
import { hashProjectFile, inspectTextFile, writeReplacedTextFile } from "./lib/project-text-stream";
|
||||||
|
|
||||||
|
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "./lib/image-policy";
|
||||||
|
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||||
|
|
||||||
const run = promisify(execFile);
|
const run = promisify(execFile);
|
||||||
const MAX_REVIEW_HITS = 50000;
|
const MAX_REVIEW_HITS = 50000;
|
||||||
@@ -28,10 +32,10 @@ type Hit = {
|
|||||||
};
|
};
|
||||||
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping };
|
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping };
|
||||||
type PathDraft = { key: string; value: string; hits: Hit[] };
|
type PathDraft = { key: string; value: string; hits: Hit[] };
|
||||||
type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string }>;
|
type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport }>;
|
||||||
paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||||
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean };
|
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
|
||||||
|
|
||||||
const typeLabels: Record<string, string> = {
|
const typeLabels: Record<string, string> = {
|
||||||
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
||||||
@@ -63,26 +67,12 @@ async function finderFolder(): Promise<string | undefined> {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function textFromBytes(data: Buffer): string {
|
|
||||||
return new TextDecoder("utf-8", { fatal: true }).decode(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isUnreadableDocument(error: unknown): boolean {
|
function isUnreadableDocument(error: unknown): boolean {
|
||||||
const message = error instanceof Error ? error.message : "";
|
const message = error instanceof Error ? error.message : "";
|
||||||
return /request failed: 422\b/i.test(message)
|
return /request failed: 422\b/i.test(message)
|
||||||
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
|
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
function contentHits(file: ProjectFile, spans: Array<{
|
|
||||||
start: number; end: number; type: string; score: number; placeholder: string; original: string;
|
|
||||||
}>, text: string): Hit[] {
|
|
||||||
return spans.map((span, index) => ({
|
|
||||||
...span, id: `${file.relPath}:content:${index}`, file: file.relPath,
|
|
||||||
source: file.relPath, kind: "content" as const,
|
|
||||||
context: text.slice(Math.max(0, span.start - 70), Math.min(text.length, span.end + 70)),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||||
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||||
file: file.relPath, kind: "content" as const }));
|
file: file.relPath, kind: "content" as const }));
|
||||||
@@ -104,8 +94,8 @@ function pathSegments(files: ProjectFile[]): PathDraft[] {
|
|||||||
|
|
||||||
async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||||
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||||
onProgress: (message: string) => void): Promise<Preview> {
|
onProgress: (message: string) => void, imagePolicy: ImagePolicy): Promise<Preview> {
|
||||||
await requireProjectCapabilities();
|
await requireProjectCapabilities(files.some((file) => file.kind === "document"));
|
||||||
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||||
const latestEntry = (await listRuns(root))[0];
|
const latestEntry = (await listRuns(root))[0];
|
||||||
const latest = latestEntry?.run;
|
const latest = latestEntry?.run;
|
||||||
@@ -118,41 +108,57 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
|||||||
const retained: Preview["retained"] = [];
|
const retained: Preview["retained"] = [];
|
||||||
const draftsByPath = new Map<string, Draft>();
|
const draftsByPath = new Map<string, Draft>();
|
||||||
const hits: Hit[] = [];
|
const hits: Hit[] = [];
|
||||||
const texts = new Map<string, string>();
|
|
||||||
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
||||||
const previousDirectory = latestEntry?.directory;
|
const previousDirectory = latestEntry?.directory;
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const data = await fs.readFile(file.absPath);
|
onProgress(`Datei prüfen: ${file.relPath}`);
|
||||||
const hash = digest(data);
|
let hash: string;
|
||||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && latest && previousDirectory
|
try { hash = file.kind === "text" ? await inspectTextFile(file.absPath) : await hashProjectFile(file.absPath); }
|
||||||
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
catch (error) {
|
||||||
if (previousOutput && previousDirectory) {
|
const reason = (error as Error).message;
|
||||||
retained.push({ file, hash, output: previousOutput, directory: previousDirectory });
|
if (!/^(Binärdatei|Keine gültige UTF-8-Textdatei)$/.test(reason)) throw error;
|
||||||
|
skipped.push({ path: file.relPath, reason });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let decoded: string | undefined;
|
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
|
||||||
if (file.kind === "text") {
|
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
|
||||||
if (data.includes(0)) { skipped.push({ path: file.relPath, reason: "Binärdatei" }); continue; }
|
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
||||||
try { decoded = textFromBytes(data); }
|
if (previousOutput && previousDirectory) {
|
||||||
catch { skipped.push({ path: file.relPath, reason: "Keine gültige UTF-8-Textdatei" }); continue; }
|
retained.push({ file, hash, output: previousOutput, directory: previousDirectory,
|
||||||
|
imageReport: latest?.files.find((saved) => saved.output === previousOutput)?.imageReport });
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
const draft: Draft = { file, hash, hits: [] };
|
const draft: Draft = { file, hash, hits: [] };
|
||||||
drafts.push(draft);
|
drafts.push(draft);
|
||||||
draftsByPath.set(file.relPath, draft);
|
draftsByPath.set(file.relPath, draft);
|
||||||
if (decoded !== undefined) texts.set(file.relPath, decoded);
|
|
||||||
}
|
}
|
||||||
const addHits = (draft: Draft, found: Hit[]) => {
|
const addHits = (draft: Draft, found: Hit[]) => {
|
||||||
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||||
hits.push(...draft.hits);
|
hits.push(...draft.hits);
|
||||||
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||||
};
|
};
|
||||||
const analyzedTexts = await analyzeProjectTexts([...texts].map(([key, text]) => ({ key, text })),
|
const textDrafts = drafts.filter((draft) => draft.file.kind === "text");
|
||||||
mapping, entityTypes, masks, pseudonymize,
|
const analyzeText: typeof pseudonymize = async (text, current, types, rules) => {
|
||||||
(index, total) => onProgress(`Textdateien analysieren: Paket ${index}/${total}`));
|
try {
|
||||||
|
return await pseudonymize(text, current, types, rules, AbortSignal.timeout(60_000));
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && /timeout|abort/i.test(error.name)) {
|
||||||
|
throw new Error("Velum: Analyse-Zeitlimit nach 60 Sekunden erreicht. Backend-Auslastung und Proxy-Zeitlimit prüfen.", { cause: error });
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const analyzedTexts = await analyzeProjectTextFiles(textDrafts.map((draft) => ({
|
||||||
|
key: draft.file.relPath, path: draft.file.absPath,
|
||||||
|
})), mapping, entityTypes, masks, analyzeText,
|
||||||
|
(file, index) => onProgress(`Textdateien analysieren: ${file} · Paket ${index}`));
|
||||||
mapping = analyzedTexts.mapping;
|
mapping = analyzedTexts.mapping;
|
||||||
for (const [path, spans] of analyzedTexts.spansByFile) {
|
for (const draft of textDrafts) {
|
||||||
const draft = draftsByPath.get(path)!;
|
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde während der Analyse geändert: ${draft.file.relPath}`);
|
||||||
addHits(draft, contentHits(draft.file, spans, texts.get(path)!));
|
addHits(draft, (analyzedTexts.spansByFile.get(draft.file.relPath) ?? []).map((span, index) => ({
|
||||||
|
...span, id: `${draft.file.relPath}:content:${index}`, file: draft.file.relPath,
|
||||||
|
source: draft.file.relPath, kind: "content" as const,
|
||||||
|
})));
|
||||||
}
|
}
|
||||||
const documents = drafts.filter((draft) => draft.file.kind === "document");
|
const documents = drafts.filter((draft) => draft.file.kind === "document");
|
||||||
for (const [index, draft] of documents.entries()) {
|
for (const [index, draft] of documents.entries()) {
|
||||||
@@ -160,7 +166,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
|||||||
const data = await fs.readFile(draft.file.absPath);
|
const data = await fs.readFile(draft.file.absPath);
|
||||||
try {
|
try {
|
||||||
draft.analysisMapping = mapping;
|
draft.analysisMapping = mapping;
|
||||||
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes);
|
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes, undefined, imagePolicy);
|
||||||
mapping = result.mapping;
|
mapping = result.mapping;
|
||||||
addHits(draft, documentHits(draft.file, result.hits));
|
addHits(draft, documentHits(draft.file, result.hits));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -187,7 +193,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
|||||||
const byPath = new Map(paths.map((path) => [path.key, path]));
|
const byPath = new Map(paths.map((path) => [path.key, path]));
|
||||||
for (const [index, batch] of pathBatches.entries()) {
|
for (const [index, batch] of pathBatches.entries()) {
|
||||||
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
|
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
|
||||||
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, pseudonymize,
|
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, analyzeText,
|
||||||
"Dateinamen analysieren");
|
"Dateinamen analysieren");
|
||||||
mapping = analyzed.mapping;
|
mapping = analyzed.mapping;
|
||||||
for (const { batch: part, result } of analyzed.results) {
|
for (const { batch: part, result } of analyzed.results) {
|
||||||
@@ -206,7 +212,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { drafts, retained, paths, mapping, previousMapping,
|
return { drafts, retained, paths, mapping, previousMapping,
|
||||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace };
|
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
|
||||||
}
|
}
|
||||||
|
|
||||||
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||||
@@ -246,7 +252,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number;
|
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number;
|
||||||
replaced: number } | null>(null);
|
replaced: number; images: ReturnType<typeof summarizeImages> } | null>(null);
|
||||||
const accepted = useMemo(() => new Set(groups.filter((group) => selectedGroups.has(group.key))
|
const accepted = useMemo(() => new Set(groups.filter((group) => selectedGroups.has(group.key))
|
||||||
.flatMap((group) => group.hits.map((hit) => hit.id))), [groups, selectedGroups]);
|
.flatMap((group) => group.hits.map((hit) => hit.id))), [groups, selectedGroups]);
|
||||||
const selectedOccurrences = accepted.size;
|
const selectedOccurrences = accepted.size;
|
||||||
@@ -298,7 +304,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
}
|
}
|
||||||
if (!(await confirmAlert({
|
if (!(await confirmAlert({
|
||||||
title: inPlace ? "Geprüfte Auswahl anwenden und Originaldateien ersetzen?" : "Geprüfte Auswahl als Kopien erstellen?",
|
title: inPlace ? "Geprüfte Auswahl anwenden und Originaldateien ersetzen?" : "Geprüfte Auswahl als Kopien erstellen?",
|
||||||
message: `${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
|
message: `${props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING + " " : ""}${IMAGE_POLICY_LABELS[props.preview.imagePolicy]}. ${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
|
||||||
? "Die Originale und gegebenenfalls ihre Namen werden im Projektordner ersetzt und vorher außerhalb gesichert. PDF-Dateien werden als DOCX ausgegeben."
|
? "Die Originale und gegebenenfalls ihre Namen werden im Projektordner ersetzt und vorher außerhalb gesichert. PDF-Dateien werden als DOCX ausgegeben."
|
||||||
: "Die pseudonymisierten Kopien werden neben dem Projektordner gespeichert."}`,
|
: "Die pseudonymisierten Kopien werden neben dem Projektordner gespeichert."}`,
|
||||||
primaryAction: { title: inPlace ? "Originaldateien ersetzen" : "Kopien erstellen",
|
primaryAction: { title: inPlace ? "Originaldateien ersetzen" : "Kopien erstellen",
|
||||||
@@ -323,6 +329,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
run.mapping = mappingForSelection(props.preview.mapping, props.preview.previousMapping,
|
run.mapping = mappingForSelection(props.preview.mapping, props.preview.previousMapping,
|
||||||
acceptedHits, activeMerges);
|
acceptedHits, activeMerges);
|
||||||
run.entityTypes = [...props.preview.entityTypes];
|
run.entityTypes = [...props.preview.entityTypes];
|
||||||
|
run.imagePolicy = props.preview.imagePolicy;
|
||||||
run.sourceState = {};
|
run.sourceState = {};
|
||||||
run.commentAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
run.commentAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
||||||
run.reviewAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
run.reviewAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
||||||
@@ -331,8 +338,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
const usedPaths = new Set<string>();
|
const usedPaths = new Set<string>();
|
||||||
const replacements: RunFile[] = [];
|
const replacements: RunFile[] = [];
|
||||||
for (const retained of props.preview.retained) {
|
for (const retained of props.preview.retained) {
|
||||||
const data = await fs.readFile(retained.file.absPath);
|
if (await hashProjectFile(retained.file.absPath) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
|
||||||
if (digest(data) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
|
|
||||||
const relPath = retained.output;
|
const relPath = retained.output;
|
||||||
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||||
usedPaths.add(relPath);
|
usedPaths.add(relPath);
|
||||||
@@ -341,26 +347,27 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target,
|
await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target,
|
||||||
fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
||||||
await fs.chmod(target, 0o600);
|
await fs.chmod(target, 0o600);
|
||||||
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind };
|
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind, imageReport: retained.imageReport };
|
||||||
run.files.push(file);
|
run.files.push(file);
|
||||||
run.sourceState[inPlace ? relPath : file.source] = {
|
run.sourceState[inPlace ? relPath : file.source] = {
|
||||||
hash: inPlace ? digest(await fs.readFile(target)) : retained.hash, output: relPath,
|
hash: inPlace ? await hashProjectFile(target) : retained.hash, output: relPath,
|
||||||
};
|
};
|
||||||
// A prior copy-only run did not change the source files. Switching to in-place
|
// A prior copy-only run did not change the source files. Switching to in-place
|
||||||
// must install its reviewed outputs even when their names are unchanged.
|
// must install its reviewed outputs even when their names are unchanged.
|
||||||
if (file.source !== file.output || (inPlace && !props.preview.sourceInPlace)) replacements.push(file);
|
if (file.source !== file.output || (inPlace && !props.preview.sourceInPlace)) replacements.push(file);
|
||||||
}
|
}
|
||||||
for (const draft of props.preview.drafts) {
|
for (const draft of props.preview.drafts) {
|
||||||
const data = await fs.readFile(draft.file.absPath);
|
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
|
||||||
if (digest(data) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
|
|
||||||
const relPath = outputPath(draft.file.relPath, props.preview.paths, accepted,
|
const relPath = outputPath(draft.file.relPath, props.preview.paths, accepted,
|
||||||
draft.file.kind === "document", activeMerges);
|
draft.file.kind === "document", activeMerges);
|
||||||
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||||
usedPaths.add(relPath);
|
usedPaths.add(relPath);
|
||||||
const target = resolveWithin(join(directory, "files"), relPath);
|
const target = resolveWithin(join(directory, "files"), relPath);
|
||||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
let output: Buffer;
|
let outputHash: string;
|
||||||
|
let imageReport: DocumentImageReport | undefined;
|
||||||
if (draft.file.kind === "document") {
|
if (draft.file.kind === "document") {
|
||||||
|
const data = await fs.readFile(draft.file.absPath);
|
||||||
const idPrefix = `${draft.file.relPath}:document:`;
|
const idPrefix = `${draft.file.relPath}:document:`;
|
||||||
const reviewed = draft.hits.map((hit) => ({ ...hit, id: hit.id.slice(idPrefix.length) }));
|
const reviewed = draft.hits.map((hit) => ({ ...hit, id: hit.id.slice(idPrefix.length) }));
|
||||||
let docIds = draft.hits.filter((hit) => accepted.has(hit.id)).map((hit) => hit.id.slice(idPrefix.length));
|
let docIds = draft.hits.filter((hit) => accepted.has(hit.id)).map((hit) => hit.id.slice(idPrefix.length));
|
||||||
@@ -368,18 +375,18 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
masks, docIds, props.preview.entityTypes, draft.analysisMapping);
|
masks, docIds, props.preview.entityTypes, draft.analysisMapping, props.preview.imagePolicy);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!/\b409\b/.test((error as Error).message) || !/Treffer passen nicht mehr/.test((error as Error).message)) {
|
if (!/\b409\b/.test((error as Error).message) || !/Treffer passen nicht mehr/.test((error as Error).message)) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
const refreshed = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
const refreshed = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
masks, undefined, props.preview.entityTypes);
|
masks, undefined, props.preview.entityTypes, undefined, props.preview.imagePolicy);
|
||||||
const ids = reconcileDocumentHitIds(reviewed, docIds, refreshed.hits);
|
const ids = reconcileDocumentHitIds(reviewed, docIds, refreshed.hits);
|
||||||
if (!ids) throw new Error(`${draft.file.relPath}: Erkennungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
if (!ids) throw new Error(`${draft.file.relPath}: Erkennungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||||
docIds = ids;
|
docIds = ids;
|
||||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
masks, docIds, props.preview.entityTypes, run.mapping);
|
masks, docIds, props.preview.entityTypes, run.mapping, props.preview.imagePolicy);
|
||||||
}
|
}
|
||||||
const selectedIds = new Set(docIds);
|
const selectedIds = new Set(docIds);
|
||||||
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
||||||
@@ -389,15 +396,18 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
&& (entry.merged_into ?? placeholder) === hit.placeholder))) {
|
&& (entry.merged_into ?? placeholder) === hit.placeholder))) {
|
||||||
throw new Error(`${draft.file.relPath}: Zuordnungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
throw new Error(`${draft.file.relPath}: Zuordnungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||||
}
|
}
|
||||||
output = Buffer.from(result.file_base64, "base64");
|
imageReport = checkedImageReport(result, props.preview.imagePolicy);
|
||||||
|
const output = Buffer.from(result.file_base64, "base64");
|
||||||
|
await fs.writeFile(target, output, { mode: 0o600 });
|
||||||
|
outputHash = digest(output);
|
||||||
} else {
|
} else {
|
||||||
output = Buffer.from(replaceSpans(textFromBytes(data), withPersonMerges(draft.hits, activeMerges), accepted), "utf8");
|
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
|
||||||
|
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
|
||||||
}
|
}
|
||||||
await fs.writeFile(target, output, { mode: 0o600 });
|
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind, imageReport };
|
||||||
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind };
|
|
||||||
run.files.push(file);
|
run.files.push(file);
|
||||||
run.sourceState[inPlace ? relPath : file.source] = {
|
run.sourceState[inPlace ? relPath : file.source] = {
|
||||||
hash: inPlace ? digest(output) : draft.hash, output: relPath,
|
hash: inPlace ? outputHash : draft.hash, output: relPath,
|
||||||
};
|
};
|
||||||
replacements.push(file);
|
replacements.push(file);
|
||||||
}
|
}
|
||||||
@@ -421,6 +431,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
await saveProjectWhitelist(props.root, nextWhitelist);
|
await saveProjectWhitelist(props.root, nextWhitelist);
|
||||||
props.onWhitelistChanged(await loadProjectWhitelist(props.root));
|
props.onWhitelistChanged(await loadProjectWhitelist(props.root));
|
||||||
}
|
}
|
||||||
|
const images = summarizeImages(run.files);
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = inPlace ? (replacements.length ? `${replacements.length} Dateien ersetzt` : "Dateiauswahl aktualisiert")
|
toast.title = inPlace ? (replacements.length ? `${replacements.length} Dateien ersetzt` : "Dateiauswahl aktualisiert")
|
||||||
: `${run.files.length} Kopien erstellt`;
|
: `${run.files.length} Kopien erstellt`;
|
||||||
@@ -428,7 +439,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
: inPlace ? "Ausgeschlossene Dateien wurden im neuen Projektstand weggelassen."
|
: inPlace ? "Ausgeschlossene Dateien wurden im neuen Projektstand weggelassen."
|
||||||
: "Die Kopien liegen neben dem Projektordner.";
|
: "Die Kopien liegen neben dem Projektordner.";
|
||||||
setCompleted({ directory: inPlace && replacements.length ? join(directory, "backup")
|
setCompleted({ directory: inPlace && replacements.length ? join(directory, "backup")
|
||||||
: inPlace ? props.root : publishedCopyPath!, inPlace, files: run.files.length, replaced: replacements.length });
|
: inPlace ? props.root : publishedCopyPath!, inPlace, files: run.files.length, replaced: replacements.length, images });
|
||||||
await showInFinder(inPlace ? props.root : publishedCopyPath!).catch(() => undefined);
|
await showInFinder(inPlace ? props.root : publishedCopyPath!).catch(() => undefined);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (directory && !persisted) await fs.rm(directory, { recursive: true, force: true });
|
if (directory && !persisted) await fs.rm(directory, { recursive: true, force: true });
|
||||||
@@ -440,6 +451,10 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (completed) return <List navigationTitle="Pseudonymisierung abgeschlossen">
|
if (completed) return <List navigationTitle="Pseudonymisierung abgeschlossen">
|
||||||
|
<List.Item icon={completed.images.warnings.length ? Icon.Warning : Icon.Image}
|
||||||
|
title={`${completed.images.replaced} Bilder ersetzt · ${completed.images.removed} Bilder entfernt`}
|
||||||
|
subtitle={IMAGE_POLICY_LABELS[props.preview.imagePolicy]} />
|
||||||
|
{completed.images.warnings.map((warning) => <List.Item key={warning} icon={Icon.Warning} title={warning} />)}
|
||||||
<List.Item icon={Icon.CheckCircle}
|
<List.Item icon={Icon.CheckCircle}
|
||||||
title={completed.inPlace ? (completed.replaced ? "Projektdateien ersetzt" : "Dateiauswahl aktualisiert")
|
title={completed.inPlace ? (completed.replaced ? "Projektdateien ersetzt" : "Dateiauswahl aktualisiert")
|
||||||
: `${completed.files} pseudonymisierte Kopien erstellt`}
|
: `${completed.files} pseudonymisierte Kopien erstellt`}
|
||||||
@@ -456,7 +471,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
|
|
||||||
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen"
|
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen"
|
||||||
searchBarPlaceholder="Person oder Platzhalter suchen">
|
searchBarPlaceholder="Person oder Platzhalter suchen">
|
||||||
<List.Section title="Abschluss">
|
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||||
<List.Item icon={Icon.Play} title="Pseudonymisierung starten"
|
<List.Item icon={Icon.Play} title="Pseudonymisierung starten"
|
||||||
subtitle={`${selectedGroups.size} Zuordnungen · ${people.length} Personen · ${props.preview.retained.length} unveränderte Dateien übernommen`}
|
subtitle={`${selectedGroups.size} Zuordnungen · ${people.length} Personen · ${props.preview.retained.length} unveränderte Dateien übernommen`}
|
||||||
actions={<ActionPanel>
|
actions={<ActionPanel>
|
||||||
@@ -494,7 +509,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
|||||||
|
|
||||||
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen"
|
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen"
|
||||||
searchBarPlaceholder="Begriff oder Platzhalter suchen">
|
searchBarPlaceholder="Begriff oder Platzhalter suchen">
|
||||||
<List.Section title="Abschluss">
|
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||||
<List.Item key="apply" icon={Icon.Play}
|
<List.Item key="apply" icon={Icon.Play}
|
||||||
title={`${selectedGroups.size} von ${groups.length} Zuordnungen ausgewählt`}
|
title={`${selectedGroups.size} von ${groups.length} Zuordnungen ausgewählt`}
|
||||||
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
||||||
@@ -561,7 +576,7 @@ function SkippedFiles(props: { files: SkippedProjectFile[] }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
|
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||||
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean;
|
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean; imagePolicy: ImagePolicy;
|
||||||
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||||
const { push } = useNavigation();
|
const { push } = useNavigation();
|
||||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(
|
const [selected, setSelected] = useState<Set<string>>(() => new Set(
|
||||||
@@ -604,7 +619,7 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
|||||||
.map((file) => ({ path: file.relPath, reason: "Für dieses Projekt abgewählt" }))];
|
.map((file) => ({ path: file.relPath, reason: "Für dieses Projekt abgewählt" }))];
|
||||||
const whitelist = await loadProjectWhitelist(props.root);
|
const whitelist = await loadProjectWhitelist(props.root);
|
||||||
const preview = await prepare(props.root, files, props.rules, whitelist, props.types, skipped,
|
const preview = await prepare(props.root, files, props.rules, whitelist, props.types, skipped,
|
||||||
props.reanalyzeUnchanged, (message) => { toast.title = message; });
|
props.reanalyzeUnchanged, (message) => { toast.title = message; }, props.imagePolicy);
|
||||||
if (!preview.drafts.length && !preview.hits.length && !fileSelectionChanged) {
|
if (!preview.drafts.length && !preview.hits.length && !fileSelectionChanged) {
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Alle ausgewählten Projektdateien unverändert";
|
toast.title = "Alle ausgewählten Projektdateien unverändert";
|
||||||
@@ -657,6 +672,7 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
|||||||
export default function Command() {
|
export default function Command() {
|
||||||
const { push } = useNavigation();
|
const { push } = useNavigation();
|
||||||
const [root, setRoot] = useState("");
|
const [root, setRoot] = useState("");
|
||||||
|
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY);
|
||||||
const [rules, setRules] = useState("");
|
const [rules, setRules] = useState("");
|
||||||
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
|
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
|
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
|
||||||
@@ -745,7 +761,7 @@ export default function Command() {
|
|||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = `${scan.files.length} Dateien zur Auswahl`;
|
toast.title = `${scan.files.length} Dateien zur Auswahl`;
|
||||||
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
|
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
|
||||||
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged}
|
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged} imagePolicy={imagePolicy}
|
||||||
onWhitelistChanged={setWhitelist} />);
|
onWhitelistChanged={setWhitelist} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
@@ -778,6 +794,13 @@ export default function Command() {
|
|||||||
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
|
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
|
||||||
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}
|
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}
|
||||||
</Form.TagPicker>
|
</Form.TagPicker>
|
||||||
|
<Form.Dropdown id="imagePolicy" title="Bilder in Office/PDF" value={imagePolicy}
|
||||||
|
onChange={(value) => setImagePolicy(checkedImagePolicy(value))}>
|
||||||
|
{Object.entries(IMAGE_POLICY_LABELS).map(([value, title]) => <Form.Dropdown.Item key={value} value={value} title={title} />)}
|
||||||
|
</Form.Dropdown>
|
||||||
|
<Form.Description title={imagePolicy === "keep" ? "Achtung" : "Bildbehandlung"}
|
||||||
|
text={imagePolicy === "keep" ? KEEP_IMAGE_WARNING
|
||||||
|
: "Keine Analyse von Bildinhalten. Position und Größe bleiben bei Office-Platzhaltern soweit möglich erhalten. PDF wird als Word-Dokument neu aufgebaut. Entfernte Bilder sind nicht wiederherstellbar."} />
|
||||||
<Form.Checkbox id="reanalyzeUnchanged" title="Erneute Analyse"
|
<Form.Checkbox id="reanalyzeUnchanged" title="Erneute Analyse"
|
||||||
label="Auch unveränderte Dateien erneut analysieren" value={reanalyzeUnchanged}
|
label="Auch unveränderte Dateien erneut analysieren" value={reanalyzeUnchanged}
|
||||||
onChange={setReanalyzeUnchanged}
|
onChange={setReanalyzeUnchanged}
|
||||||
|
|||||||
25
src/velum.ts
25
src/velum.ts
@@ -1,4 +1,7 @@
|
|||||||
import { fetchWithAuth } from "./auth";
|
import { fetchWithAuth } from "./auth";
|
||||||
|
import { checkProjectCapabilities } from "./lib/project-capabilities";
|
||||||
|
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
|
||||||
|
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
import type {
|
import type {
|
||||||
DepseudonymizeResponse,
|
DepseudonymizeResponse,
|
||||||
@@ -112,8 +115,10 @@ export async function pseudonymize(
|
|||||||
mapping: PlaceholderMapping,
|
mapping: PlaceholderMapping,
|
||||||
entityTypes?: EntityType[],
|
entityTypes?: EntityType[],
|
||||||
forceMasks?: Record<string, string[]>,
|
forceMasks?: Record<string, string[]>,
|
||||||
|
signal?: AbortSignal,
|
||||||
): Promise<PseudonymizeResponse> {
|
): Promise<PseudonymizeResponse> {
|
||||||
const response = await fetchWithAuth(apiUrl("/api/pseudonymize"), {
|
const response = await fetchWithAuth(apiUrl("/api/pseudonymize"), {
|
||||||
|
signal,
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -141,19 +146,11 @@ export type DocumentHit = {
|
|||||||
original: string;
|
original: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function requireProjectCapabilities(): Promise<void> {
|
export async function requireProjectCapabilities(documents = false): Promise<void> {
|
||||||
const response = await fetchWithAuth(apiUrl("/api/project-capabilities"));
|
await checkProjectCapabilities(apiUrl("/api/project-capabilities"), documents, fetchWithAuth);
|
||||||
if (!response.ok) throw new Error("Die Velum-API muss für die Projektfunktionen aktualisiert werden.");
|
|
||||||
const capabilities = await parseJsonResponse<Record<string, boolean>>(response);
|
|
||||||
if (!capabilities.request_force_masks || !capabilities.document_hit_review
|
|
||||||
|| !capabilities.document_review_mapping
|
|
||||||
|| !capabilities.document_restoration || !capabilities.comment_author_review
|
|
||||||
|| !capabilities.revision_author_review) {
|
|
||||||
throw new Error("Die Velum-API unterstützt die Projektfunktionen noch nicht vollständig.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DocumentResult = {
|
export type DocumentResult = DocumentImageReport & {
|
||||||
filename: string;
|
filename: string;
|
||||||
content_type: string;
|
content_type: string;
|
||||||
file_base64: string;
|
file_base64: string;
|
||||||
@@ -170,18 +167,22 @@ export async function pseudonymizeDocument(
|
|||||||
acceptedHitIds?: string[],
|
acceptedHitIds?: string[],
|
||||||
entityTypes?: EntityType[],
|
entityTypes?: EntityType[],
|
||||||
analysisMapping?: PlaceholderMapping,
|
analysisMapping?: PlaceholderMapping,
|
||||||
|
imagePolicy: ImagePolicy = DEFAULT_IMAGE_POLICY,
|
||||||
): Promise<DocumentResult> {
|
): Promise<DocumentResult> {
|
||||||
|
checkedImagePolicy(imagePolicy);
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
||||||
form.set("mapping", JSON.stringify(mapping));
|
form.set("mapping", JSON.stringify(mapping));
|
||||||
form.set("force_masks", JSON.stringify(forceMasks));
|
form.set("force_masks", JSON.stringify(forceMasks));
|
||||||
|
form.set("image_policy", imagePolicy);
|
||||||
if (entityTypes !== undefined) form.set("entity_types", JSON.stringify(entityTypes));
|
if (entityTypes !== undefined) form.set("entity_types", JSON.stringify(entityTypes));
|
||||||
if (acceptedHitIds) form.set("accepted_hit_ids", JSON.stringify(acceptedHitIds));
|
if (acceptedHitIds) form.set("accepted_hit_ids", JSON.stringify(acceptedHitIds));
|
||||||
if (analysisMapping) form.set("analysis_mapping", JSON.stringify(analysisMapping));
|
if (analysisMapping) form.set("analysis_mapping", JSON.stringify(analysisMapping));
|
||||||
const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), {
|
const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), {
|
||||||
method: "POST", body: form,
|
method: "POST", body: form,
|
||||||
});
|
});
|
||||||
return parseJsonResponse<DocumentResult>(response);
|
const result = await parseJsonResponse<DocumentResult>(response);
|
||||||
|
return { ...result, ...checkedImageReport(result, imagePolicy) };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function depseudonymizeDocument(
|
export async function depseudonymizeDocument(
|
||||||
|
|||||||
83
tests/image-policy.test.ts
Normal file
83
tests/image-policy.test.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import ts from "typescript";
|
||||||
|
import * as imagePolicy from "../src/lib/image-policy";
|
||||||
|
import * as projectCapabilities from "../src/lib/project-capabilities";
|
||||||
|
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
|
||||||
|
|
||||||
|
const policies = ["placeholder", "remove", "keep"] as const;
|
||||||
|
function response(policy = "placeholder", changes: Record<string, unknown> = {}) {
|
||||||
|
return { image_policy: policy, images_replaced: 2, images_removed: 0,
|
||||||
|
media_parts_removed: 3, warnings: [], file_base64: "UFIDBA==", mapping: {}, hits: [], ...changes };
|
||||||
|
}
|
||||||
|
it("verwendet Platzhalter als sicheren Standard und lehnt unbekannte Optionen ab", () => {
|
||||||
|
expect(DEFAULT_IMAGE_POLICY).toBe("placeholder");
|
||||||
|
for (const policy of policies) expect(checkedImagePolicy(policy)).toBe(policy);
|
||||||
|
expect(() => checkedImagePolicy("unknown")).toThrow();
|
||||||
|
});
|
||||||
|
it("verarbeitet Dokumente alter Stände und bei geänderter Bildoption erneut", () => {
|
||||||
|
for (const selected of policies) {
|
||||||
|
expect(sameImagePolicyCoverage(undefined, selected)).toBe(false);
|
||||||
|
expect(sameImagePolicyCoverage({}, selected)).toBe(false);
|
||||||
|
for (const saved of policies) expect(sameImagePolicyCoverage({ imagePolicy: saved }, selected)).toBe(saved === selected);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("blockiert fehlende Bestätigung, ungültige Zähler und Warnungen", () => {
|
||||||
|
for (const changes of [{ image_policy: undefined }, { image_policy: "keep" },
|
||||||
|
{ images_removed: -1 }, { images_replaced: undefined }, { warnings: undefined }]) {
|
||||||
|
expect(() => checkedImageReport(response("placeholder", changes), "placeholder")).toThrow();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("speichert nur Bildzähler und Warnungen im Dateibericht", () => {
|
||||||
|
const checked = checkedImageReport(response(), "placeholder");
|
||||||
|
expect(Object.keys(checked).sort()).toEqual(["image_policy", "images_replaced", "images_removed", "media_parts_removed", "warnings"].sort());
|
||||||
|
expect("mapping" in checked).toBe(false);
|
||||||
|
expect("file_base64" in checked).toBe(false);
|
||||||
|
});
|
||||||
|
it("zeigt auch mit sonstigen Backend-Hinweisen bei keep eine Datenschutzwarnung", () => {
|
||||||
|
const report = checkedImageReport(response("keep", { warnings: ["Anderer Hinweis"] }), "keep");
|
||||||
|
expect(report.warnings).toEqual([KEEP_IMAGE_WARNING, "Anderer Hinweis"]);
|
||||||
|
expect(summarizeImages([{ imageReport: report }, { imageReport: report }])).toEqual({
|
||||||
|
replaced: 4, removed: 0, warnings: [KEEP_IMAGE_WARNING, "Anderer Hinweis"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleich", async () => {
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const code = ts.transpileModule(readFileSync(new URL("../src/velum.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023 },
|
||||||
|
}).outputText;
|
||||||
|
const calls: FormData[] = [];
|
||||||
|
let returnedPolicy = "placeholder";
|
||||||
|
let supportsImages = true;
|
||||||
|
const mocks: Record<string, unknown> = {
|
||||||
|
"./auth": { fetchWithAuth: async (url: string, init: RequestInit = {}) => {
|
||||||
|
if (url.endsWith("capabilities")) return Response.json({ request_force_masks: true,
|
||||||
|
document_hit_review: true, document_review_mapping: true, document_restoration: true,
|
||||||
|
comment_author_review: true, revision_author_review: true, document_image_policy: supportsImages });
|
||||||
|
calls.push(init.body as FormData);
|
||||||
|
return Response.json(response(returnedPolicy));
|
||||||
|
} },
|
||||||
|
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
|
||||||
|
"./lib/image-policy": imagePolicy,
|
||||||
|
"./lib/project-capabilities": projectCapabilities,
|
||||||
|
};
|
||||||
|
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
|
||||||
|
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
|
||||||
|
const api = module.exports;
|
||||||
|
for (const policy of policies) {
|
||||||
|
returnedPolicy = policy;
|
||||||
|
for (const accepted of [undefined, ["hit-1"], undefined, ["new-hit-1"]]) {
|
||||||
|
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {}, accepted, ["PERSON"], {}, policy);
|
||||||
|
expect(calls.at(-1)!.get("image_policy")).toBe(policy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
returnedPolicy = "placeholder";
|
||||||
|
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {});
|
||||||
|
expect(calls.at(-1)!.get("image_policy")).toBe("placeholder");
|
||||||
|
returnedPolicy = "keep";
|
||||||
|
await expect(api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {})).rejects.toThrow("bestätigt");
|
||||||
|
supportsImages = false;
|
||||||
|
await expect(api.requireProjectCapabilities(true)).rejects.toThrow();
|
||||||
|
await api.requireProjectCapabilities(false);
|
||||||
|
});
|
||||||
@@ -140,3 +140,23 @@ it("verweigert das stumme Zerschneiden eines überlangen Worts", () => {
|
|||||||
"ohne Trennstelle",
|
"ohne Trennstelle",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("zerlegt HTTP 413 ohne bestehende Zuordnungen oder Dateigrenzen zu verlieren", async () => {
|
||||||
|
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
|
||||||
|
let calls = 0;
|
||||||
|
const result = await analyzeProjectBatch(batch, {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
calls++; if (text.includes("Anna") && text.includes("Berta")) throw new Error("Velum API request failed: 413 Payload Too Large");
|
||||||
|
return response(text, mapping);
|
||||||
|
}, "Test");
|
||||||
|
expect(calls).toBe(3); expect(Object.keys(result.mapping)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
it("wiederholt Authentifizierungs- und Validierungsfehler nicht", async () => {
|
||||||
|
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
|
||||||
|
for (const status of [401, 403, 422]) {
|
||||||
|
let calls = 0;
|
||||||
|
await expect(analyzeProjectBatch(batch, {}, ["PERSON"], {}, async () => {
|
||||||
|
calls++; throw new Error(`Velum API request failed: ${status}`);
|
||||||
|
}, "Test")).rejects.toThrow(String(status));
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
42
tests/project-capabilities.test.ts
Normal file
42
tests/project-capabilities.test.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { checkProjectCapabilities, requiredProjectCapabilities } from "../src/lib/project-capabilities";
|
||||||
|
const url = "https://velum.invalid/api/project-capabilities";
|
||||||
|
const reply = (value: unknown) => async () => Response.json(value);
|
||||||
|
it("reproduziert die alte Meldung: Textprojekt benötigt keine Office-Fähigkeiten", async () => {
|
||||||
|
const olderBackend = { request_force_masks: true, document_hit_review: true, document_restoration: true };
|
||||||
|
await checkProjectCapabilities(url, false, reply(olderBackend));
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(olderBackend))).rejects.toThrow("document_review_mapping");
|
||||||
|
});
|
||||||
|
it("prüft jede Office-Schutzfunktion strikt, einschließlich Bilder und Autoren", async () => {
|
||||||
|
const complete = Object.fromEntries(requiredProjectCapabilities(true).map((key) => [key, true]));
|
||||||
|
await checkProjectCapabilities(url, true, reply(complete));
|
||||||
|
for (const key of Object.keys(complete)) {
|
||||||
|
const missing = { ...complete }; delete missing[key];
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(missing))).rejects.toThrow(key);
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply({ ...complete, [key]: "true" }))).rejects.toThrow(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("unterscheidet fehlende Endpunkte, Anmeldung, Größenlimits und Gateway-Fehler", async () => {
|
||||||
|
for (const status of [401, 403, 404, 405, 413, 502, 504]) {
|
||||||
|
await expect(checkProjectCapabilities(url, false, async () => new Response("", { status })))
|
||||||
|
.rejects.toThrow(`HTTP ${status}`);
|
||||||
|
}
|
||||||
|
await expect(checkProjectCapabilities(url, false, async () => new Response("Login", {
|
||||||
|
headers: { "content-type": "text/html" },
|
||||||
|
}))).rejects.toThrow("Keine JSON-Antwort");
|
||||||
|
});
|
||||||
|
it("meldet URL, fehlende Fähigkeit, ungültige Antwort und Zeitlimit", async () => {
|
||||||
|
await expect(checkProjectCapabilities(url, false, reply({}))).rejects.toThrow("request_force_masks");
|
||||||
|
for (const value of [null, [], true]) await expect(checkProjectCapabilities(url, false, reply(value)))
|
||||||
|
.rejects.toThrow("Ungültige Projektfähigkeiten");
|
||||||
|
await expect(checkProjectCapabilities(url, false, async (_url, init) => {
|
||||||
|
expect(init.signal).toBeDefined(); throw new DOMException("Deadline", "TimeoutError");
|
||||||
|
})).rejects.toThrow("Zeitlimit");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reproduziert die Live-API vom 8. November ohne document_image_policy", async () => {
|
||||||
|
const live = { request_force_masks: true, document_hit_review: true, document_review_mapping: true,
|
||||||
|
document_restoration: true, comment_author_review: true, revision_author_review: true };
|
||||||
|
await checkProjectCapabilities(url, false, reply(live));
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(live))).rejects.toThrow("document_image_policy");
|
||||||
|
});
|
||||||
124
tests/project-text-stream.test.ts
Normal file
124
tests/project-text-stream.test.ts
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import { afterEach, expect, it } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
|
||||||
|
import { decodedText, fileTextParts, hashProjectFile, inspectTextFile, textLines, writeReplacedTextFile } from "../src/lib/project-text-stream";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
|
||||||
|
async function fixture() { const root = await fs.mkdtemp(join(tmpdir(), "velum-stream-")); roots.push(root); return root; }
|
||||||
|
|
||||||
|
it("trennt vollständige Zeilen und bewahrt CRLF, CR, LF und die letzte Zeile", async () => {
|
||||||
|
async function* chunks() { yield "eins\r"; yield "\nzwei\rdr"; yield "ei\n😀Ende"; }
|
||||||
|
const lines = [];
|
||||||
|
for await (const line of textLines(chunks())) lines.push(line);
|
||||||
|
expect(lines).toEqual(["eins\r\n", "zwei\r", "drei\n", "😀Ende"]);
|
||||||
|
});
|
||||||
|
it("erhält auch bei byteweisen Lesevorgängen BOM, Umlaute und Emoji", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "unicode.txt");
|
||||||
|
await fs.writeFile(source, "\uFEFFÄ😀\r\nEnde");
|
||||||
|
let text = "";
|
||||||
|
for await (const part of decodedText(source, undefined, 1)) text += part;
|
||||||
|
expect(text).toBe("\uFEFFÄ😀\r\nEnde");
|
||||||
|
});
|
||||||
|
it("schneidet weder eine Zeile noch ein Wort an der Paketgrenze durch", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "lines.txt");
|
||||||
|
const text = "\uFEFF" + "Lange Füllzeile mit 😀.\r\n".repeat(800) + "Max Mustermann\r\nletzte Zeile";
|
||||||
|
await fs.writeFile(source, text);
|
||||||
|
let rebuilt = ""; let count = 0;
|
||||||
|
for await (const part of fileTextParts(source)) {
|
||||||
|
const core = text.slice(part.coreStart, part.coreEnd);
|
||||||
|
expect(part.text.slice(part.coreStart - part.scanStart, part.coreEnd - part.scanStart)).toBe(core);
|
||||||
|
if (part.coreEnd < text.length) expect(core.endsWith("\n")).toBe(true);
|
||||||
|
expect(part.text.length).toBeLessThan(24_000);
|
||||||
|
rebuilt += core; count++;
|
||||||
|
}
|
||||||
|
expect(count).toBeGreaterThan(1); expect(rebuilt).toBe(text);
|
||||||
|
});
|
||||||
|
it("analysiert mehr als 20 MiB und fügt nur bestätigte Treffer verlustfrei zur Datei zusammen", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "large.txt"); const target = join(root, "masked.txt");
|
||||||
|
const first = "\uFEFF😀 Max Mustermann\r\n"; const last = "Anna Berger ohne abschließenden Umbruch";
|
||||||
|
const filler = "Text ohne Treffer.\r\n".repeat(26_214);
|
||||||
|
const expected = createHash("sha256").update("\uFEFF😀 PERSON_01\r\n");
|
||||||
|
const handle = await fs.open(source, "w");
|
||||||
|
await handle.writeFile(first);
|
||||||
|
for (let i = 0; i < 64; i++) { await handle.writeFile(filler); expected.update(filler); }
|
||||||
|
await handle.writeFile(last); expected.update(last); await handle.close();
|
||||||
|
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
|
||||||
|
const hash = await inspectTextFile(source);
|
||||||
|
let requests = 0, active = 0, maxActive = 0;
|
||||||
|
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {}, ["PERSON"], {}, async (text, previous) => {
|
||||||
|
requests++; active++; maxActive = Math.max(maxActive, active);
|
||||||
|
expect(text.length).toBeLessThanOrEqual(24_000);
|
||||||
|
await Promise.resolve();
|
||||||
|
const mapping: PlaceholderMapping = { ...previous };
|
||||||
|
const spans = [...text.matchAll(/Max Mustermann|Anna Berger/g)].map((match) => {
|
||||||
|
const placeholder = match[0] === "Max Mustermann" ? "PERSON_01" : "PERSON_02";
|
||||||
|
mapping[placeholder] = { original: match[0], type: "PERSON" };
|
||||||
|
const start = [...text.slice(0, match.index)].length;
|
||||||
|
return { start, end: start + match[0].length, original: match[0], placeholder, type: "PERSON", score: 1 };
|
||||||
|
});
|
||||||
|
active--;
|
||||||
|
return { pseudonymized_text: text, mapping, spans, entity_count: Object.keys(mapping).length, selected_entity_types: ["PERSON"] };
|
||||||
|
}, () => undefined);
|
||||||
|
const spans = result.spansByFile.get("large.txt")!.map((span, i) => ({ ...span, id: String(i) }));
|
||||||
|
expect(spans.map((span) => span.original)).toEqual(["Max Mustermann", "Anna Berger"]);
|
||||||
|
expect(spans[0].start).toBe(first.indexOf("Max"));
|
||||||
|
expect(spans[1].start).toBe(first.length + 64 * filler.length);
|
||||||
|
expect(Object.keys(result.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
|
||||||
|
const outputHash = await writeReplacedTextFile(source, target, spans, new Set(["0"]), hash);
|
||||||
|
expect(outputHash).toBe(expected.digest("hex"));
|
||||||
|
expect(await hashProjectFile(target)).toBe(outputHash);
|
||||||
|
expect(await hashProjectFile(source)).toBe(hash);
|
||||||
|
expect(requests).toBeGreaterThan(1000); expect(maxActive).toBe(1);
|
||||||
|
}, 30_000);
|
||||||
|
it("ersetzt einen Treffer über einer Lesegrenze und erhält unveränderte Bytes", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "cross.txt"); const target = join(root, "out.txt");
|
||||||
|
const text = "x".repeat(65_531) + "Max Mustermann 😀\r\nEnde";
|
||||||
|
await fs.writeFile(source, text);
|
||||||
|
await writeReplacedTextFile(source, target, [{ id: "hit", start: 65_531, end: 65_545, placeholder: "PERSON_01" }], new Set(["hit"]), await hashProjectFile(source));
|
||||||
|
expect(await fs.readFile(target, "utf8")).toBe("x".repeat(65_531) + "PERSON_01 😀\r\nEnde");
|
||||||
|
});
|
||||||
|
it("hält Zuordnungen und Offsets über viele Dateien hinweg getrennt", async () => {
|
||||||
|
const root = await fixture(); const files = [];
|
||||||
|
for (let i = 0; i < 100; i++) { const path = join(root, `${i}.txt`); await fs.writeFile(path, "😀 Anna\r\n"); files.push({ key: String(i), path }); }
|
||||||
|
let requests = 0;
|
||||||
|
const result = await analyzeProjectTextFiles(files, {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
requests++;
|
||||||
|
return { pseudonymized_text: text, mapping: { ...mapping, PERSON_01: { original: "Anna", type: "PERSON" } }, selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
spans: [...text.matchAll(/Anna/g)].map((match) => ({ start: [...text.slice(0, match.index)].length, end: [...text.slice(0, match.index)].length + 4, original: "Anna", type: "PERSON", score: 1, placeholder: "PERSON_01" })) };
|
||||||
|
}, () => undefined);
|
||||||
|
expect(requests).toBe(1); expect(result.spansByFile.size).toBe(100);
|
||||||
|
for (const spans of result.spansByFile.values()) { expect(spans).toHaveLength(1); expect(spans[0].start).toBe(3); }
|
||||||
|
});
|
||||||
|
it("bricht überlange Zeilen ab und entfernt bei Quelländerungen die unvollständige Ausgabe", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "long.txt"); const target = join(root, "partial.txt");
|
||||||
|
await fs.writeFile(source, "x".repeat(20_001));
|
||||||
|
await expect(analyzeProjectTextFiles([{ key: "long.txt", path: source }], {}, [], {}, async () => { throw Error("should not call"); }, () => undefined)).rejects.toThrow("Zeile 1");
|
||||||
|
await expect(writeReplacedTextFile(source, target, [], new Set(), "old-hash")).rejects.toThrow("geändert");
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
expect((await fs.stat(source)).size).toBe(20_001);
|
||||||
|
});
|
||||||
|
it("verwirft Binärdaten und unvollständiges UTF-8 ohne fertige Ausgabedatei", async () => {
|
||||||
|
const root = await fixture();
|
||||||
|
for (const data of [Buffer.from([65, 0, 66]), Buffer.from([65, 0xc3])]) {
|
||||||
|
const source = join(root, "invalid.txt"); const target = join(root, "partial.txt"); await fs.writeFile(source, data);
|
||||||
|
await expect(inspectTextFile(source)).rejects.toThrow();
|
||||||
|
await expect(writeReplacedTextFile(source, target, [], new Set(), await hashProjectFile(source))).rejects.toThrow();
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erkennt einen Namen auch über zwei Zeilen und eine Paketgrenze hinweg genau einmal", async () => {
|
||||||
|
const root = await fixture(); const path = join(root, "boundary.txt");
|
||||||
|
const prefix = "x\n".repeat(4997);
|
||||||
|
await fs.writeFile(path, prefix + "Max\r\nMustermann\r\nEnde");
|
||||||
|
const result = await analyzeProjectTextFiles([{ key: "boundary.txt", path }], {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
const spans = [...text.matchAll(/Max\r\nMustermann/g)].map((match) => ({ start: match.index, end: match.index + match[0].length,
|
||||||
|
original: match[0], placeholder: "PERSON_01", type: "PERSON", score: 1 }));
|
||||||
|
return { pseudonymized_text: text, mapping, spans, entity_count: spans.length, selected_entity_types: ["PERSON"] };
|
||||||
|
}, () => undefined);
|
||||||
|
expect(result.spansByFile.get("boundary.txt")!.map((span) => [span.start, span.end])).toEqual([[prefix.length, prefix.length + 15]]);
|
||||||
|
});
|
||||||
@@ -498,3 +498,13 @@ describe("Velum-Projektstände", () => {
|
|||||||
expect(project.sameEntityTypeCoverage(run, ["PERSON", "EMAIL", "URL"])).toBe(false);
|
expect(project.sameEntityTypeCoverage(run, ["PERSON", "EMAIL", "URL"])).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("erfasst große Textdateien weiterhin, behält aber die Office-Uploadgrenze", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-large-scan-")); roots.push(root);
|
||||||
|
for (const name of ["large.txt", "large.docx"]) {
|
||||||
|
const handle = await fs.open(join(root, name), "w"); await handle.truncate(21 * 1024 * 1024); await handle.close();
|
||||||
|
}
|
||||||
|
const result = await project.scanProjectFiles(root, undefined, false);
|
||||||
|
expect(result.files.map((file) => file.relPath)).toEqual(["large.txt"]);
|
||||||
|
expect(result.skipped).toEqual([{ path: "large.docx", reason: "Datei zu groß (Grenze: 20 MiB)" }]);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user