feat: run Velum project jobs in the background and process DOCX locally

This commit is contained in:
muena
2026-11-30 16:12:11 +01:00
parent 11ddd6d70f
commit d2ed7130f0
32 changed files with 2325 additions and 462 deletions

135
src/lib/local-docx.ts Normal file
View File

@@ -0,0 +1,135 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import { constants, promises as fs } from "node:fs";
import { homedir } from "node:os";
import { delimiter, dirname, join } from "node:path";
import { promisify } from "node:util";
import { analyzeDocxSegments } from "../velum";
import type { EntityType, PlaceholderMapping } from "../types";
import { checkedImageReport } from "./image-policy";
import type { ImagePolicy } from "./image-policy";
import { MAX_BATCH_CODEPOINTS } from "./project-review";
import { projectTextAnalyzer } from "./project-text-mapping";
import type { Hit } from "./project-work";
type Segment = { text: string; source: string; kind: "text" | "author" | "link" | "email" };
const exec = promisify(execFile);
async function docxCodec(assets: string, args: string[]): Promise<unknown> {
const paths = [
...(process.env.PATH ?? "").split(delimiter).filter(Boolean),
"/opt/homebrew/bin", "/usr/local/bin", join(homedir(), ".local/bin"),
];
let uv: string | undefined;
for (const directory of new Set(paths)) {
const candidate = join(directory, "uv");
try {
await fs.access(candidate, constants.X_OK);
uv = candidate;
break;
} catch { /* check the next executable directory */ }
}
if (!uv) throw new Error("Für lokale DOCX-Aufträge wird uv benötigt. Bitte uv installieren und Raycast erneut öffnen.");
try {
const { stdout } = await exec(uv, [
"run", "--no-project", "--isolated", "--with", "lxml==6.2.1",
"--python", "3.11", "python", "-m", "velum.docx_local", ...args,
], { cwd: join(assets, "velum-docx"), maxBuffer: 192 * 1024 * 1024, env: { ...process.env, PYTHONUTF8: "1" } });
return JSON.parse(stdout);
} catch (error) {
const stderr = (error as { stderr?: string }).stderr?.trim();
throw new Error(stderr || "Lokaler DOCX-Schritt fehlgeschlagen.", { cause: error });
}
}
export async function inspectDocx(
assets: string, path: string, relative: string, hash: string, policy: ImagePolicy,
mapping: PlaceholderMapping, types: EntityType[], masks: Record<string, string[]>,
progress: (message: string) => void,
): Promise<{ hits: Hit[]; mapping: PlaceholderMapping; segmentCount: number }> {
const segments = await docxCodec(assets, ["extract", path, policy, hash]) as Segment[];
const hits: Hit[] = [];
let batch: Segment[] = [];
let offset = 0;
let size = 0;
let part = 0;
let current = mapping;
const analyze = projectTextAnalyzer(mapping, async (_text, window) => {
const response = await analyzeDocxSegments(batch.map(({ text, kind }) => ({ text, kind })), window, types, masks);
if (response.spans.length !== batch.length) throw new Error("Velum liefert eine ungültige Zahl von DOCX-Segmenten.");
let start = 0;
const spans = response.spans.flatMap((matches, index) => {
const segment = Array.from(batch[index].text);
const result = matches.map((span) => {
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|| span.start < 0 || span.start >= span.end || span.end > segment.length) {
throw new Error("Ungültige Trefferposition der Velum-DOCX-API.");
}
return { ...span, start: start + span.start, end: start + span.end };
});
start += segment.length + 2;
return result;
});
return { spans, mapping: response.mapping, selected_entity_types: types, pseudonymized_text: "", entity_count: 0 };
});
async function flush() {
if (batch.length === 0) return;
progress(`DOCX analysieren: ${relative} · Paket ${++part}`);
const text = batch.map((segment) => segment.text).join("\n\n");
const analyzed = await analyze(text, current, types, masks);
current = analyzed.mapping;
let start = 0;
let hit = 0;
const ordered = [...analyzed.spans].sort((a, b) => a.start - b.start);
for (const [index, segment] of batch.entries()) {
const characters = Array.from(segment.text);
const segmentIndex = offset + index;
while (hit < ordered.length && ordered[hit].start < start + characters.length) {
const span = ordered[hit++];
const begin = span.start - start;
const end = span.end - start;
if (begin < 0 || end > characters.length) throw new Error("DOCX-Treffer überschreitet sein Segment.");
hits.push({ ...span, start: begin, end, segment: segmentIndex,
id: `${relative}:local-docx:${segmentIndex}:${begin}:${end}`, file: relative, source: segment.source,
context: characters.slice(Math.max(0, begin - 60), end + 60).join(""), kind: "content" });
}
start += characters.length + 2;
}
if (hit !== ordered.length) throw new Error("DOCX-Treffer konnte keinem Segment zugeordnet werden.");
offset += batch.length;
batch = [];
size = 0;
}
for (const segment of segments) {
if (segment.text.length > 250_000) throw new Error("Ein einzelnes DOCX-Textfeld überschreitet 250.000 Zeichen.");
if (batch.length && (size + segment.text.length + 2 > MAX_BATCH_CODEPOINTS || batch.length === 256)) await flush();
batch.push(segment);
size += segment.text.length + 2;
}
await flush();
return { hits, mapping: current, segmentCount: segments.length };
}
export async function writeDocx(
assets: string, path: string, target: string, hash: string, policy: ImagePolicy, segmentCount: number,
hits: Hit[], accepted: Set<string>,
) {
const replacements: Record<string, { start: number; end: number; original: string; placeholder: string }[]> = {};
for (const hit of hits) {
if (!accepted.has(hit.id)) continue;
if (!Number.isSafeInteger(hit.segment) || hit.segment! < 0 || hit.segment! >= segmentCount) {
throw new Error("DOCX-Treffer hat kein gültiges Segment.");
}
const { start, end, original, placeholder } = hit;
(replacements[hit.segment!] ??= []).push({ start, end, original, placeholder });
}
for (const spans of Object.values(replacements)) spans.sort((a, b) => a.start - b.start);
const instructions = join(dirname(target), ".velum-replacements-" + randomUUID());
await fs.writeFile(instructions, JSON.stringify({ replacements, segmentCount }), { flag: "wx", mode: 0o600 });
try {
return checkedImageReport(await docxCodec(assets, ["apply", path, policy, hash, instructions, target]), policy);
} finally {
await fs.rm(instructions, { force: true });
}
}

