forked from r.muellner/velum-raycast
feat: add custom terms and consolidate session management
Show exact matches in red and add categorized custom terms to hit review. Move session administration into the translation tables command.
This commit is contained in:
@@ -90,9 +90,11 @@ export async function inspectDocx(
|
||||
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(Math.max(0, begin - 60), end + 60).join(""), kind: "content" });
|
||||
context: characters.slice(snippetStart, end + 60).join(""),
|
||||
contextOffset: characters.slice(snippetStart, begin).join("").length, kind: "content" });
|
||||
}
|
||||
start += characters.length + 2;
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ export async function analyzeProjectTexts(
|
||||
return { mapping: current, spansByFile };
|
||||
}
|
||||
|
||||
export type StreamTextSpan = TextSpan & { context: string };
|
||||
export type StreamTextSpan = TextSpan & { context: string; contextOffset: number };
|
||||
|
||||
/** Analyze complete-line parts lazily, sharing small requests across file boundaries. */
|
||||
export async function analyzeProjectTextFiles(
|
||||
@@ -290,8 +290,9 @@ export async function analyzeProjectTextFiles(
|
||||
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 });
|
||||
const snippetStart = Math.max(0, positions[span.start] - 70);
|
||||
const context = Buffer.from(part.text.slice(snippetStart, positions[span.end] + 70), "utf8").toString("utf8");
|
||||
spansByFile.get(part.file)!.push({ ...span, start, end, context, contextOffset: positions[span.start] - snippetStart });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +129,34 @@ export function literalReviewContext(text: string): string {
|
||||
return `${fence}\n${text}\n${fence}`;
|
||||
}
|
||||
|
||||
function escapeReviewMarkdown(text: string): string {
|
||||
return text.replace(/[^\p{L}\p{M}\p{N} \r\n]/gu, (character) => `&#${character.codePointAt(0)};`)
|
||||
.replace(/ {2,}/g, (spaces) => " " + " ".repeat(spaces.length - 1))
|
||||
.replace(/\r\n?|\n/g, " \n");
|
||||
}
|
||||
|
||||
const latexTextEscapes: Record<string, string> = {
|
||||
"\\": "\\textbackslash{}", "~": "\\textasciitilde{}", "^": "\\textasciicircum{}",
|
||||
"{": "\\{", "}": "\\}", "%": "\\%", "$": "\\$", "&": "\\&", "#": "\\#", "_": "\\_",
|
||||
"-": "{-}", " ": "\\ ", "\t": "\\ \\ \\ \\ ",
|
||||
"'": "\\texttt{'}", "`": "\\texttt{`}",
|
||||
};
|
||||
|
||||
/** Raycast renders inline LaTeX with color support in its Markdown detail views. */
|
||||
export function highlightedReviewContext(text: string, start: number, length: number): string {
|
||||
const end = start + length;
|
||||
if (!Number.isInteger(start) || !Number.isInteger(length) || start < 0 || length <= 0 || end > text.length) {
|
||||
return literalReviewContext(text);
|
||||
}
|
||||
const before = escapeReviewMarkdown(text.slice(0, start));
|
||||
const match = text.slice(start, end).split(/\r\n?|\n/).map((line) => {
|
||||
if (!line) return "";
|
||||
const literal = line.replace(/[\\~^{}%$&#_ \t'`-]/g, (character) => latexTextEscapes[character]);
|
||||
return String.raw`\(\textcolor{#dc2626}{\text{${literal}}}\)`;
|
||||
}).join(" \n");
|
||||
return before + match + escapeReviewMarkdown(text.slice(end));
|
||||
}
|
||||
|
||||
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
|
||||
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
|
||||
const characters = Array.from(text);
|
||||
@@ -147,7 +175,7 @@ export function textHitContexts(text: string, spans: Array<{ start: number; end:
|
||||
const before = characters.slice(Math.max(0, start - 90), start).join("");
|
||||
const match = characters.slice(start, end).join("");
|
||||
const after = characters.slice(end, end + 90).join("");
|
||||
contexts[index] = `**Zeile ${line}**\n\n${literalReviewContext(`${before}⟦${match}⟧${after}`)}`;
|
||||
contexts[index] = `**Zeile ${line}**\n\n${highlightedReviewContext(before + match + after, before.length, match.length)}`;
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ export async function reviseProjectRun(args: {
|
||||
run.origin = previous.origin;
|
||||
run.revisedFrom = previous.id;
|
||||
run.entityTypes = previous.entityTypes ? [...previous.entityTypes] : undefined;
|
||||
run.customTermCoverage = previous.customTermCoverage;
|
||||
run.commentAuthorCoverage = previous.commentAuthorCoverage;
|
||||
run.reviewAuthorCoverage = previous.reviewAuthorCoverage;
|
||||
run.mapping = plan.mapping;
|
||||
|
||||
@@ -23,14 +23,14 @@ 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;
|
||||
kind: "content" | "path"; segment?: number; contextOffset?: 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 };
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy; customTermCoverage?: string };
|
||||
|
||||
function isLocalDocx(file: ProjectFile): boolean {
|
||||
return file.kind === "document" && extname(file.relPath).toLowerCase() === ".docx";
|
||||
@@ -44,6 +44,7 @@ function isUnreadableDocument(error: unknown): boolean {
|
||||
|
||||
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||
contextOffset: Array.from(hit.context).slice(0, Math.min(60, hit.start)).join("").length,
|
||||
file: file.relPath, kind: "content" as const }));
|
||||
}
|
||||
|
||||
@@ -69,6 +70,8 @@ export async function prepareProject(assets: string, root: string, files: Projec
|
||||
const latestEntry = (await listRuns(root))[0];
|
||||
const latest = latestEntry?.run;
|
||||
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
|
||||
const customTermCoverage = rules.length ? digest(Buffer.from(JSON.stringify(rules))) : undefined;
|
||||
const customTermsChanged = latest?.customTermCoverage !== customTermCoverage;
|
||||
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
|
||||
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
|
||||
const previousPlaceholders = Object.keys(previousMapping);
|
||||
@@ -89,7 +92,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
|
||||
continue;
|
||||
}
|
||||
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
|
||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
|
||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && !customTermsChanged && 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)) {
|
||||
@@ -177,7 +180,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
|
||||
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,
|
||||
context: path.value, contextOffset: span.start,
|
||||
}));
|
||||
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
for (const hit of path.hits) hits.push(hit);
|
||||
@@ -185,7 +188,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
|
||||
}
|
||||
}
|
||||
return { drafts, retained, paths, mapping, previousMapping, baseRunId: latest?.id,
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy, customTermCoverage };
|
||||
}
|
||||
|
||||
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||
@@ -236,6 +239,7 @@ export async function applyProject(
|
||||
run.mapping = mappingForSelection(preview.mapping, preview.previousMapping,
|
||||
acceptedHits, activeMerges);
|
||||
run.entityTypes = [...preview.entityTypes];
|
||||
run.customTermCoverage = preview.customTermCoverage;
|
||||
run.imagePolicy = preview.imagePolicy;
|
||||
run.sourceState = {};
|
||||
run.commentAuthorCoverage = preview.entityTypes.includes("PERSON");
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 type { CustomTerm, EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||
import { whitelistKey } from "./project-whitelist";
|
||||
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
||||
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
@@ -13,7 +13,7 @@ import { mappingForRestoration } from "./mapping-groups";
|
||||
export { whitelistKey } from "./project-whitelist";
|
||||
export type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
|
||||
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
|
||||
export type ProjectRule = CustomTerm;
|
||||
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; localDocx?: true };
|
||||
@@ -27,6 +27,7 @@ export type ProjectRun = {
|
||||
mapping: PlaceholderMapping;
|
||||
/** Categories actually used to analyze the files in this snapshot. */
|
||||
entityTypes?: EntityType[];
|
||||
customTermCoverage?: string;
|
||||
/** 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. */
|
||||
@@ -204,18 +205,21 @@ export async function loadProjectRules(projectPath: string, support?: string): P
|
||||
function isProjectRule(value: unknown): value is ProjectRule {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const rule = value as Record<string, unknown>;
|
||||
return ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"].includes(String(rule.type))
|
||||
return typeof rule.type === "string" && /^[A-Z][A-Z0-9_]*$/.test(rule.type)
|
||||
&& typeof rule.value === "string" && rule.value.trim().length >= 2;
|
||||
}
|
||||
|
||||
export function parseProjectRules(input: string): ProjectRule[] {
|
||||
export function parseProjectRules(input: string,
|
||||
entityTypes: readonly string[] = ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"]): ProjectRule[] {
|
||||
const allowed = new Set(entityTypes);
|
||||
const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
|
||||
const match = /^(BEGRIFF|PERSON|ORG|ORT|FIRMA|KUNDE):\s*(.+)$/i.exec(line);
|
||||
return match
|
||||
? { type: match[1].toUpperCase() as ProjectRule["type"], value: match[2].trim() }
|
||||
const match = /^([A-Z][A-Z0-9_]*):\s*(.+)$/i.exec(line);
|
||||
const type = match?.[1].toUpperCase();
|
||||
return match && type && allowed.has(type)
|
||||
? { type, value: match[2].trim() }
|
||||
: { type: "BEGRIFF" as const, value: line };
|
||||
});
|
||||
if (rules.length > 500 || rules.some((rule) => rule.value.length < 2 || rule.value.length > 200)) {
|
||||
if (rules.length > 500 || rules.some((rule) => !validCustomTerm(rule.value))) {
|
||||
throw new Error("Maximal 500 Begriffe mit jeweils 2 bis 200 Zeichen sind erlaubt.");
|
||||
}
|
||||
return rules.filter((rule, index) => rules.findIndex(
|
||||
@@ -223,10 +227,21 @@ export function parseProjectRules(input: string): ProjectRule[] {
|
||||
) === index);
|
||||
}
|
||||
|
||||
export function validCustomTerm(value: string): boolean {
|
||||
const length = Array.from(value.trim()).length;
|
||||
return length >= 2 && length <= 200;
|
||||
}
|
||||
|
||||
export async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise<void> {
|
||||
const path = rulesPath(projectPath, support);
|
||||
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
await fs.writeFile(path, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
|
||||
const temp = `${path}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(temp, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
|
||||
await fs.rename(temp, path);
|
||||
} finally {
|
||||
await fs.rm(temp, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||
@@ -481,6 +496,7 @@ export async function updateProjectMapping(projectPath: string,
|
||||
run.revisedFrom = latest.run.id;
|
||||
run.mapping = mapping;
|
||||
run.entityTypes = latest.run.entityTypes ? [...latest.run.entityTypes] : undefined;
|
||||
run.customTermCoverage = latest.run.customTermCoverage;
|
||||
run.matchModes = { ...latest.run.matchModes };
|
||||
run.files = latest.run.files.map((file) => ({ ...file }));
|
||||
run.sourceState = latest.run.sourceState ? { ...latest.run.sourceState } : undefined;
|
||||
|
||||
Reference in New Issue
Block a user