Files
velum-raycast/tests/project-text-stream.test.ts
muena 11ddd6d70f 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.
2026-11-08 10:43:40 +01:00

125 lines
8.4 KiB
TypeScript

import { afterEach, expect, it } from "bun:test";
import { promises as fs } from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
import { decodedText, fileTextParts, hashProjectFile, inspectTextFile, textLines, writeReplacedTextFile } from "../src/lib/project-text-stream";
import type { PlaceholderMapping } from "../src/types";
const roots: string[] = [];
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
async function fixture() { const root = await fs.mkdtemp(join(tmpdir(), "velum-stream-")); roots.push(root); return root; }
it("trennt vollständige Zeilen und bewahrt CRLF, CR, LF und die letzte Zeile", async () => {
async function* chunks() { yield "eins\r"; yield "\nzwei\rdr"; yield "ei\n😀Ende"; }
const lines = [];
for await (const line of textLines(chunks())) lines.push(line);
expect(lines).toEqual(["eins\r\n", "zwei\r", "drei\n", "😀Ende"]);
});
it("erhält auch bei byteweisen Lesevorgängen BOM, Umlaute und Emoji", async () => {
const root = await fixture(); const source = join(root, "unicode.txt");
await fs.writeFile(source, "\uFEFFÄ😀\r\nEnde");
let text = "";
for await (const part of decodedText(source, undefined, 1)) text += part;
expect(text).toBe("\uFEFFÄ😀\r\nEnde");
});
it("schneidet weder eine Zeile noch ein Wort an der Paketgrenze durch", async () => {
const root = await fixture(); const source = join(root, "lines.txt");
const text = "\uFEFF" + "Lange Füllzeile mit 😀.\r\n".repeat(800) + "Max Mustermann\r\nletzte Zeile";
await fs.writeFile(source, text);
let rebuilt = ""; let count = 0;
for await (const part of fileTextParts(source)) {
const core = text.slice(part.coreStart, part.coreEnd);
expect(part.text.slice(part.coreStart - part.scanStart, part.coreEnd - part.scanStart)).toBe(core);
if (part.coreEnd < text.length) expect(core.endsWith("\n")).toBe(true);
expect(part.text.length).toBeLessThan(24_000);
rebuilt += core; count++;
}
expect(count).toBeGreaterThan(1); expect(rebuilt).toBe(text);
});
it("analysiert mehr als 20 MiB und fügt nur bestätigte Treffer verlustfrei zur Datei zusammen", async () => {
const root = await fixture(); const source = join(root, "large.txt"); const target = join(root, "masked.txt");
const first = "\uFEFF😀 Max Mustermann\r\n"; const last = "Anna Berger ohne abschließenden Umbruch";
const filler = "Text ohne Treffer.\r\n".repeat(26_214);
const expected = createHash("sha256").update("\uFEFF😀 PERSON_01\r\n");
const handle = await fs.open(source, "w");
await handle.writeFile(first);
for (let i = 0; i < 64; i++) { await handle.writeFile(filler); expected.update(filler); }
await handle.writeFile(last); expected.update(last); await handle.close();
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
const hash = await inspectTextFile(source);
let requests = 0, active = 0, maxActive = 0;
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {}, ["PERSON"], {}, async (text, previous) => {
requests++; active++; maxActive = Math.max(maxActive, active);
expect(text.length).toBeLessThanOrEqual(24_000);
await Promise.resolve();
const mapping: PlaceholderMapping = { ...previous };
const spans = [...text.matchAll(/Max Mustermann|Anna Berger/g)].map((match) => {
const placeholder = match[0] === "Max Mustermann" ? "PERSON_01" : "PERSON_02";
mapping[placeholder] = { original: match[0], type: "PERSON" };
const start = [...text.slice(0, match.index)].length;
return { start, end: start + match[0].length, original: match[0], placeholder, type: "PERSON", score: 1 };
});
active--;
return { pseudonymized_text: text, mapping, spans, entity_count: Object.keys(mapping).length, selected_entity_types: ["PERSON"] };
}, () => undefined);
const spans = result.spansByFile.get("large.txt")!.map((span, i) => ({ ...span, id: String(i) }));
expect(spans.map((span) => span.original)).toEqual(["Max Mustermann", "Anna Berger"]);
expect(spans[0].start).toBe(first.indexOf("Max"));
expect(spans[1].start).toBe(first.length + 64 * filler.length);
expect(Object.keys(result.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
const outputHash = await writeReplacedTextFile(source, target, spans, new Set(["0"]), hash);
expect(outputHash).toBe(expected.digest("hex"));
expect(await hashProjectFile(target)).toBe(outputHash);
expect(await hashProjectFile(source)).toBe(hash);
expect(requests).toBeGreaterThan(1000); expect(maxActive).toBe(1);
}, 30_000);
it("ersetzt einen Treffer über einer Lesegrenze und erhält unveränderte Bytes", async () => {
const root = await fixture(); const source = join(root, "cross.txt"); const target = join(root, "out.txt");
const text = "x".repeat(65_531) + "Max Mustermann 😀\r\nEnde";
await fs.writeFile(source, text);
await writeReplacedTextFile(source, target, [{ id: "hit", start: 65_531, end: 65_545, placeholder: "PERSON_01" }], new Set(["hit"]), await hashProjectFile(source));
expect(await fs.readFile(target, "utf8")).toBe("x".repeat(65_531) + "PERSON_01 😀\r\nEnde");
});
it("hält Zuordnungen und Offsets über viele Dateien hinweg getrennt", async () => {
const root = await fixture(); const files = [];
for (let i = 0; i < 100; i++) { const path = join(root, `${i}.txt`); await fs.writeFile(path, "😀 Anna\r\n"); files.push({ key: String(i), path }); }
let requests = 0;
const result = await analyzeProjectTextFiles(files, {}, ["PERSON"], {}, async (text, mapping) => {
requests++;
return { pseudonymized_text: text, mapping: { ...mapping, PERSON_01: { original: "Anna", type: "PERSON" } }, selected_entity_types: ["PERSON"], entity_count: 1,
spans: [...text.matchAll(/Anna/g)].map((match) => ({ start: [...text.slice(0, match.index)].length, end: [...text.slice(0, match.index)].length + 4, original: "Anna", type: "PERSON", score: 1, placeholder: "PERSON_01" })) };
}, () => undefined);
expect(requests).toBe(1); expect(result.spansByFile.size).toBe(100);
for (const spans of result.spansByFile.values()) { expect(spans).toHaveLength(1); expect(spans[0].start).toBe(3); }
});
it("bricht überlange Zeilen ab und entfernt bei Quelländerungen die unvollständige Ausgabe", async () => {
const root = await fixture(); const source = join(root, "long.txt"); const target = join(root, "partial.txt");
await fs.writeFile(source, "x".repeat(20_001));
await expect(analyzeProjectTextFiles([{ key: "long.txt", path: source }], {}, [], {}, async () => { throw Error("should not call"); }, () => undefined)).rejects.toThrow("Zeile 1");
await expect(writeReplacedTextFile(source, target, [], new Set(), "old-hash")).rejects.toThrow("geändert");
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
expect((await fs.stat(source)).size).toBe(20_001);
});
it("verwirft Binärdaten und unvollständiges UTF-8 ohne fertige Ausgabedatei", async () => {
const root = await fixture();
for (const data of [Buffer.from([65, 0, 66]), Buffer.from([65, 0xc3])]) {
const source = join(root, "invalid.txt"); const target = join(root, "partial.txt"); await fs.writeFile(source, data);
await expect(inspectTextFile(source)).rejects.toThrow();
await expect(writeReplacedTextFile(source, target, [], new Set(), await hashProjectFile(source))).rejects.toThrow();
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
}
});
it("erkennt einen Namen auch über zwei Zeilen und eine Paketgrenze hinweg genau einmal", async () => {
const root = await fixture(); const path = join(root, "boundary.txt");
const prefix = "x\n".repeat(4997);
await fs.writeFile(path, prefix + "Max\r\nMustermann\r\nEnde");
const result = await analyzeProjectTextFiles([{ key: "boundary.txt", path }], {}, ["PERSON"], {}, async (text, mapping) => {
const spans = [...text.matchAll(/Max\r\nMustermann/g)].map((match) => ({ start: match.index, end: match.index + match[0].length,
original: match[0], placeholder: "PERSON_01", type: "PERSON", score: 1 }));
return { pseudonymized_text: text, mapping, spans, entity_count: spans.length, selected_entity_types: ["PERSON"] };
}, () => undefined);
expect(result.spansByFile.get("boundary.txt")!.map((span) => [span.start, span.end])).toEqual([[prefix.length, prefix.length + 15]]);
});