60
src/lib/mapping-export.ts Normal file
View File

@@ -0,0 +1,60 @@
import { promises as fs } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { PlaceholderMapping } from "../types";
import { mappingRoot } from "./mapping-groups";
export type MappingExportKind = "terms" | "replacements";
/** One record per line; literal backslashes and line breaks remain distinguishable. */
function singleLine(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
}
export function mappingExport(mapping: PlaceholderMapping, kind: MappingExportKind): { text: string; count: number } {
const compare = (left: string, right: string) => left.localeCompare(right, "de", { numeric: true });
if (kind === "terms") {
const terms = [...new Set(Object.values(mapping).map((entry) => entry.original))].sort(compare);
return { text: terms.map(singleLine).join("\n") + (terms.length ? "\n" : ""), count: terms.length };
}
if (kind !== "replacements") throw new Error("Unbekanntes Exportformat.");
const pairs = new Map<string, { original: string; replacement: string }>();
for (const [key, entry] of Object.entries(mapping)) {
const replacement = mappingRoot(key, mapping);
pairs.set(JSON.stringify([entry.original, replacement]), { original: entry.original, replacement });
}
const rows = [...pairs.values()].sort((left, right) => compare(left.original, right.original)
|| compare(left.replacement, right.replacement));
return {
text: rows.map(({ original, replacement }) => `${singleLine(original)} → ${singleLine(replacement)}`).join("\n") + (rows.length ? "\n" : ""),
count: rows.length,
};
}
/** Save a private, complete UTF-8 copy, without replacing earlier exports. */
export async function writeMappingExport(title: string, mapping: PlaceholderMapping, kind: MappingExportKind,
directory = join(homedir(), "Downloads", "Velum")): Promise<{ path: string; count: number }> {
const { text, count } = mappingExport(mapping, kind);
if (!count) throw new Error("Diese Übersetzungstabelle enthält noch keine Begriffe.");
const name = [...title.normalize("NFC").replace(/[^\p{L}\p{N}_. -]/gu, "-")].slice(0, 40).join("")
.replace(/^[.\s-]+|[.\s-]+$/g, "") || "Velum";
const suffix = kind === "terms" ? "begriffe" : "ersetzungen";
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
const temporary = await fs.mkdtemp(join(directory, ".velum-export-"));
try {
const file = join(temporary, "export.txt");
await fs.writeFile(file, text, { encoding: "utf8", flag: "wx", mode: 0o600 });
for (let index = 0; index < 1000; index++) {
const path = join(directory, `${name}-${suffix}${index ? ` (${index + 1})` : ""}.txt`);
try {
await fs.link(file, path);
return { path, count };
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
}
throw new Error("Zu viele gleichnamige Exportdateien. Bitte ältere Exporte umbenennen.");
} finally {
await fs.rm(temporary, { recursive: true, force: true });
}
}

View File

@@ -208,7 +208,6 @@ export async function analyzeProjectTexts(
let total = 0;
for (const entry of batches()) if (entry.batch.segments.length) total++;
let current = mapping;
let hitCount = 0;
let index = 0;
for (const { batch, byKey } of batches()) {
onProgress(++index, total);
@@ -248,7 +247,6 @@ 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.");
}
}
}
@@ -273,7 +271,6 @@ export async function analyzeProjectTextFiles(
let size = 0;
let current = mapping;
let batchIndex = 0;
let hits = 0;
const flush = async () => {
if (!parts.length) return;
const batch = makeTextBatches(parts)[0];
@@ -295,7 +292,6 @@ export async function analyzeProjectTextFiles(
// 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.");
}
}
}

164
src/lib/project-jobs.ts Normal file
View File

