示例工程 61-chat-ui-streaming
61-chat-ui-streaming/demo-02-diff-lines/diff.ts
type DiffLine = { kind: "add" | "del" | "ctx"; text: string };
const UNIFIED = [
" export const mode = 'dev';",
"-export const retries = 1;",
"+export const retries = 3;",
"+export const timeoutMs = 5000;",
];
function classify(line: string): DiffLine {
if (line.startsWith("+"))
return { kind: "add", text: line.slice(1).trimStart() };
if (line.startsWith("-"))
return { kind: "del", text: line.slice(1).trimStart() };
if (line.startsWith(" "))
return { kind: "ctx", text: line.slice(1).trimStart() };
throw new Error(`BAD_DIFF_LINE:${line.slice(0, 12)}`);
}
function parse(lines: string[]): {
lines: DiffLine[];
add: number;
del: number;
ctx: number;
} {
const parsed = lines.map(classify);
return {
lines: parsed,
add: parsed.filter((line) => line.kind === "add").length,
del: parsed.filter((line) => line.kind === "del").length,
ctx: parsed.filter((line) => line.kind === "ctx").length,
};
}
const diff = parse(UNIFIED);
let bad = "";
try {
parse(["*** not a diff"]);
} catch (error) {
bad = error instanceof Error ? error.message : String(error);
}
const ok =
diff.add === 2 &&
diff.del === 1 &&
diff.ctx === 1 &&
diff.lines.length === 4 &&
diff.lines[0]?.kind === "ctx" &&
diff.lines[1]?.kind === "del" &&
bad === "BAD_DIFF_LINE:*** not a di";
console.log(JSON.stringify({ evt: "smoke", ok, diff, bad }));
export {};