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 { propagateDocxPersons } from "./person-propagation"; 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 { 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, 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."); const snippetStart = Math.max(0, begin - 60); hits.push({ ...span, start: begin, end, segment: segmentIndex, id: `${relative}:local-docx:${segmentIndex}:${begin}:${end}`, file: relative, source: segment.source, context: characters.slice(snippetStart, end + 60).join(""), contextOffset: characters.slice(snippetStart, begin).join("").length, 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(); const propagated = types.includes("PERSON") ? propagateDocxPersons(segments, hits, current, relative) : { hits, mapping: current }; return { ...propagated, segmentCount: segments.length }; } export async function writeDocx( assets: string, path: string, target: string, hash: string, policy: ImagePolicy, segmentCount: number, hits: Hit[], accepted: Set, ) { const replacements: Record = {}; 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 }); } }