@@ -0,0 +1,164 @@
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import { join } from "node:path";
import { environment } from "@raycast/api";
import { getPreferences } from "../preferences";
import { canonicalProjectPath, projectDataRoot } from "./velum-project";
import type { applyProject, prepareProject, Preview, ProjectOutput } from "./project-work";
export type AnalysisInput = {
root: string;
files: Parameters<typeof prepareProject>[2];
rules: Parameters<typeof prepareProject>[3];
whitelist: Parameters<typeof prepareProject>[4];
entityTypes: Parameters<typeof prepareProject>[5];
skipped: Parameters<typeof prepareProject>[6];
reanalyzeUnchanged: boolean;
imagePolicy: Parameters<typeof prepareProject>[9];
fileSelectionChanged: boolean;
};
export type Decision = Parameters<typeof applyProject>[5];
export type JobPhase = "analysis" | "apply";
export type ProjectJobState =
| { phase: JobPhase; pid: number; message: string }
| { phase: "review" }
| { phase: "complete"; output?: ProjectOutput; reused?: number }
| { phase: "error"; message: string };
export function projectJobDirectory(root: string, support = environment.supportPath): string {
return join(projectDataRoot(root, support), "active-job");
}
export async function writeJobJson(directory: string, file: string, value: unknown): Promise<void> {
const target = join(directory, file);
const temporary = target + "." + randomUUID();
try {
await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
await fs.rename(temporary, target);
} finally {
await fs.rm(temporary, { force: true });
}
}
export async function readJobJson<T>(directory: string, file: string): Promise<T> {
return JSON.parse(await fs.readFile(join(directory, file), "utf8")) as T;
}
export async function readProjectJob(root: string): Promise<ProjectJobState | undefined> {
const directory = projectJobDirectory(root);
let state: ProjectJobState;
try {
state = await readJobJson<ProjectJobState>(directory, "state.json");
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
const info = await fs.stat(directory).catch((statError: NodeJS.ErrnoException) => {
if (statError.code !== "ENOENT") throw statError;
});
if (info && Date.now() - info.mtimeMs > 10_000) {
return { phase: "error", message: "Der Projektauftrag wurde beim Start unterbrochen." };
}
return undefined;
}
if (state.phase === "analysis" || state.phase === "apply") {
try {
process.kill(state.pid, 0);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
// The worker writes its terminal state before exiting.
const last = await readJobJson<ProjectJobState>(directory, "state.json");
if (last.phase !== "analysis" && last.phase !== "apply") return last;
return { phase: "error", message: "Der lokale Hintergrundprozess wurde beendet." };
}
}
return state;
}
export async function loadProjectReview(root: string): Promise<{ input: AnalysisInput; preview: Preview }> {
const directory = projectJobDirectory(root);
const [input, preview] = await Promise.all([
readJobJson<AnalysisInput>(directory, "input.json"),
readJobJson<Preview>(directory, "preview.json"),
]);
return { input, preview };
}
async function launch(directory: string, phase: JobPhase): Promise<void> {
const config = JSON.stringify({
assets: environment.assetsPath,
support: environment.supportPath,
preferences: getPreferences(),
});
const child = spawn(process.execPath, [join(environment.assetsPath, "velum-project-worker.cjs"), directory, phase], {
detached: true,
stdio: ["pipe", "ignore", "ignore"],
cwd: directory,
});
// Register a handler immediately, before doing any asynchronous filesystem IO.
const started = new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("spawn", resolve);
});
child.stdin.on("error", () => undefined);
try {
await started;
await writeJobJson(directory, "state.json", { phase, pid: child.pid,
message: phase === "analysis" ? "Analyse startet" : "Ausgabe wird vorbereitet" });
// Only the pipe receives credentials. Job metadata, logs and arguments are
// safe to retain even after the window or worker closes.
await new Promise<void>((resolve, reject) => {
child.stdin.once("error", reject);
child.stdin.end(config, resolve);
});
} catch (error) {
child.stdin.destroy();
child.kill();
throw error;
} finally {
child.unref();
}
}
export async function startProjectAnalysis(input: AnalysisInput): Promise<void> {
const root = canonicalProjectPath(input.root);
const directory = projectJobDirectory(root);
await fs.mkdir(projectDataRoot(root), { recursive: true, mode: 0o700 });
await fs.mkdir(directory, { mode: 0o700 });
try {
await writeJobJson(directory, "input.json", { ...input, root });
await launch(directory, "analysis");
} catch (error) {
await writeJobJson(directory, "state.json", { phase: "error",
message: "Der lokale Hintergrundprozess konnte nicht gestartet werden." });
throw error;
}
}
export async function startProjectApply(root: string, decision: Decision): Promise<void> {
const directory = projectJobDirectory(root);
if ((await readProjectJob(root))?.phase !== "review") {
throw new Error("Dieser Projektauftrag steht nicht mehr zur Prüfung bereit.");
}
// Exclusive creation prevents two windows from publishing the same review.
await fs.writeFile(join(directory, "decision.json"), JSON.stringify(decision), { flag: "wx", mode: 0o600 });
try {
await launch(directory, "apply");
} catch (error) {
await fs.rm(join(directory, "decision.json"), { force: true });
await writeJobJson(directory, "state.json", { phase: "review" });
throw error;
}
}
export async function discardProjectJob(root: string): Promise<void> {
const state = await readProjectJob(root);
if (!state || state.phase === "analysis" || state.phase === "apply") {
throw new Error("Der Hintergrundauftrag läuft noch.");
}
const directory = projectJobDirectory(root);
if (state.phase === "review") {
// Mutual exclusion with the review's Apply action.
await fs.writeFile(join(directory, "decision.json"), "", { flag: "wx", mode: 0o600 });
}
await fs.rm(directory, { recursive: true, force: true });
}

View File

