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:
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 {
|
||||
EntityType,
|
||||
PlaceholderMapping,
|
||||
PseudonymizeResponse,
|
||||
} from "../types";
|
||||
import { makeTextBatches, spansBySegment } from "./project-review";
|
||||
import { makeTextBatches, MAX_BATCH_CODEPOINTS, spansBySegment } from "./project-review";
|
||||
import type { TextBatch } from "./project-review";
|
||||
|
||||
type Analyze = (
|
||||
@@ -31,7 +33,9 @@ export async function analyzeProjectBatch(
|
||||
return { mapping: result.mapping, results: [{ batch, result }] };
|
||||
} catch (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) {
|
||||
throw new Error(
|
||||
`${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;
|
||||
|
||||
/** Split only at whitespace, retaining context on both sides of every boundary. */
|
||||
export function splitTextForAnalysis(
|
||||
function* iterateTextForAnalysis(
|
||||
text: string,
|
||||
coreLength = TEXT_CORE_LENGTH,
|
||||
overlap = TEXT_CONTEXT_OVERLAP,
|
||||
): Array<{
|
||||
): Generator<{
|
||||
text: string;
|
||||
scanStart: number;
|
||||
coreStart: number;
|
||||
@@ -95,7 +99,6 @@ export function splitTextForAnalysis(
|
||||
}> {
|
||||
if (coreLength < 2 || overlap < 0)
|
||||
throw new Error("Ungültige Abschnittsgröße.");
|
||||
const parts = [];
|
||||
let coreStart = 0;
|
||||
while (coreStart < text.length) {
|
||||
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 (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
|
||||
scanEnd++;
|
||||
parts.push({
|
||||
yield {
|
||||
text: text.slice(scanStart, scanEnd),
|
||||
scanStart,
|
||||
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[] {
|
||||
@@ -144,9 +150,9 @@ function utf16Positions(text: string): number[] {
|
||||
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 result: TextSpan[] = [];
|
||||
const result: T[] = [];
|
||||
for (const span of sorted) {
|
||||
const last = result.at(-1);
|
||||
if (!last || span.start >= last.end) {
|
||||
@@ -173,34 +179,39 @@ export async function analyzeProjectTexts(
|
||||
mapping: PlaceholderMapping;
|
||||
spansByFile: Map<string, TextSpan[]>;
|
||||
}> {
|
||||
const chunks: TextChunk[] = [];
|
||||
const spansByFile = new Map(files.map(({ key }) => [key, [] as TextSpan[]]));
|
||||
for (const file of files) {
|
||||
let parts: ReturnType<typeof splitTextForAnalysis>;
|
||||
try {
|
||||
parts = splitTextForAnalysis(file.text);
|
||||
} catch (error) {
|
||||
throw new Error(`${file.key}: ${(error as Error).message}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
for (const [index, part] of parts.entries()) {
|
||||
chunks.push({
|
||||
...part,
|
||||
key: String(chunks.length),
|
||||
file: file.key,
|
||||
index,
|
||||
total: parts.length,
|
||||
});
|
||||
// Only the current request and its offset metadata stay alive. Do not build
|
||||
// arrays of every chunk and every concatenated request for a large file.
|
||||
function* batches(): Generator<{ batch: TextBatch; byKey: Map<string, TextChunk> }> {
|
||||
let chunks: TextChunk[] = [];
|
||||
let length = 0;
|
||||
for (const file of files) {
|
||||
let total = 0;
|
||||
try {
|
||||
for (const part of iterateTextForAnalysis(file.text)) if (part.coreEnd > part.coreStart) total++;
|
||||
let index = 0;
|
||||
for (const part of iterateTextForAnalysis(file.text)) {
|
||||
if (chunks.length && length + 4 + part.text.length > MAX_BATCH_CODEPOINTS) {
|
||||
yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||
chunks = [];
|
||||
length = 0;
|
||||
}
|
||||
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]));
|
||||
const batches = makeTextBatches(
|
||||
chunks.map(({ key, text }) => ({ key, text })),
|
||||
);
|
||||
let total = 0;
|
||||
for (const entry of batches()) if (entry.batch.segments.length) total++;
|
||||
let current = mapping;
|
||||
for (const [index, batch] of batches.entries()) {
|
||||
onProgress(index + 1, batches.length);
|
||||
let hitCount = 0;
|
||||
let index = 0;
|
||||
for (const { batch, byKey } of batches()) {
|
||||
onProgress(++index, total);
|
||||
const analyzed = await analyzeProjectBatch(
|
||||
batch,
|
||||
current,
|
||||
@@ -237,6 +248,7 @@ export async function analyzeProjectTexts(
|
||||
const end = chunk.scanStart + positions[span.end];
|
||||
if (start >= chunk.coreStart && start < chunk.coreEnd) {
|
||||
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));
|
||||
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 { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||
import { environment } from "@raycast/api";
|
||||
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||
import { whitelistKey } from "./project-whitelist";
|
||||
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
||||
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
import { restoreOriginalCase } from "./restore-case";
|
||||
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 ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
||||
export type SkippedProjectFile = { path: string; reason: string };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport };
|
||||
export type ProjectRun = {
|
||||
version: 2;
|
||||
origin?: "direct" | "imported";
|
||||
@@ -25,6 +27,8 @@ export type ProjectRun = {
|
||||
mapping: PlaceholderMapping;
|
||||
/** Categories actually used to analyze the files in this snapshot. */
|
||||
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. */
|
||||
sourceState?: Record<string, { hash: string; output: string }>;
|
||||
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
||||
@@ -231,7 +235,7 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
||||
export async function scanProjectFiles(root: string, maxSize?: number,
|
||||
validateText = true): Promise<{
|
||||
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
}> {
|
||||
@@ -258,15 +262,16 @@ export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
||||
continue;
|
||||
}
|
||||
const stat = await fs.stat(path);
|
||||
if (stat.size > maxSize) { skip(relPath, "Datei zu groß"); continue; }
|
||||
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||
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))) {
|
||||
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
||||
continue;
|
||||
}
|
||||
if (kind === "text" && validateText) {
|
||||
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; }
|
||||
}
|
||||
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. */
|
||||
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
||||
try {
|
||||
const previous = await fs.readFile(resolveWithin(join(directory, "files"), relPath));
|
||||
return digest(previous) === currentHash;
|
||||
return await hashProjectFile(resolveWithin(join(directory, "files"), relPath)) === currentHash;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
@@ -728,7 +732,7 @@ export async function replaceProjectFilesInPlace(projectPath: string, runDirecto
|
||||
try {
|
||||
for (const file of files) {
|
||||
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}`);
|
||||
}
|
||||
await fs.unlink(source);
|
||||
|
||||
Reference in New Issue
Block a user