| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- // 行级差异引擎:Myers diff + 左右对齐 + 行内字符级高亮。
- // 只依赖 Node 内置能力,不引入任何 npm 包。
- const EQ = 1;
- const DEL = 2;
- const INS = 3;
- export const ROW_SAME = "=";
- export const ROW_CHANGE = "~";
- export const ROW_LEFT_ONLY = "-";
- export const ROW_RIGHT_ONLY = "+";
- export function splitLines(text) {
- if (text === "") return [];
- const lines = text.split(/\r\n|\r|\n/);
- if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
- return lines;
- }
- // 一个超长单行文件(例如把整个类挤在一行的混淆源码)会退化成字符级比较,
- // 这里按固定宽度切断,既保留可读性又让 diff 有可对齐的单位。
- const LONG_LINE_LIMIT = 2000;
- const CHUNK_WIDTH = 160;
- export function splitLinesForDiff(text) {
- const raw = splitLines(text);
- let needsChunk = false;
- for (const line of raw) {
- if (line.length > LONG_LINE_LIMIT) {
- needsChunk = true;
- break;
- }
- }
- if (!needsChunk) return { lines: raw, chunked: false };
- const out = [];
- for (const line of raw) {
- if (line.length <= LONG_LINE_LIMIT) {
- out.push(line);
- continue;
- }
- for (let i = 0; i < line.length; i += CHUNK_WIDTH) {
- out.push(line.slice(i, i + CHUNK_WIDTH));
- }
- }
- return { lines: out, chunked: true };
- }
- function myersCore(a, b, maxD) {
- const n = a.length;
- const m = b.length;
- if (n === 0 && m === 0) return [];
- const max = Math.min(maxD, n + m);
- const size = 2 * max + 1;
- const v = new Int32Array(size);
- const traces = [];
- for (let d = 0; d <= max; d++) {
- traces.push(v.slice());
- for (let k = -d; k <= d; k += 2) {
- let x;
- if (k === -d || (k !== d && v[max + k - 1] < v[max + k + 1])) x = v[max + k + 1];
- else x = v[max + k - 1] + 1;
- let y = x - k;
- while (x < n && y < m && a[x] === b[y]) {
- x++;
- y++;
- }
- v[max + k] = x;
- if (x >= n && y >= m) return backtrack(traces, n, m, max);
- }
- }
- return null;
- }
- function backtrack(traces, n, m, max) {
- let x = n;
- let y = m;
- const ops = [];
- for (let d = traces.length - 1; d >= 0; d--) {
- const v = traces[d];
- const k = x - y;
- let prevK;
- if (k === -d || (k !== d && v[max + k - 1] < v[max + k + 1])) prevK = k + 1;
- else prevK = k - 1;
- const prevX = v[max + prevK];
- const prevY = prevX - prevK;
- while (x > prevX && y > prevY) {
- ops.push([EQ, x - 1, y - 1]);
- x--;
- y--;
- }
- if (d > 0) {
- if (x === prevX) {
- ops.push([INS, -1, y - 1]);
- y--;
- } else {
- ops.push([DEL, x - 1, -1]);
- x--;
- }
- }
- }
- ops.reverse();
- return ops;
- }
- function opsFor(a, b, maxD) {
- // 先削掉公共前缀/后缀,常见场景(文件里只有局部改动)能省掉绝大部分计算。
- let start = 0;
- while (start < a.length && start < b.length && a[start] === b[start]) start++;
- let endA = a.length;
- let endB = b.length;
- while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
- endA--;
- endB--;
- }
- const midA = a.slice(start, endA);
- const midB = b.slice(start, endB);
- const ops = myersCore(midA, midB, maxD);
- const head = [];
- for (let i = 0; i < start; i++) head.push([EQ, i, i]);
- if (ops === null) {
- // 差异过大:退化成“整块替换”,仍然保证左右行号正确。
- const block = [];
- for (let i = 0; i < midA.length; i++) block.push([DEL, start + i, -1]);
- for (let i = 0; i < midB.length; i++) block.push([INS, -1, start + i]);
- const tail = [];
- for (let i = 0; i < a.length - endA; i++) tail.push([EQ, endA + i, endB + i]);
- return { ops: head.concat(block, tail), collapsed: true };
- }
- const shifted = ops.map(([type, ai, bi]) => [
- type,
- ai < 0 ? -1 : ai + start,
- bi < 0 ? -1 : bi + start,
- ]);
- const tail = [];
- for (let i = 0; i < a.length - endA; i++) tail.push([EQ, endA + i, endB + i]);
- return { ops: head.concat(shifted, tail), collapsed: false };
- }
- /**
- * 生成左右对齐的行数组。
- * 返回 { rows, stats, collapsed, totalRows }
- * row: { type, leftNo, rightNo, left, right, inline? }
- */
- export function buildRows(leftText, rightText, options = {}) {
- const maxD = options.maxD ?? 900;
- const inline = options.inline !== false;
- const left = splitLinesForDiff(leftText ?? "");
- const right = splitLinesForDiff(rightText ?? "");
- const a = left.lines;
- const b = right.lines;
- const { ops, collapsed } = opsFor(a, b, maxD);
- const rows = [];
- const stats = { added: 0, removed: 0, changed: 0, unchanged: 0 };
- let i = 0;
- while (i < ops.length) {
- const op = ops[i];
- if (op[0] === EQ) {
- rows.push({
- type: ROW_SAME,
- leftNo: op[1] + 1,
- rightNo: op[2] + 1,
- left: a[op[1]],
- right: b[op[2]],
- });
- stats.unchanged++;
- i++;
- continue;
- }
- // 收集连续的删除/新增块,配对的算“修改”,落单的算纯增/纯删。
- const dels = [];
- const inss = [];
- while (i < ops.length && ops[i][0] !== EQ) {
- if (ops[i][0] === DEL) dels.push(ops[i][1]);
- else inss.push(ops[i][2]);
- i++;
- }
- const pairs = Math.min(dels.length, inss.length);
- for (let p = 0; p < pairs; p++) {
- const li = dels[p];
- const ri = inss[p];
- const row = {
- type: ROW_CHANGE,
- leftNo: li + 1,
- rightNo: ri + 1,
- left: a[li],
- right: b[ri],
- };
- if (inline) {
- const seg = inlineSegments(a[li], b[ri]);
- row.leftSeg = seg.left;
- row.rightSeg = seg.right;
- }
- rows.push(row);
- stats.changed++;
- }
- for (let p = pairs; p < dels.length; p++) {
- rows.push({
- type: ROW_LEFT_ONLY,
- leftNo: dels[p] + 1,
- rightNo: null,
- left: a[dels[p]],
- right: null,
- });
- stats.removed++;
- }
- for (let p = pairs; p < inss.length; p++) {
- rows.push({
- type: ROW_RIGHT_ONLY,
- leftNo: null,
- rightNo: inss[p] + 1,
- left: null,
- right: b[inss[p]],
- });
- stats.added++;
- }
- }
- return {
- rows,
- stats,
- collapsed,
- chunked: left.chunked || right.chunked,
- totalRows: rows.length,
- };
- }
- const TOKEN_RE = /[\p{L}\p{N}_$]+|\s+|./gu;
- const INLINE_TOKEN_LIMIT = 2200;
- function tokenize(line) {
- const out = [];
- const re = new RegExp(TOKEN_RE.source, TOKEN_RE.flags);
- let m;
- while ((m = re.exec(line)) !== null) {
- out.push(m[0]);
- if (out.length > INLINE_TOKEN_LIMIT) return null;
- }
- return out;
- }
- function commonPrefixSuffix(a, b) {
- let prefix = 0;
- const minLen = Math.min(a.length, b.length);
- while (prefix < minLen && a.charCodeAt(prefix) === b.charCodeAt(prefix)) prefix++;
- let suffix = 0;
- while (
- suffix < minLen - prefix &&
- a.charCodeAt(a.length - 1 - suffix) === b.charCodeAt(b.length - 1 - suffix)
- ) {
- suffix++;
- }
- return { prefix, suffix };
- }
- /**
- * 行内高亮:返回左右两边的片段数组 [{ t: 文本, c: 0 相同 / 1 差异 }]。
- * 同一行差异过大时退化为“公共前后缀 + 中间整体标红”,避免页面被碎片淹没。
- */
- export function inlineSegments(a, b) {
- if (a === b) {
- return { left: [{ t: a, c: 0 }], right: [{ t: b, c: 0 }] };
- }
- const ta = tokenize(a);
- const tb = tokenize(b);
- let pairs = null;
- if (ta && tb) {
- const ops = myersCore(ta, tb, 240);
- if (ops) {
- pairs = { ops, ta, tb };
- }
- }
- if (pairs) {
- const { ops, ta: la, tb: lb } = pairs;
- const left = [];
- const right = [];
- let sawDiff = false;
- for (const [type, ai, bi] of ops) {
- if (type === EQ) {
- pushSeg(left, la[ai], 0);
- pushSeg(right, lb[bi], 0);
- } else if (type === DEL) {
- pushSeg(left, la[ai], 1);
- sawDiff = true;
- } else {
- pushSeg(right, lb[bi], 1);
- sawDiff = true;
- }
- }
- if (sawDiff) return { left, right };
- }
- const { prefix, suffix } = commonPrefixSuffix(a, b);
- const leftMid = a.slice(prefix, a.length - suffix);
- const rightMid = b.slice(prefix, b.length - suffix);
- const left = [];
- const right = [];
- pushSeg(left, a.slice(0, prefix), 0);
- if (leftMid) pushSeg(left, leftMid, 1);
- pushSeg(left, a.slice(a.length - suffix), 0);
- pushSeg(right, b.slice(0, prefix), 0);
- if (rightMid) pushSeg(right, rightMid, 1);
- pushSeg(right, b.slice(b.length - suffix), 0);
- return { left, right };
- }
- function pushSeg(list, text, code) {
- if (!text) return;
- const last = list[list.length - 1];
- if (last && last.c === code) last.t += text;
- else list.push({ t: text, c: code });
- }
- /**
- * 只保留差异块及其上下文,用于“仅显示差异”。
- * rows 是 buildRows 的结果,返回新的 rows 子集;被省略的位置插入省略标记。
- */
- export function collapseRows(rows, context = 3) {
- const keep = new Array(rows.length).fill(false);
- for (let i = 0; i < rows.length; i++) {
- if (rows[i].type === ROW_SAME) continue;
- const from = Math.max(0, i - context);
- const to = Math.min(rows.length - 1, i + context);
- for (let j = from; j <= to; j++) keep[j] = true;
- }
- const out = [];
- let hidden = 0;
- for (let i = 0; i < rows.length; i++) {
- if (keep[i]) {
- if (hidden > 0) {
- out.push({ type: "gap", hidden });
- hidden = 0;
- }
- out.push(rows[i]);
- } else {
- hidden++;
- }
- }
- if (hidden > 0) out.push({ type: "gap", hidden });
- return out;
- }
|