@@ -0,0 +1,99 @@
import type { PlaceholderMapping, PseudonymizeResponse } from "../types";
type Analyze = (text: string, mapping: PlaceholderMapping, types: string[],
masks: Record<string, string[]>) => Promise<PseudonymizeResponse>;
/** Keep project identities locally; the API sees only rules needed by this text. */
export function projectTextAnalyzer(initial: PlaceholderMapping, analyze: Analyze): Analyze {
const mapping: PlaceholderMapping = { ...initial };
const identities = new Map<string, string>();
const counters = new Map<string, number>();
const identity = (type: string, original: string) => JSON.stringify([type, original.trim().toLowerCase()]);
const roots = new Set(Object.values(initial).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
// Ordinary historical NER mappings do not force recognition. Only custom
// terms and user-confirmed person aliases have recognition semantics.
const rules: PlaceholderMapping = {};
for (const [key, entry] of Object.entries(initial)) {
identities.set(identity(entry.type, entry.original), key);
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
if (entry.type === "BEGRIFF" || entry.merged_into || roots.has(key)) rules[key] = entry;
}
const canonical = (key: string): string => {
const seen = new Set<string>();
while (mapping[key]?.merged_into) {
if (seen.has(key)) throw new Error("Zyklische Personen-Zusammenführung.");
seen.add(key);
key = mapping[key].merged_into!;
if (!mapping[key]) throw new Error("Ziel einer Personen-Zusammenführung fehlt.");
}
return key;
};
return async (text, _previous, types, masks) => {
// Other project phases (for example Office analysis) may have extended
// the mapping since the previous text request. Keep those identities too.
if (_previous !== mapping) {
const addedRoots = new Set(Object.values(_previous).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
for (const [key, entry] of Object.entries(_previous)) {
if (mapping[key] && identity(mapping[key].type, mapping[key].original) !== identity(entry.type, entry.original)) {
throw new Error("Widersprüchliche Platzhalter in der Projektzuordnung.");
}
mapping[key] = entry;
identities.set(identity(entry.type, entry.original), key);
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
if (entry.type === "BEGRIFF" || entry.merged_into || addedRoots.has(key)) rules[key] = entry;
}
}
const lower = text.toLowerCase().replace(/\s+/gu, " ");
const window: PlaceholderMapping = {};
for (const [key, entry] of Object.entries(rules)) {
if (!lower.includes(entry.original.trim().toLowerCase().replace(/\s+/gu, " "))) continue;
let dependency: string | null | undefined = key;
const seen = new Set<string>();
while (dependency) {
if (seen.has(dependency) || !mapping[dependency]) throw new Error("Ungültige Personen-Zusammenführung.");
seen.add(dependency);
window[dependency] = mapping[dependency];
dependency = mapping[dependency].merged_into;
}
}
const response = await analyze(text, window, types, masks);
const translated = new Map<string, string>();
for (const [remote, entry] of Object.entries(response.mapping)) {
const id = identity(entry.type, entry.original);
let local = identities.get(id);
if (!local) {
const number = (counters.get(entry.type) ?? 0) + 1;
counters.set(entry.type, number);
local = `${entry.type}_${String(number).padStart(2, "0")}`;
if (mapping[local]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
mapping[local] = { original: entry.original, type: entry.type };
identities.set(id, local);
if (entry.type === "BEGRIFF") rules[local] = mapping[local];
}
translated.set(remote, canonical(local));
}
const spans = response.spans.map((span) => {
const placeholder = translated.get(span.placeholder);
if (!placeholder) throw new Error("Velum-Treffer ohne passende Zuordnung.");
return { ...span, placeholder };
});
// Rebuild from original positions so existing literal placeholders are
// never accidentally renumbered alongside newly detected entities.
const characters = Array.from(text);
const pieces: string[] = [];
let offset = 0;
for (const span of [...spans].sort((a, b) => a.start - b.start)) {
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|| span.start < offset || span.start >= span.end || span.end > characters.length) {
throw new Error("Ungültige Trefferposition der Velum-API.");
}
pieces.push(characters.slice(offset, span.start).join(""), span.placeholder);
offset = span.end;
}
pieces.push(characters.slice(offset).join(""));
return { ...response, pseudonymized_text: pieces.join(""), mapping, spans,
entity_count: identities.size };
};
}

View File

@@ -122,11 +122,22 @@ export async function writeReplacedTextFile(
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");
let fragments: string[] = [];
let bufferedLength = 0;
const flushOutput = async () => {
if (!bufferedLength) return;
const bytes = Buffer.from(fragments.join(""), "utf8");
fragments = [];
bufferedLength = 0;
outputHash.update(bytes);
await output.writeFile(bytes);
};
const write = async (text: string) => {
if (!text) return;
fragments.push(text);
bufferedLength += text.length;
if (bufferedLength >= 64 * 1024) await flushOutput();
};
let offset = 0;
let pending = "";
let index = 0;
@@ -147,6 +158,7 @@ export async function writeReplacedTextFile(
offset += flush;
}
if (index !== selected.length || pending) throw new Error("Trefferposition liegt außerhalb der Quelldatei.");
await flushOutput();
if (inputHash.digest("hex") !== expectedHash) throw new Error("Datei wurde seit der Vorschau geändert.");
complete = true;
return outputHash.digest("hex");

362
src/lib/project-work.ts Normal file
View File

@@ -0,0 +1,362 @@
import { constants as fsConstants, promises as fs } from "node:fs";
import { basename, dirname, extname, join } from "node:path";
import { pseudonymize, pseudonymizeDocument, requireProjectCapabilities } from "../velum";
import type { DocumentHit } from "../velum";
import type { EntityType, PlaceholderMapping } from "../types";
import {
createRun, digest, forceMasks, listRuns, loadProjectWhitelist, publishProjectCopies, replaceSpans,
reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath,
saveProjectWhitelist, saveRun, sameEntityTypeCoverage, toUtf16Offsets,
} from "./velum-project";
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./velum-project";
import {
canonicalPerson, filenameScanText, makeTextBatches, mappingForSelection, reconcileDocumentHitIds, spansBySegment,
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
} from "./project-review";
import { analyzeProjectBatch, analyzeProjectTextFiles } from "./project-analysis";
import { projectTextAnalyzer } from "./project-text-mapping";
import { hashProjectFile, inspectTextFile, writeReplacedTextFile } from "./project-text-stream";
import { checkedImageReport, sameImagePolicyCoverage, summarizeImages } from "./image-policy";
import type { ImagePolicy, DocumentImageReport } from "./image-policy";
import { inspectDocx, writeDocx } from "./local-docx";
export type Hit = {
id: string; file: string; source: string; original: string; placeholder: string;
type: string; score: number; context: string; start: number; end: number;
kind: "content" | "path"; segment?: number;
};
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping; docxSegmentCount?: number };
type PathDraft = { key: string; value: string; hits: Hit[] };
export type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport; localDocx?: true }>;
baseRunId?: string; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
function isLocalDocx(file: ProjectFile): boolean {
return file.kind === "document" && extname(file.relPath).toLowerCase() === ".docx";
}
function isUnreadableDocument(error: unknown): boolean {
const message = error instanceof Error ? error.message : "";
return /request failed: 422\b/i.test(message)
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
}
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
file: file.relPath, kind: "content" as const }));
}
function pathSegments(files: ProjectFile[]): PathDraft[] {
const map = new Map<string, PathDraft>();
for (const file of files) {
const parts = file.relPath.split("/");
for (let index = 0; index < parts.length; index++) {
const key = parts.slice(0, index + 1).join("/");
const isFile = index === parts.length - 1;
const value = isFile ? basename(parts[index], extname(parts[index])) : parts[index];
if (value && !map.has(key)) map.set(key, { key, value, hits: [] });
}
}
return [...map.values()];
}
export async function prepareProject(assets: string, root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
onProgress: (message: string) => void, imagePolicy: ImagePolicy): Promise<Preview> {
await requireProjectCapabilities(files.some((file) => file.kind === "document" && !isLocalDocx(file)));
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
const latestEntry = (await listRuns(root))[0];
const latest = latestEntry?.run;
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
const previousPlaceholders = Object.keys(previousMapping);
let mapping: PlaceholderMapping = previousMapping;
const drafts: Draft[] = [];
const retained: Preview["retained"] = [];
const hits: Hit[] = [];
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
const previousDirectory = latestEntry?.directory;
for (const file of files) {
onProgress(`Datei prüfen: ${file.relPath}`);
let hash: string;
try { hash = file.kind === "text" ? await inspectTextFile(file.absPath) : await hashProjectFile(file.absPath); }
catch (error) {
const reason = (error as Error).message;
if (!/^(Binärdatei|Keine gültige UTF-8-Textdatei)$/.test(reason)) throw error;
skipped.push({ path: file.relPath, reason });
continue;
}
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
const previousFile = latest?.files.find((saved) => saved.output === previousOutput);
if (previousOutput && previousDirectory && (!isLocalDocx(file) || previousFile?.localDocx)) {
retained.push({ file, hash, output: previousOutput, directory: previousDirectory,
imageReport: previousFile?.imageReport, localDocx: previousFile?.localDocx });
continue;
}
const draft: Draft = { file, hash, hits: [] };
drafts.push(draft);
}
const addHits = (draft: Draft, found: Hit[]) => {
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
for (const hit of draft.hits) hits.push(hit);
};
const textDrafts = drafts.filter((draft) => draft.file.kind === "text");
const analyzeText = projectTextAnalyzer(mapping, async (text, current, types, rules) => {
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;
for (const draft of textDrafts) {
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde während der Analyse geändert: ${draft.file.relPath}`);
addHits(draft, (analyzedTexts.spansByFile.get(draft.file.relPath) ?? []).map((span, index) => Object.assign(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");
for (const [index, draft] of documents.entries()) {
onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`);
try {
if (isLocalDocx(draft.file)) {
const result = await inspectDocx(assets, draft.file.absPath, draft.file.relPath, draft.hash,
imagePolicy, mapping, entityTypes, masks, onProgress);
mapping = result.mapping;
draft.docxSegmentCount = result.segmentCount;
addHits(draft, result.hits);
continue;
}
const data = await fs.readFile(draft.file.absPath);
draft.analysisMapping = mapping;
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes, undefined, imagePolicy);
mapping = result.mapping;
addHits(draft, documentHits(draft.file, result.hits));
} catch (error) {
if (isLocalDocx(draft.file) || !isUnreadableDocument(error)) {
throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`);
}
skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" });
drafts.splice(drafts.indexOf(draft), 1);
}
}
// Names of retained files already have a reviewed output in the saved stand.
// Only new or changed files need another filename analysis.
if (!drafts.length && !retained.length) {
const first = skipped[0];
throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
}
const paths = pathSegments(drafts.map((draft) => draft.file));
const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original),
...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)];
const pathBatches = makeTextBatches(paths.map((path) => ({
key: path.key, text: filenameScanText(path.value, knownTerms),
})));
const byPath = new Map(paths.map((path) => [path.key, path]));
for (const [index, batch] of pathBatches.entries()) {
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, analyzeText,
"Dateinamen analysieren");
mapping = analyzed.mapping;
for (const { batch: part, result } of analyzed.results) {
const spans = spansBySegment(part, result.spans);
for (const segment of part.segments) {
const path = byPath.get(segment.key)!;
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
source: "Datei- oder Ordnername", kind: "path" as const,
context: path.value,
}));
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
for (const hit of path.hits) hits.push(hit);
}
}
}
return { drafts, retained, paths, mapping, previousMapping, baseRunId: latest?.id,
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
}
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
merges: Record<string, string>): string {
const lookup = new Map(paths.map((item) => [item.key, item]));
const parts = relPath.split("/");
const output = parts.map((part, index) => {
const key = parts.slice(0, index + 1).join("/");
const path = lookup.get(key);
if (!path) return part;
const isFile = index === parts.length - 1;
const extension = isFile ? (document && extname(part).toLowerCase() === ".pdf" ? ".docx" : extname(part)) : "";
return replaceSpans(path.value, withPersonMerges(path.hits, merges), accepted) + extension;
});
return safeRelativePath(output.join("/"));
}
function withPersonMerges(hits: Hit[], merges: Record<string, string>): Hit[] {
return hits.map((hit) => hit.type === "PERSON"
? { ...hit, placeholder: canonicalPerson(hit.placeholder, merges) } : hit);
}
export type ProjectOutput = {
directory: string; inPlace: boolean; files: number; replaced: number;
images: ReturnType<typeof summarizeImages>;
};
export async function applyProject(
assets: string, root: string, preview: Preview, rules: ProjectRule[], whitelist: ProjectWhitelistEntry[],
decision: { inPlace: boolean; acceptedIds: string[]; activeMerges: Record<string, string>; rejected: ProjectWhitelistEntry[] },
progress: (message: string) => void,
): Promise<ProjectOutput> {
const { inPlace, acceptedIds, activeMerges, rejected } = decision;
const accepted = new Set(acceptedIds);
const acceptedHits = preview.hits.filter((hit) => accepted.has(hit.id));
if (acceptedHits.length !== accepted.size) throw new Error("Die Auswahl passt nicht mehr zur gespeicherten Vorschau.");
let directory: string | undefined;
let publishedCopyPath: string | undefined;
let persisted = false;
let keepRecoveryDirectory = false;
try {
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
}
const created = await createRun(root);
directory = created.directory;
const { run } = created;
run.mapping = mappingForSelection(preview.mapping, preview.previousMapping,
acceptedHits, activeMerges);
run.entityTypes = [...preview.entityTypes];
run.imagePolicy = preview.imagePolicy;
run.sourceState = {};
run.commentAuthorCoverage = preview.entityTypes.includes("PERSON");
run.reviewAuthorCoverage = preview.entityTypes.includes("PERSON");
run.matchModes = preview.matchModes;
run.sourceInPlace = preview.sourceInPlace || inPlace;
const usedPaths = new Set<string>();
const replacements: RunFile[] = [];
const sources = new Map<string, string>();
const total = preview.retained.length + preview.drafts.length;
let processed = 0;
for (const retained of preview.retained) {
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
sources.set(retained.file.relPath, retained.hash);
if (await hashProjectFile(retained.file.absPath) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
const relPath = retained.output;
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
usedPaths.add(relPath);
const target = resolveWithin(join(directory, "files"), relPath);
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target,
fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
await fs.chmod(target, 0o600);
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind, imageReport: retained.imageReport, localDocx: retained.localDocx };
run.files.push(file);
run.sourceState[inPlace ? relPath : file.source] = {
hash: inPlace ? await hashProjectFile(target) : retained.hash, output: relPath,
};
// 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.
if (file.source !== file.output || (inPlace && !preview.sourceInPlace)) replacements.push(file);
}
for (const draft of preview.drafts) {
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
sources.set(draft.file.relPath, draft.hash);
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
const relPath = outputPath(draft.file.relPath, preview.paths, accepted,
draft.file.kind === "document", activeMerges);
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
usedPaths.add(relPath);
const target = resolveWithin(join(directory, "files"), relPath);
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
let outputHash: string;
let imageReport: DocumentImageReport | undefined;
if (draft.docxSegmentCount !== undefined) {
imageReport = await writeDocx(assets, draft.file.absPath, target, draft.hash, preview.imagePolicy,
draft.docxSegmentCount, withPersonMerges(draft.hits, activeMerges), accepted);
outputHash = await hashProjectFile(target);
} else if (draft.file.kind === "document") {
const data = await fs.readFile(draft.file.absPath);
const idPrefix = `${draft.file.relPath}:document:`;
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));
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
let result;
try {
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
masks, docIds, preview.entityTypes, draft.analysisMapping, preview.imagePolicy);
} catch (error) {
if (!/\b409\b/.test((error as Error).message) || !/Treffer passen nicht mehr/.test((error as Error).message)) {
throw error;
}
const refreshed = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
masks, undefined, preview.entityTypes, undefined, preview.imagePolicy);
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.`);
docIds = ids;
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
masks, docIds, preview.entityTypes, run.mapping, preview.imagePolicy);
}
const selectedIds = new Set(docIds);
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
if (selectedHits.length !== selectedIds.size || selectedHits.some((hit) => !Object.entries(run.mapping)
.some(([placeholder, entry]) => entry.type === hit.type
&& entry.original.toLocaleLowerCase() === hit.original.toLocaleLowerCase()
&& (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.`);
}
imageReport = checkedImageReport(result, preview.imagePolicy);
const output = Buffer.from(result.file_base64, "base64");
await fs.writeFile(target, output, { mode: 0o600 });
outputHash = digest(output);
} else {
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
}
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind, imageReport,
localDocx: draft.docxSegmentCount !== undefined ? true : undefined };
run.files.push(file);
run.sourceState[inPlace ? relPath : file.source] = {
hash: inPlace ? outputHash : draft.hash, output: relPath,
};
replacements.push(file);
}
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
}
if (!inPlace) {
publishedCopyPath = await publishProjectCopies(run, directory);
run.copyPath = publishedCopyPath;
}
if (inPlace) {
if (replacements.length) {
// Keep recoverable files if an interrupted replacement needs its backup.
keepRecoveryDirectory = true;
await replaceProjectFilesInPlace(root, directory, replacements, sources);
}
run.inPlace = true;
}
await saveRun(directory, run);
persisted = true;
if (rejected.length) {
const nextWhitelist = [...await loadProjectWhitelist(root), ...rejected];
await saveProjectWhitelist(root, nextWhitelist);
}
return { directory: inPlace && replacements.length ? join(directory, "backup")
: inPlace ? root : publishedCopyPath!, inPlace, files: run.files.length,
replaced: replacements.length, images: summarizeImages(run.files) };
} catch (error) {
if (directory && !persisted && !keepRecoveryDirectory) await fs.rm(directory, { recursive: true, force: true });
if (publishedCopyPath && !persisted) await fs.rm(publishedCopyPath, { recursive: true, force: true });
throw new Error(`${(error as Error).message}${(persisted || keepRecoveryDirectory) && directory ? ` Kopien/Sicherung: ${directory}` : ""}`, { cause: error });
}
}

View File

@@ -16,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"]; imageReport?: DocumentImageReport };
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport; localDocx?: true };
export type ProjectRun = {
version: 2;
origin?: "direct" | "imported";
@@ -236,7 +236,7 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
}
export async function scanProjectFiles(root: string, maxSize?: number,
validateText = true): Promise<{
validateText = true, documentLimits: Readonly<Record<string, number>> = {}): Promise<{
files: ProjectFile[]; skipped: SkippedProjectFile[];
}> {
const files: ProjectFile[] = [];
@@ -263,7 +263,8 @@ export async function scanProjectFiles(root: string, maxSize?: number,
}
const stat = await fs.stat(path);
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
const limit = maxSize ?? (kind === "document" ? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
const limit = maxSize ?? (kind === "document"
? documentLimits[extname(path).toLowerCase()] ?? 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)");
@@ -533,7 +534,8 @@ export async function scanRestorableCopyFiles(run: ProjectRun, directory: string
root = join(directory, "files");
}
}
const scan = await scanProjectFiles(root);
// XLSX restoration runs locally as a stream and does not upload the file.
const scan = await scanProjectFiles(root, undefined, true, { ".xlsx": Number.POSITIVE_INFINITY });
const files = scan.files.filter((file) => file.kind === "text" || isRestorableDocument(file.relPath));
return { root, files, skipped: scan.skipped.length + scan.files.length - files.length };
}

21
src/lib/worker-runtime.ts Normal file
View File

@@ -0,0 +1,21 @@
import type { NormalizedPreferences } from "../preferences";
// Only these Raycast services are used by the shared Node project code.
export const environment = { assetsPath: "", supportPath: "" };
let preferences: NormalizedPreferences;
export function getPreferenceValues<T>(): T {
return preferences as T;
}
const tokenStore = new Map<string, string>();
export const LocalStorage = {
async getItem<T>(key: string) { return tokenStore.get(key) as T | undefined; },
async setItem(key: string, value: string) { tokenStore.set(key, value); },
async removeItem(key: string) { tokenStore.delete(key); },
};
export function configureWorker(config: { assets: string; support: string; preferences: NormalizedPreferences }) {
environment.assetsPath = config.assets;
environment.supportPath = config.support;
preferences = config.preferences;
}

274
src/lib/xlsx-restoration.ts Normal file
View File

@@ -0,0 +1,274 @@
import { createReadStream, closeSync, openSync, writeSync, promises as fs } from "node:fs";
import { join, posix } from "node:path";
import { tmpdir } from "node:os";
import { TextDecoder } from "node:util";
import { Unzip, UnzipInflate, Zip, ZipDeflate } from "fflate";
import { SaxesParser, type SaxesTagNS } from "saxes";
import type { PlaceholderMapping } from "../types";
const EMPTY = new Uint8Array(0);
const SPREADSHEET = new Set([
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"http://purl.oclc.org/ooxml/spreadsheetml/main",
]);
const DRAWING = new Set([
"http://schemas.openxmlformats.org/drawingml/2006/main",
"http://purl.oclc.org/ooxml/drawingml/main",
]);
const WORD = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const isTextRun = (node: SaxesTagNS) => node.local === "t" && (SPREADSHEET.has(node.uri) || DRAWING.has(node.uri) || node.uri === WORD);
const isTextUnit = (node: SaxesTagNS) => SPREADSHEET.has(node.uri) && ["si", "is"].includes(node.local)
|| node.local === "p" && (DRAWING.has(node.uri) || node.uri === WORD);
const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
let value = index;
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0);
return value >>> 0;
});
function crcUpdate(crc: number, data: Uint8Array): number {
for (const value of data) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ value) & 255];
return crc;
}
type ZipPart = { size: number; crc: number };
/** Inspect the small central directory; never load a worksheet or the whole ZIP. */
async function zipIndex(path: string): Promise<Map<string, ZipPart>> {
const file = await fs.open(path, "r");
try {
const { size } = await file.stat();
const tail = Buffer.alloc(Math.min(size, 65_557));
await file.read(tail, 0, tail.length, size - tail.length);
let end = -1;
for (let i = tail.length - 22; i >= 0; i--) {
if (tail.readUInt32LE(i) === 0x06054b50 && i + 22 + tail.readUInt16LE(i + 20) === tail.length) { end = i; break; }
}
if (end < 0) throw new Error("Excel-Datei ist kein vollständiges ZIP-Archiv.");
const entries = tail.readUInt16LE(end + 10);
const length = tail.readUInt32LE(end + 12), offset = tail.readUInt32LE(end + 16);
if (tail.readUInt16LE(end + 4) || tail.readUInt16LE(end + 6) || entries !== tail.readUInt16LE(end + 8)
|| entries === 0xffff || offset === 0xffffffff || length > 16 * 1024 * 1024 || offset + length > size - tail.length + end) {
throw new Error("Nicht unterstütztes Excel-ZIP-Archiv (mehrteilig, ZIP64 oder zu großes Inhaltsverzeichnis).");
}
const directory = Buffer.alloc(length);
if ((await file.read(directory, 0, length, offset)).bytesRead !== length) throw new Error("Unvollständiges ZIP-Inhaltsverzeichnis.");
const parts = new Map<string, ZipPart>();
let cursor = 0, total = 0;
for (let index = 0; index < entries; index++) {
if (cursor + 46 > length || directory.readUInt32LE(cursor) !== 0x02014b50) throw new Error("Ungültiges ZIP-Inhaltsverzeichnis.");
const flags = directory.readUInt16LE(cursor + 8), method = directory.readUInt16LE(cursor + 10);
const nameLength = directory.readUInt16LE(cursor + 28);
const next = cursor + 46 + nameLength + directory.readUInt16LE(cursor + 30) + directory.readUInt16LE(cursor + 32);
if (next > length || flags & 1 || ![0, 8].includes(method)) throw new Error("Verschlüsselte oder nicht unterstützte Excel-Datei.");
const rawName = directory.subarray(cursor + 46, cursor + 46 + nameLength);
if (!(flags & 0x800) && rawName.some((value) => value > 127)) throw new Error("Nicht unterstützte ZIP-Dateinamencodierung.");
const name = new TextDecoder("utf-8", { fatal: true }).decode(rawName);
if (parts.has(name) || name.startsWith("/") || name.includes("\\")
|| posix.normalize(name) !== name || name.split("/").includes("..")) throw new Error("Ungültiger oder doppelter Excel-Paketbestandteil.");
const part = { size: directory.readUInt32LE(cursor + 24), crc: directory.readUInt32LE(cursor + 16) };
total += part.size;
if (part.size === 0xffffffff || total > 2 * 1024 * 1024 * 1024) throw new Error("Entpackte Excel-Datei überschreitet 2 GiB.");
parts.set(name, part);
cursor = next;
}
if (cursor !== length || !parts.has("xl/workbook.xml") || !parts.has("[Content_Types].xml")) throw new Error("Datei ist kein unterstütztes Excel-Workbook.");
return parts;
} finally { await file.close(); }
}
function escapeXml(value: string, attribute = false): string {
let result = value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "&#13;");
if (attribute) result = result.replace(/"/g, "&quot;").replace(/\t/g, "&#9;").replace(/\n/g, "&#10;");
return result;
}
function restorationPattern(mapping: PlaceholderMapping) {
const originals = new Map<string, string>();
for (const [key, entry] of Object.entries(mapping)) {
for (const char of entry.original) {
const code = char.codePointAt(0)!;
if ((code < 32 && ![9, 10, 13].includes(code)) || (code >= 0xd800 && code <= 0xdfff) || code === 0xfffe || code === 0xffff) {
throw new Error("Zuordnung enthält Zeichen, die in Excel-XML nicht erlaubt sind.");
}
}
originals.set(key, entry.original);
}
const keys = [...originals.keys()].filter((key) => key && !/^[A-Z][A-Z0-9]*_\d+$/.test(key)).sort((a, b) => b.length - a.length);
const alternatives = keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
alternatives.push("[A-Z][A-Z0-9]*_\\d+");
const pattern = originals.size ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives.join("|")})(?![\\p{L}\\p{N}_])`, "gu") : undefined;
return { originals, pattern };
}
type Token = { markup: string } | { text: string; run: boolean };
/** Buffer one rich-text cell or drawing paragraph, never a table or worksheet. */
function xmlRestorer(mapping: ReturnType<typeof restorationPattern>, emit: (text: string) => void, workbook: boolean) {
let replacements = 0;
const restore = (text: string) => mapping.pattern ? text.replace(mapping.pattern, (match) => {
const original = mapping.originals.get(match);
if (original === undefined) return match;
replacements++;
return original;
}) : text;
const parser = new SaxesParser({ xmlns: true });
const stack: SaxesTagNS[] = [];
let cell: { depth: number; tokens: Token[]; length: number } | undefined;
let pending = "";
const append = (token: Token) => {
if (!cell) { emit("markup" in token ? token.markup : escapeXml(restore(token.text))); return; }
cell.length += "markup" in token ? token.markup.length : token.text.length;
if (cell.length > 4 * 1024 * 1024) throw new Error("Eine einzelne Excel-Zelle überschreitet 4 MiB XML.");
cell.tokens.push(token);
};
const flushText = () => {
if (!pending) return;
const node = stack.at(-1);
append({ text: pending, run: Boolean(node && isTextRun(node)) });
pending = "";
};
const flushCell = () => {
const tokens = cell!.tokens;
const runs = tokens.filter((token): token is Extract<Token, { text: string }> => "text" in token && token.run);
const joined = runs.map((run) => run.text).join("");
const matches = mapping.pattern ? [...joined.matchAll(mapping.pattern)].filter((match) => mapping.originals.has(match[0])) : [];
replacements += matches.length;
let offset = 0, next = 0;
for (const run of runs) {
const start = offset, end = start + run.text.length;
let cursor = 0, output = "";
while (next < matches.length && matches[next].index + matches[next][0].length <= start) next++;
for (let i = next; i < matches.length && matches[i].index < end; i++) {
const match = matches[i], stop = match.index + match[0].length;
output += run.text.slice(cursor, Math.max(cursor, match.index - start));
if (match.index >= start) output += mapping.originals.get(match[0])!;
cursor = Math.min(run.text.length, stop - start);
}
run.text = output + run.text.slice(cursor);
offset = end;
}
for (const token of tokens) emit("markup" in token ? token.markup : escapeXml(token.run ? token.text : restore(token.text)));
cell = undefined;
};
parser.on("xmldecl", (declaration) => {
if (declaration.version !== "1.0") throw new Error("Nur XML 1.0 wird in Excel-Dateien unterstützt.");
});
parser.on("doctype", () => { throw new Error("DTD/Entities werden in Excel-Dateien nicht unterstützt."); });
parser.on("opentag", (node) => {
flushText();
if (!stack.length && workbook && (!SPREADSHEET.has(node.uri) || node.local !== "workbook")) throw new Error("Ungültiger Excel-Workbook-Bestandteil.");
stack.push(node);
if (!cell && isTextUnit(node)) cell = { depth: stack.length, tokens: [], length: 0 };
const attributes = Object.values(node.attributes).map((attr) => ` ${attr.name}="${escapeXml(restore(attr.value), true)}"`).join("");
const preserve = SPREADSHEET.has(node.uri) && node.local === "t" && !node.attributes["xml:space"] ? ' xml:space="preserve"' : "";
append({ markup: `<${node.name}${attributes}${preserve}>` });
});
parser.on("closetag", (node) => {
flushText();
append({ markup: `</${node.name}>` });
if (cell?.depth === stack.length) flushCell();
stack.pop();
});
const text = (value: string) => {
pending += value;
if (pending.length > 4 * 1024 * 1024) throw new Error("Ein Excel-Textknoten überschreitet 4 MiB.");
};
parser.on("text", text);
parser.on("cdata", text);
parser.on("comment", (value) => { flushText(); append({ markup: `<!--${value}-->` }); });
parser.on("processinginstruction", (value) => { flushText(); append({ markup: `<?${value.target}${value.body ? " " + value.body : ""}?>` }); });
emit('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
return { push: (text: string) => parser.write(text), end: () => { parser.close(); flushText(); return replacements; } };
}
/** Restore an XLSX directly from disk to a new private file, with bounded XML memory. */
export async function restoreXlsxFile(source: string, target: string, mapping: PlaceholderMapping,
onProgress: (percent: number) => void = () => undefined): Promise<{ replacements: number }> {
const before = await fs.stat(source);
const index = await zipIndex(source);
const matcher = restorationPattern(mapping);
const descriptor = openSync(target, "wx", 0o600);
let complete = false, zipComplete = false, replacements = 0, processed = 0, progress = -1;
const seen = new Set<string>(), finished = new Set<string>();
const total = [...index.values()].reduce((sum, part) => sum + part.size, 0);
const zip = new Zip((error, data, final) => {
if (error) throw error;
let offset = 0;
while (offset < data.length) offset += writeSync(descriptor, data, offset, data.length - offset);
if (final) zipComplete = true;
});
try {
const unzip = new Unzip((file) => {
const expected = index.get(file.name);
if (!expected || seen.has(file.name)) throw new Error("Excel-ZIP-Inhaltsverzeichnis stimmt nicht mit den Paketdaten überein.");
seen.add(file.name);
const output = new ZipDeflate(file.name, { level: 4 });
zip.add(output);
let crc = 0xffffffff, size = 0;
let fragments: string[] = [], length = 0;
const flush = () => {
if (!length) return;
output.push(Buffer.from(fragments.join(""), "utf8"));
fragments = []; length = 0;
};
const xml = /\.(xml|rels)$/i.test(file.name) ? xmlRestorer(matcher, (value) => {
fragments.push(value); length += value.length;
if (length >= 64 * 1024) flush();
}, file.name === "xl/workbook.xml") : undefined;
let decoder: TextDecoder | undefined, header = Buffer.alloc(0);
const decode = (data: Uint8Array, final: boolean) => {
if (!decoder) {
header = Buffer.concat([header, data]);
if (header.length < 4 && !final) return;
const encoding = header[0] === 0xff && header[1] === 0xfe || header[0] === 0x3c && header[1] === 0 ? "utf-16le"
: header[0] === 0xfe && header[1] === 0xff || header[0] === 0 && header[1] === 0x3c ? "utf-16be" : "utf-8";
decoder = new TextDecoder(encoding, { fatal: true });
data = header; header = Buffer.alloc(0);
}
xml!.push(decoder.decode(data, { stream: !final }));
};
file.ondata = (error, data, final) => {
if (error) throw error;
size += data.length;
if (size > expected.size) throw new Error("Excel-Paketbestandteil überschreitet seine angegebene Größe.");
crc = crcUpdate(crc, data);
for (let offset = 0; offset < data.length; offset += 64 * 1024) {
const part = data.subarray(offset, offset + 64 * 1024);
if (xml) decode(part, false); else output.push(part);
}
processed += data.length;
const percent = Math.floor(processed * 100 / Math.max(total, 1));
if (percent !== progress) { progress = percent; onProgress(percent); }
if (final) {
if (size !== expected.size || ((crc ^ 0xffffffff) >>> 0) !== expected.crc) throw new Error("Excel-Paketbestandteil ist beschädigt (Größe/CRC).");
if (xml) { decode(EMPTY, true); replacements += xml.end(); flush(); }
output.push(EMPTY, true);
finished.add(file.name);
}
};
file.start();
});
unzip.register(UnzipInflate);
for await (const data of createReadStream(source, { highWaterMark: 16 * 1024 })) unzip.push(data, false);
unzip.push(EMPTY, true);
if (finished.size !== index.size) throw new Error("Excel-ZIP-Archiv ist unvollständig.");
zip.end();
if (!zipComplete) throw new Error("Excel-Ausgabedatei wurde nicht vollständig geschrieben.");
const after = await fs.stat(source);
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error("Excel-Datei wurde während der Wiederherstellung geändert.");
complete = true;
return { replacements };
} finally {
zip.terminate();
closeSync(descriptor);
if (!complete) await fs.rm(target, { force: true });
}
}
/** Compatibility for callers already holding an Office document in memory. */
export async function restoreXlsxBuffer(data: Buffer, mapping: PlaceholderMapping): Promise<Buffer> {
const directory = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-"));
try {
const source = join(directory, "source.xlsx"), target = join(directory, "restored.xlsx");
await fs.writeFile(source, data, { mode: 0o600 });
await restoreXlsxFile(source, target, mapping);
return await fs.readFile(target);
} finally { await fs.rm(directory, { recursive: true, force: true }); }
}