- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/text.ts?version=293&format=json
491 linesFirst import 75% · codex-capacity-chair 25% · pinch 1%Last change codex-capacity-chair in version 175, 3 versions changed it
You're reading version 293. The newest is 318, and no version since then changed this file.
1// Text helpers: line endings, splitting, and a line diff (a longest common
2// subsequence, found with Myers' O(ND) algorithm in linear space).
4/** Normalize line endings to "\n". */
5export function normalizeText(text: string): string {
6 return text.replace(/\r\n?/g, "\n");
7}
9/** Split normalized text into lines. "" -> []; a trailing "\n" ends the last line. */
10export function splitLines(text: string): string[] {
11 if (text === "") return [];
12 const body = text.endsWith("\n") ? text.slice(0, -1) : text;
13 return body.split("\n");
14}
16/** Join lines into file text. A non-empty file always ends with "\n". */
17export function joinLines(lines: readonly string[]): string {
18 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
19}
21/** Normalize, then make a non-empty text end with "\n" (how files are projected). */
22export function canonicalText(text: string): string {
23 return joinLines(splitLines(normalizeText(text)));
24}
26/**
27 * One hunk of a line diff: old lines [start, end) become `lines`.
28 * start === end is a pure insertion before old line `start`.
29 */
30export interface Hunk {
31 readonly start: number;
32 readonly end: number;
33 readonly lines: readonly string[];
34}
36/**
37 * Line diff of `a` (old) against `b` (new), as hunks in order. The unchanged
38 * lines are a longest common subsequence, so every hunk is as small as it can
39 * be, up to a cost: where one stretch needs more than about MAX_COST edits (a
40 * file reordered or rewritten through), the search stops there and goes on
41 * from the furthest point it reached, as git's xdiff does (abso issue 158).
42 * The diff is then close to minimal rather than minimal, and costs about the
43 * file's length times MAX_COST instead of its length squared.
44 */
45export function diffLines(a: readonly string[], b: readonly string[]): Hunk[] {
46 return hunksFromMatches(a.length, b, commonLines(a, b));
47}
49/** Diff a single-pass old-line source without retaining its strings. */
50export function diffLineStream(a: Iterable<string>, b: readonly string[]): Hunk[] {
51 const ids = new Map<string, number>();
52 const next = b.map((line) => {
53 let id = ids.get(line);
54 if (id === undefined) {
55 id = ids.size;
56 ids.set(line, id);
57 }
58 return id;
59 });
60 const previous: number[] = [];
61 for (const line of a) previous.push(ids.get(line) ?? -1);
62 return hunksFromMatches(previous.length, b, commonLines(previous, next));
63}
65/** Compare replayable old-line chunks without assembling historical strings. */
66export function diffChunkedLines(a: Iterable<() => Iterable<string>>, b: readonly string[]): Hunk[] {
67 const keys = new Map<string, number>();
68 const buckets = new Map<string, number[]>();
69 const next = b.map((line, index) => {
70 let id = keys.get(line);
71 if (id === undefined) {
72 id = index;
73 keys.set(line, id);
74 const key = chunkKey([line]);
75 const bucket = buckets.get(key) ?? [];
76 bucket.push(id);
77 buckets.set(key, bucket);
78 }
79 return id;
80 });
81 const previous: number[] = [];
82 for (const chunks of a) {
83 const iterator = chunks()[Symbol.iterator]();
84 let key: string;
85 const aligned = b[previous.length];
86 let alignedOffset = 0;
87 let alignedEqual = aligned !== undefined;
88 try {
89 const first = iterator.next();
90 if (first.done) {
91 previous.push(keys.get("") ?? -1);
92 continue;
93 }
94 const second = iterator.next();
95 if (second.done) {
96 previous.push(keys.get(first.value) ?? -1);
97 continue;
98 }
99 key = chunkKey(
100 (function* () {
101 function* remaining() {
102 yield first.value;
103 yield second.value;
104 for (let next = iterator.next(); !next.done; next = iterator.next()) yield next.value;
105 }
106 for (const chunk of remaining()) {
107 if (alignedEqual && !aligned!.startsWith(chunk, alignedOffset)) alignedEqual = false;
108 alignedOffset += chunk.length;
109 yield chunk;
110 }
111 })(),
112 );
113 } finally {
114 iterator.return?.();
115 }
116 // Same-position unchanged lines are common. Confirm them during hashing,
117 // retaining exact comparison and the collision-safe fallback for moved lines.
118 if (alignedEqual && alignedOffset === aligned!.length) {
119 previous.push(next[previous.length]!);
120 continue;
121 }
122 const candidates = buckets.get(key);
123 let match = -1;
124 for (const candidate of candidates ?? []) {
125 let offset = 0;
126 let equal = true;
127 for (const chunk of chunks()) {
128 if (!b[candidate]!.startsWith(chunk, offset)) equal = false;
129 offset += chunk.length;
130 }
131 if (equal && offset === b[candidate]!.length) {
132 match = candidate;
133 break;
134 }
135 }
136 previous.push(match);
137 }
138 return hunksFromMatches(previous.length, b, commonLines(previous, next));
139}
141function chunkKey(chunks: Iterable<string>): string {
142 let hash = 2166136261;
143 let length = 0;
144 for (const chunk of chunks) {
145 length += chunk.length;
146 for (let i = 0; i < chunk.length; i++) hash = Math.imul(hash ^ chunk.charCodeAt(i), 16777619) >>> 0;
147 }
148 return `${length}:${hash}`;
149}
151/** The existing diff algorithm over exact line symbols, without retaining text. */
152export function diffLineSymbols(
153 a: readonly number[],
154 b: readonly number[],
155): { start: number; end: number; lines: number[] }[] {
156 return hunksFromMatches(a.length, b, commonLines(a, b));
157}
159function hunksFromMatches<T>(
160 length: number,
161 b: readonly T[],
162 matches: readonly number[],
163): { start: number; end: number; lines: T[] }[] {
164 const hunks: { start: number; end: number; lines: T[] }[] = [];
165 let i = 0;
166 let j = 0;
167 for (let m = 0; m <= matches.length; m += 2) {
168 const mi = m < matches.length ? matches[m]! : length;
169 const mj = m < matches.length ? matches[m + 1]! : b.length;
170 if (mi > i || mj > j) hunks.push({ start: i, end: mi, lines: b.slice(j, mj) });
171 i = mi + 1;
172 j = mj + 1;
173 }
174 return hunks;
175}
177/**
178 * The matched pairs of a longest common subsequence of `a` and `b`, flattened
179 * as [i0, j0, i1, j1, ...] in increasing order.
180 */
181function commonLines<T>(a: readonly T[], b: readonly T[]): number[] {
182 // Common prefix and suffix match directly.
183 let pre = 0;
184 while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
185 let suf = 0;
186 while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
187 const out: number[] = [];
188 for (let k = 0; k < pre; k++) out.push(k, k);
190 // A line that occurs on only one side can never be matched; leave it out of
191 // the search (this also makes wholly different texts instant).
192 const ids = new Map<T, number>();
193 const intern = (s: T): number => {
194 let id = ids.get(s);
195 if (id === undefined) {
196 id = ids.size;
197 ids.set(s, id);
198 }
199 return id;
200 };
201 const inA = new Set<number>();
202 const inB = new Set<number>();
203 const aIds: number[] = [];
204 const bIds: number[] = [];
205 for (let i = pre; i < a.length - suf; i++) inA.add((aIds[i - pre] = intern(a[i]!)));
206 for (let j = pre; j < b.length - suf; j++) inB.add((bIds[j - pre] = intern(b[j]!)));
207 const aPos: number[] = [];
208 const bPos: number[] = [];
209 const x: number[] = [];
210 const y: number[] = [];
211 aIds.forEach((id, i) => {
212 if (inB.has(id)) {
213 aPos.push(pre + i);
214 x.push(id);
215 }
216 });
217 bIds.forEach((id, j) => {
218 if (inA.has(id)) {
219 bPos.push(pre + j);
220 y.push(id);
221 }
222 });
223 const pairs: number[] = [];
224 myers(Int32Array.from(x), Int32Array.from(y), 0, x.length, 0, y.length, pairs);
225 for (let k = 0; k < pairs.length; k += 2) out.push(aPos[pairs[k]!]!, bPos[pairs[k + 1]!]!);
227 for (let k = suf; k > 0; k--) out.push(a.length - k, b.length - k);
228 return out;
229}
231/** About how many edits one stretch of a diff searches before settling for close to minimal (git's XDL_MAX_COST_MIN). */
232export const MAX_COST = 256;
234/**
235 * Myers' linear-space diff on a[aLo, aHi) and b[bLo, bHi): pushes the pairs
236 * of a longest common subsequence, in order, onto `out`. Each step splits the
237 * problem at a point on an optimal edit path and recurses on both halves.
238 */
239function myers(a: Int32Array, b: Int32Array, aLo: number, aHi: number, bLo: number, bHi: number, out: number[]): void {
240 while (aLo < aHi && bLo < bHi && a[aLo] === b[bLo]) out.push(aLo++, bLo++);
241 let suf = 0;
242 while (aLo < aHi - suf && bLo < bHi - suf && a[aHi - 1 - suf] === b[bHi - 1 - suf]) suf++;
243 const n = aHi - suf - aLo;
244 const m = bHi - suf - bLo;
245 if (n > 0 && m > 0) {
246 const split = bisect(a, aLo, n, b, bLo, m, Math.max(MAX_COST, Math.ceil(Math.sqrt(n + m))));
247 if (split) {
248 myers(a, b, aLo, aLo + split[0], bLo, bLo + split[1], out);
249 myers(a, b, aLo + split[0], aHi - suf, bLo + split[1], bHi - suf, out);
250 }
251 }
252 for (let k = suf; k > 0; k--) out.push(aHi - k, bHi - k);
253}
255/**
256 * Where the furthest-reaching forward and backward paths of a shortest edit
257 * script between a[aLo, aLo+n) and b[bLo, bLo+m) meet: a point [x, y] on an
258 * optimal path, relative to aLo and bLo. Both inputs are non-empty and differ
259 * in their first and last elements, so the point is neither corner and both
260 * halves are strictly smaller. Diagonals that run off the edit grid are
261 * dropped from the search (as in diff-match-patch's diff_bisect). Past `cap`
262 * edits it stops and answers the furthest point a forward path reached, which
263 * is on a path of that many edits from the start, so the first half stays
264 * exact; that point is never a corner, so both halves are still smaller.
265 */
266function bisect(
267 a: Int32Array,
268 aLo: number,
269 n: number,
270 b: Int32Array,
271 bLo: number,
272 m: number,
273 cap: number,
274): [number, number] | undefined {
275 const maxD = Math.ceil((n + m) / 2);
276 let bestX = -1;
277 let bestY = -1;
278 const offset = maxD;
279 const size = 2 * maxD + 2;
280 const v1 = new Int32Array(size).fill(-1);
281 const v2 = new Int32Array(size).fill(-1);
282 v1[offset + 1] = 0;
283 v2[offset + 1] = 0;
284 const delta = n - m;
285 const front = (delta & 1) !== 0;
286 let k1start = 0;
287 let k1end = 0;
288 let k2start = 0;
289 let k2end = 0;
290 for (let d = 0; d <= maxD; d++) {
291 for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
292 const i1 = offset + k1;
293 let x1 = k1 === -d || (k1 !== d && v1[i1 - 1]! < v1[i1 + 1]!) ? v1[i1 + 1]! : v1[i1 - 1]! + 1;
294 let y1 = x1 - k1;
295 while (x1 < n && y1 < m && a[aLo + x1] === b[bLo + y1]) {
296 x1++;
297 y1++;
298 }
299 v1[i1] = x1;
300 if (x1 <= n && y1 <= m && x1 + y1 > bestX + bestY && x1 + y1 < n + m) {
301 bestX = x1;
302 bestY = y1;
303 }
304 if (x1 > n) k1end += 2;
305 else if (y1 > m) k1start += 2;
306 else if (front) {
307 const i2 = offset + delta - k1;
308 if (i2 >= 0 && i2 < size && v2[i2] !== -1 && x1 >= n - v2[i2]!) return [x1, y1];
309 }
310 }
311 for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
312 const i2 = offset + k2;
313 let x2 = k2 === -d || (k2 !== d && v2[i2 - 1]! < v2[i2 + 1]!) ? v2[i2 + 1]! : v2[i2 - 1]! + 1;
314 let y2 = x2 - k2;
315 while (x2 < n && y2 < m && a[aLo + n - 1 - x2] === b[bLo + m - 1 - y2]) {
316 x2++;
317 y2++;
318 }
319 v2[i2] = x2;
320 if (x2 > n) k2end += 2;
321 else if (y2 > m) k2start += 2;
322 else if (!front) {
323 const i1 = offset + delta - k2;
324 if (i1 >= 0 && i1 < size && v1[i1] !== -1) {
325 const x1 = v1[i1]!;
326 if (x1 >= n - x2) return [x1, offset + x1 - i1];
327 }
328 }
329 }
330 if (d >= cap) {
331 if (bestX + bestY > 0) return [bestX, bestY];
332 const x = n >> 1;
333 const y = m >> 1;
334 return x + y > 0 && x + y < n + m ? [x, y] : [n, 0];
335 }
336 }
337 return undefined; // not reached: the paths meet by d = ceil((n + m) / 2)
338}
340/**
341 * Three-way merge of lines, the way git merges a file: `ours` and `theirs`
342 * both started from `base`. Changes on one side only are taken; changes both
343 * sides made identically are taken once; changes that overlap or touch and
344 * differ are a conflict (counted, with ours kept in `lines`), unless
345 * `resolve` settles it: given the base span and each side's text for it, it
346 * may return the merged text. `resolved` lists where each settled span
347 * starts in `lines`.
348 */
349export function mergeLines(
350 base: readonly string[],
351 ours: readonly string[],
352 theirs: readonly string[],
353 resolve?: (
354 base: readonly string[],
355 ours: readonly string[],
356 theirs: readonly string[],
357 at: number,
358 ) => string[] | undefined,
359 conflict?: (span: MergeConflict) => string[],
360): { lines: string[]; conflicts: number; resolved: number[]; conflictsAt: { at: number; length: number }[] } {
361 const resolved: number[] = [];
362 const conflictsAt: { at: number; length: number }[] = [];
363 // How far each side's line numbers have moved from the base's, by the hunks before the current span.
364 let oShift = 0;
365 let tShift = 0;
366 const oh = diffLines(base, ours);
367 const th = diffLines(base, theirs);
368 const out: string[] = [];
369 let conflicts = 0;
370 let pos = 0;
371 let i = 0;
372 let j = 0;
373 const apply = (group: readonly Hunk[], lo: number, hi: number): string[] => {
374 const result: string[] = [];
375 let p = lo;
376 for (const h of group) {
377 result.push(...base.slice(p, h.start), ...h.lines);
378 p = h.end;
379 }
380 result.push(...base.slice(p, hi));
381 return result;
382 };
383 while (i < oh.length || j < th.length) {
384 const first = j >= th.length || (i < oh.length && oh[i]!.start <= th[j]!.start) ? oh[i++]! : th[j++]!;
385 const groupO: Hunk[] = [];
386 const groupT: Hunk[] = [];
387 (oh.includes(first) ? groupO : groupT).push(first);
388 const lo = first.start;
389 let hi = first.end;
390 // Every hunk that overlaps or touches the span joins the group.
391 for (let grew = true; grew; ) {
392 grew = false;
393 while (i < oh.length && oh[i]!.start <= hi) {
394 groupO.push(oh[i]!);
395 hi = Math.max(hi, oh[i++]!.end);
396 grew = true;
397 }
398 while (j < th.length && th[j]!.start <= hi) {
399 groupT.push(th[j]!);
400 hi = Math.max(hi, th[j++]!.end);
401 grew = true;
402 }
403 }
404 out.push(...base.slice(pos, lo));
405 const o = apply(groupO, lo, hi);
406 const t = apply(groupT, lo, hi);
407 if (groupO.length === 0) out.push(...t);
408 else if (groupT.length === 0 || (o.length === t.length && o.every((l, k) => l === t[k]))) out.push(...o);
409 else {
410 const settled = resolve?.(base.slice(lo, hi), o, t, lo);
411 if (settled) {
412 resolved.push(out.length);
413 out.push(...settled);
414 } else {
415 conflicts++;
416 const shown = conflict
417 ? conflict({
418 base: base.slice(lo, hi),
419 ours: o,
420 theirs: t,
421 baseAt: lo,
422 oursAt: lo + oShift,
423 theirsAt: lo + tShift,
424 })
425 : o;
426 conflictsAt.push({ at: out.length, length: shown.length });
427 out.push(...shown);
428 }
429 }
430 oShift += o.length - (hi - lo);
431 tShift += t.length - (hi - lo);
432 pos = hi;
433 }
434 out.push(...base.slice(pos));
435 return { lines: out, conflicts, resolved, conflictsAt };
436}
438/** A span both sides changed differently: each side's text, and where it starts in base, ours and theirs (0-based). */
439export interface MergeConflict {
440 readonly base: readonly string[];
441 readonly ours: readonly string[];
442 readonly theirs: readonly string[];
443 readonly baseAt: number;
444 readonly oursAt: number;
445 readonly theirsAt: number;
446}
448/**
449 * Merge one line both sides changed, word by word (#37): `const SYSTEMS =
450 * [a, b, c]` with d added on one side and e on the other becomes
451 * `[a, b, c, e, d]`. Words and punctuation are merged like lines. Where both
452 * inserted different things at the same point, both are kept (theirs, then
453 * ours) only when each is a list item, beginning or ending with a comma, inside
454 * `[...]` or `{...}` in the base line; call arguments and anything else are no
455 * merge. Any other overlap is no merge either (undefined).
456 */
457export function mergeWords(base: string, ours: string, theirs: string): string | undefined {
458 const words = (s: string): string[] => s.match(/[A-Za-z0-9_$]+|\s+|[^A-Za-z0-9_$\s]/g) ?? [];
459 const b = words(base);
460 const OPEN = "([{";
461 const CLOSE = ")]}";
462 const listItem = (piece: readonly string[]): boolean => {
463 const solid = piece.filter((w) => w.trim() !== "");
464 if (solid.length < 2 || (solid[0] !== "," && solid[solid.length - 1] !== ",")) return false;
465 let depth = 0;
466 for (const w of solid) {
467 if (OPEN.includes(w)) depth++;
468 else if (CLOSE.includes(w) && --depth < 0) return false;
469 }
470 return depth === 0;
471 };
472 // The bracket the insertion point sits in, in the base line.
473 const enclosing = (at: number): string | undefined => {
474 let depth = 0;
475 for (let i = at - 1; i >= 0; i--) {
476 if (CLOSE.includes(b[i]!)) depth++;
477 else if (OPEN.includes(b[i]!)) {
478 if (depth === 0) return b[i];
479 depth--;
480 }
481 }
482 return undefined;
483 };
484 const m = mergeLines(b, words(ours), words(theirs), (span, o, t, at) => {
485 const bracket = enclosing(at);
486 return span.length === 0 && (bracket === "[" || bracket === "{") && listItem(o) && listItem(t)
487 ? [...t, ...o]
488 : undefined;
489 });
490 return m.conflicts > 0 ? undefined : m.lines.join("");
491}