@criogaid/pi-hashline-edit 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
package/src/core/hash.ts CHANGED
@@ -21,44 +21,73 @@
21
21
  */
22
22
 
23
23
  /** Crockford base32 alphabet (without I/L/O/U to avoid ambiguous characters). Exactly 32 characters. */
24
- const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
24
+ export const HASH_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25
25
 
26
26
  /**
27
27
  * FNV-1a 32-bit. Stable (same input always yields the same output), evenly
28
28
  * distributed, non-cryptographic. Uses `Math.imul` for correct 32-bit integer
29
29
  * multiplication under JS.
30
30
  */
31
- function fnv1a32(str: string): number {
32
- let h = 0x811c9dc5;
33
- for (let i = 0; i < str.length; i++) {
34
- h ^= str.charCodeAt(i);
35
- h = Math.imul(h, 0x01000193);
36
- }
37
- return h >>> 0;
31
+ function fnv1a32(str: string, seed = 0x811c9dc5): number {
32
+ let h = seed;
33
+ for (let i = 0; i < str.length; i++) {
34
+ h ^= str.charCodeAt(i);
35
+ h = Math.imul(h, 0x01000193);
36
+ }
37
+ return h >>> 0;
38
38
  }
39
39
 
40
- /** Encode a 32-bit integer into a base32 string of the given length. */
40
+ /**
41
+ * Compute the FNV-1a 32-bit hash of `${line}\n${content}` without allocating
42
+ * the intermediate template string.
43
+ */
44
+ function fnv1a32Line(line: number, content: string): number {
45
+ let h = 0x811c9dc5;
46
+ // Feed digit characters of the line number without String(line) allocation.
47
+ let n = line;
48
+ let divisor = 1;
49
+ while (divisor * 10 <= n) divisor *= 10;
50
+ while (divisor >= 1) {
51
+ h ^= (((n / divisor) | 0) % 10) + 48;
52
+ h = Math.imul(h, 0x01000193);
53
+ divisor = (divisor / 10) | 0;
54
+ }
55
+ h ^= 10;
56
+ h = Math.imul(h, 0x01000193);
57
+ return fnv1a32(content, h);
58
+ }
59
+
60
+ /**
61
+ * Encode a 32-bit integer into a base32 string of the given length.
62
+ *
63
+ * Seven characters expose all 32 bits; the leading character contains only
64
+ * two bits. An eighth character is a leading '0', adding no entropy.
65
+ */
41
66
  function toBase32(n: number, len: number): string {
42
- let s = "";
43
- for (let i = 0; i < len; i++) {
44
- s = BASE32[n & 31] + s;
45
- n = Math.floor(n / 32);
46
- }
47
- return s;
67
+ let encoded = "";
68
+ for (let i = 0; i < len; i++) {
69
+ encoded = HASH_ALPHABET[n & 31] + encoded;
70
+ n >>>= 5;
71
+ }
72
+ return encoded;
48
73
  }
49
74
 
75
+ /** Supported hash lengths: two characters minimum; eight is the widest useful encoding. */
76
+ export const HASH_LEN_MIN = 2;
77
+ export const HASH_LEN_MAX = 8;
78
+
50
79
  /**
51
80
  * Compute the hash of a single line from its 1-based line number and content.
52
81
  *
53
82
  * @param line 1-based line number
54
83
  * @param content the line's content (no line terminator)
55
- * @param len hash length (default 4, 20 bits ≈ 1M values)
84
+ * @param len caller-selected hash length
56
85
  */
57
- export function computeLineHash(line: number, content: string, len = 4): string {
58
- return toBase32(fnv1a32(`${line}\n${content}`), len);
86
+ export function computeLineHash(line: number, content: string, len: number): string {
87
+ return toBase32(fnv1a32Line(line, content), len);
59
88
  }
60
89
 
61
90
  /** Compute compact per-line checksums; callers must treat collisions as possible. */
62
- export function hashFileLines(lines: readonly string[], len = 4): string[] {
63
- return lines.map((content, i) => computeLineHash(i + 1, content, len));
91
+ export function hashFileLines(lines: readonly string[], len: number): string[] {
92
+ return lines.map((content, i) => computeLineHash(i + 1, content, len));
64
93
  }
@@ -1,44 +1,63 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { createLfTextView, normalizeLineEndings, splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
3
+ import {
4
+ createLfTextView,
5
+ normalizeLineEndings,
6
+ splitLines,
7
+ detectLineEnding,
8
+ hasFinalNewline,
9
+ } from "./lines.ts";
4
10
 
5
11
  test("splitLines edge cases", () => {
6
- assert.deepEqual(splitLines(""), []);
7
- assert.deepEqual(splitLines("a"), ["a"]);
8
- assert.deepEqual(splitLines("a\nb"), ["a", "b"]);
9
- assert.deepEqual(splitLines("a\nb\n"), ["a", "b"]);
10
- assert.deepEqual(splitLines("a\n\n"), ["a", ""]);
11
- assert.deepEqual(splitLines("\n"), [""]);
12
+ assert.deepEqual(splitLines(""), []);
13
+ assert.deepEqual(splitLines("a"), ["a"]);
14
+ assert.deepEqual(splitLines("a\nb"), ["a", "b"]);
15
+ assert.deepEqual(splitLines("a\nb\n"), ["a", "b"]);
16
+ assert.deepEqual(splitLines("a\n\n"), ["a", ""]);
17
+ assert.deepEqual(splitLines("\n"), [""]);
12
18
  });
13
19
 
14
20
  test("splitLines strips CRLF \\r", () => {
15
- assert.deepEqual(splitLines("a\r\nb\r\n"), ["a", "b"]);
16
- assert.deepEqual(splitLines("a\r\nb"), ["a", "b"]);
21
+ assert.deepEqual(splitLines("a\r\nb\r\n"), ["a", "b"]);
22
+ assert.deepEqual(splitLines("a\r\nb"), ["a", "b"]);
23
+ });
24
+
25
+ test("splitLines handles mixed line endings and standalone CR correctly", () => {
26
+ assert.deepEqual(splitLines("a\r\nb\nc\r\n"), ["a", "b", "c"]);
27
+ assert.deepEqual(splitLines("a\rb\r\n"), ["a\rb"]);
28
+ assert.deepEqual(splitLines("a\rb\nc"), ["a\rb", "c"]);
29
+ assert.deepEqual(splitLines("\r\n"), [""]);
30
+ assert.deepEqual(splitLines("\r\n\r\n"), ["", ""]);
31
+ assert.deepEqual(splitLines("a\r\n\r\nb"), ["a", "", "b"]);
32
+ assert.deepEqual(splitLines("a\r\n\r\n"), ["a", ""]);
17
33
  });
18
34
 
19
35
  test("hasFinalNewline", () => {
20
- assert.equal(hasFinalNewline("a\nb"), false);
21
- assert.equal(hasFinalNewline("a\nb\n"), true);
22
- assert.equal(hasFinalNewline("a\r\nb"), false);
23
- assert.equal(hasFinalNewline("a\r\nb\r\n"), true);
24
- assert.equal(hasFinalNewline("a"), false);
25
- // no lines, no terminator — rejoining [] yields "" either way
26
- assert.equal(hasFinalNewline(""), true);
36
+ assert.equal(hasFinalNewline("a\nb"), false);
37
+ assert.equal(hasFinalNewline("a\nb\n"), true);
38
+ assert.equal(hasFinalNewline("a\r\nb"), false);
39
+ assert.equal(hasFinalNewline("a\r\nb\r\n"), true);
40
+ assert.equal(hasFinalNewline("a"), false);
41
+ // no lines, no terminator — rejoining [] yields "" either way
42
+ assert.equal(hasFinalNewline(""), true);
27
43
  });
28
44
 
29
45
  test("detectLineEnding", () => {
30
- assert.equal(detectLineEnding("a\nb\n"), "lf");
31
- assert.equal(detectLineEnding("a\r\nb\r\n"), "crlf");
32
- assert.equal(detectLineEnding("a\nb\r\nc\n"), "crlf");
46
+ assert.equal(detectLineEnding("a\nb\n"), "lf");
47
+ assert.equal(detectLineEnding("a\r\nb\r\n"), "crlf");
48
+ assert.equal(detectLineEnding("a\nb\r\nc\n"), "crlf");
33
49
  });
34
50
 
35
51
  test("LF views map every UTF-16 boundary back to original CRLF bytes", () => {
36
- for (const source of ["", "a\nb", "\uFEFF😀\r\nb\nc\r\n", "\r\n\r\n", "a\rb\r\r\nc"]) {
37
- const view = createLfTextView(source);
38
- assert.equal(view.text, normalizeLineEndings(source));
39
- assert.equal(view.sourceOffset(view.text.length), source.length);
40
- for (let offset = 0; offset <= view.text.length; offset++) {
41
- assert.equal(normalizeLineEndings(source.slice(0, view.sourceOffset(offset))), view.text.slice(0, offset));
42
- }
43
- }
52
+ for (const source of ["", "a\nb", "\uFEFF😀\r\nb\nc\r\n", "\r\n\r\n", "a\rb\r\r\nc"]) {
53
+ const view = createLfTextView(source);
54
+ assert.equal(view.text, normalizeLineEndings(source));
55
+ assert.equal(view.sourceOffset(view.text.length), source.length);
56
+ for (let offset = 0; offset <= view.text.length; offset++) {
57
+ assert.equal(
58
+ normalizeLineEndings(source.slice(0, view.sourceOffset(offset))),
59
+ view.text.slice(0, offset),
60
+ );
61
+ }
62
+ }
44
63
  });
package/src/core/lines.ts CHANGED
@@ -20,44 +20,48 @@ import type { LineEnding } from "./types.ts";
20
20
 
21
21
  /** Normalize CRLF boundaries to LF; standalone CR remains content. */
22
22
  export function normalizeLineEndings(text: string): string {
23
- return text.replace(/\r\n/g, "\n");
23
+ return text.replace(/\r\n/g, "\n");
24
24
  }
25
25
 
26
26
  /** Raw separators in logical-line order, shared by both mutation applicators. */
27
27
  export function lineSeparators(text: string): string[] {
28
- return text.match(/\r?\n/g) ?? [];
28
+ return text.match(/\r?\n/g) ?? [];
29
29
  }
30
30
 
31
31
  /** New internal gaps reuse the corresponding old gap, then the last gap or file style. */
32
- export function replacementSeparator(separators: readonly string[], index: number, fallback: string): string {
33
- return separators[index] || separators[separators.length - 1] || fallback;
32
+ export function replacementSeparator(
33
+ separators: readonly string[],
34
+ index: number,
35
+ fallback: string,
36
+ ): string {
37
+ return separators[index] || separators[separators.length - 1] || fallback;
34
38
  }
35
39
 
36
40
  /** Restore a logical replacement without normalizing it a second time. */
37
41
  export function restoreLineEndings(logical: string, original: string, fallback: string): string {
38
- const separators = lineSeparators(original);
39
- let index = 0;
40
- return logical.replace(/\n/g, () => replacementSeparator(separators, index++, fallback));
42
+ const separators = lineSeparators(original);
43
+ let index = 0;
44
+ return logical.replace(/\n/g, () => replacementSeparator(separators, index++, fallback));
41
45
  }
42
46
 
43
47
  /** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
44
48
  export function createLfTextView(source: string) {
45
- const removed: number[] = [];
46
- for (const match of source.matchAll(/\r\n/g)) removed.push(match.index! - removed.length);
47
- return {
48
- text: normalizeLineEndings(source),
49
- sourceOffset(offset: number): number {
50
- // Count removed CRs strictly before this boundary: a newline starts at its original CR.
51
- let lo = 0;
52
- let hi = removed.length;
53
- while (lo < hi) {
54
- const mid = Math.floor((lo + hi) / 2);
55
- if (removed[mid] < offset) lo = mid + 1;
56
- else hi = mid;
57
- }
58
- return offset + lo;
59
- },
60
- };
49
+ const removed: number[] = [];
50
+ for (const match of source.matchAll(/\r\n/g)) removed.push(match.index! - removed.length);
51
+ return {
52
+ text: normalizeLineEndings(source),
53
+ sourceOffset(offset: number): number {
54
+ // Count removed CRs strictly before this boundary: a newline starts at its original CR.
55
+ let lo = 0;
56
+ let hi = removed.length;
57
+ while (lo < hi) {
58
+ const mid = Math.floor((lo + hi) / 2);
59
+ if (removed[mid] < offset) lo = mid + 1;
60
+ else hi = mid;
61
+ }
62
+ return offset + lo;
63
+ },
64
+ };
61
65
  }
62
66
 
63
67
  /**
@@ -71,14 +75,18 @@ export function createLfTextView(source: string) {
71
75
  * - `""` → `[]`
72
76
  */
73
77
  export function splitLines(text: string): string[] {
74
- if (text === "") return [];
75
- const normalized = normalizeLineEndings(text);
76
- return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
78
+ if (text === "") return [];
79
+ if (!text.includes("\r")) {
80
+ return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
81
+ }
82
+ const normalized = text.replaceAll("\r\n", "\n");
83
+ const lines = (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
84
+ return lines;
77
85
  }
78
86
 
79
87
  /** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
80
88
  export function detectLineEnding(text: string): LineEnding {
81
- return text.includes("\r\n") ? "crlf" : "lf";
89
+ return text.includes("\r\n") ? "crlf" : "lf";
82
90
  }
83
91
 
84
92
  /**
@@ -90,5 +98,5 @@ export function detectLineEnding(text: string): LineEnding {
90
98
  * round-trips.
91
99
  */
92
100
  export function hasFinalNewline(text: string): boolean {
93
- return text === "" || text.endsWith("\n");
101
+ return text === "" || text.endsWith("\n");
94
102
  }
@@ -3,26 +3,80 @@ import { test } from "node:test";
3
3
  import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
4
4
 
5
5
  test("conflicts distinguish adjacent ranges from insertions at starts and interiors", () => {
6
- const cases: [HalfOpenRange[], number | undefined][] = [
7
- [[], undefined],
8
- [[[0, 2], [2, 4]], undefined],
9
- [[[0, 2], [2, 2]], undefined],
10
- [[[0, 0], [0, 0]], 1],
11
- [[[0, 0], [0, 2]], 1],
12
- [[[0, 3], [1, 1]], 1],
13
- [[[0, 3], [1, 2]], 1],
14
- [[[0, 1], [1, 2], [1, 3]], 2],
15
- ];
16
- for (const [ranges, expected] of cases) {
17
- assert.equal(findSortedRangeConflict(ranges), expected);
18
- assert.equal(findSortedRangeConflict(ranges.map(([start, end]) => [start + 10, end + 10])), expected);
19
- }
6
+ const cases: [HalfOpenRange[], number | undefined][] = [
7
+ [[], undefined],
8
+ [
9
+ [
10
+ [0, 2],
11
+ [2, 4],
12
+ ],
13
+ undefined,
14
+ ],
15
+ [
16
+ [
17
+ [0, 2],
18
+ [2, 2],
19
+ ],
20
+ undefined,
21
+ ],
22
+ [
23
+ [
24
+ [0, 0],
25
+ [0, 0],
26
+ ],
27
+ 1,
28
+ ],
29
+ [
30
+ [
31
+ [0, 0],
32
+ [0, 2],
33
+ ],
34
+ 1,
35
+ ],
36
+ [
37
+ [
38
+ [0, 3],
39
+ [1, 1],
40
+ ],
41
+ 1,
42
+ ],
43
+ [
44
+ [
45
+ [0, 3],
46
+ [1, 2],
47
+ ],
48
+ 1,
49
+ ],
50
+ [
51
+ [
52
+ [0, 1],
53
+ [1, 2],
54
+ [1, 3],
55
+ ],
56
+ 2,
57
+ ],
58
+ ];
59
+ for (const [ranges, expected] of cases) {
60
+ assert.equal(findSortedRangeConflict(ranges), expected);
61
+ assert.equal(
62
+ findSortedRangeConflict(ranges.map(([start, end]) => [start + 10, end + 10])),
63
+ expected,
64
+ );
65
+ }
20
66
  });
21
67
 
22
68
  test("range merging preserves input and coalesces overlap, containment, and adjacency", () => {
23
- const ranges: HalfOpenRange[] = [[7, 9], [1, 3], [2, 3], [3, 5]];
24
- const before = structuredClone(ranges);
25
- assert.deepEqual(mergeRanges(ranges), [[1, 5], [7, 9]]);
26
- assert.deepEqual(ranges, before);
27
- assert.deepEqual(mergeRanges([]), []);
69
+ const ranges: HalfOpenRange[] = [
70
+ [7, 9],
71
+ [1, 3],
72
+ [2, 3],
73
+ [3, 5],
74
+ ];
75
+ const before = structuredClone(ranges);
76
+ assert.deepEqual(mergeRanges(ranges), [
77
+ [1, 5],
78
+ [7, 9],
79
+ ]);
80
+ assert.deepEqual(ranges, before);
81
+ assert.deepEqual(mergeRanges([]), []);
28
82
  });
@@ -3,23 +3,23 @@ export type HalfOpenRange = readonly [start: number, end: number];
3
3
 
4
4
  /** Find the first conflicting pair's second index. Input must be sorted by start, then end. */
5
5
  export function findSortedRangeConflict(ranges: readonly HalfOpenRange[]): number | undefined {
6
- for (let i = 1; i < ranges.length; i++) {
7
- const previous = ranges[i - 1];
8
- const current = ranges[i];
9
- // Insertions conflict at a shared start or inside a range, but not at its end.
10
- if (current[0] < previous[1] || current[0] === previous[0]) return i;
11
- }
12
- return undefined;
6
+ for (let i = 1; i < ranges.length; i++) {
7
+ const previous = ranges[i - 1];
8
+ const current = ranges[i];
9
+ // Insertions conflict at a shared start or inside a range, but not at its end.
10
+ if (current[0] < previous[1] || current[0] === previous[0]) return i;
11
+ }
12
+ return undefined;
13
13
  }
14
14
 
15
15
  /** Merge overlapping or adjacent ranges; callers validate their own units and bounds. */
16
16
  export function mergeRanges(ranges: readonly HalfOpenRange[]): HalfOpenRange[] {
17
- const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
18
- const result: HalfOpenRange[] = [];
19
- for (const range of sorted) {
20
- const previous = result.at(-1);
21
- if (!previous || range[0] > previous[1]) result.push(range);
22
- else if (range[1] > previous[1]) result[result.length - 1] = [previous[0], range[1]];
23
- }
24
- return result;
17
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
18
+ const result: HalfOpenRange[] = [];
19
+ for (const range of sorted) {
20
+ const previous = result.at(-1);
21
+ if (!previous || range[0] > previous[1]) result.push(range);
22
+ else if (range[1] > previous[1]) result[result.length - 1] = [previous[0], range[1]];
23
+ }
24
+ return result;
25
25
  }
@@ -0,0 +1,109 @@
1
+ import { escapeRegex } from "./text.ts";
2
+ import {
3
+ createLfTextView,
4
+ detectLineEnding,
5
+ normalizeLineEndings,
6
+ restoreLineEndings,
7
+ } from "./lines.ts";
8
+ import { findSortedRangeConflict } from "./ranges.ts";
9
+ import { errorMessage } from "./errors.ts";
10
+
11
+ export interface Replacement {
12
+ find: string;
13
+ replace: string;
14
+ regex?: boolean;
15
+ flags?: string;
16
+ }
17
+
18
+ /**
19
+ * Both matcher modes operate on the shared LF view. Flag characters are validated by the tool
20
+ * schema; replace's prepareArguments also compiles regex rules here before any file is read.
21
+ */
22
+ export function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
23
+ const set = new Set((flagsRaw ?? "").split(""));
24
+ set.add("g");
25
+ const flagStr = [...set].join("");
26
+ const logical = normalizeLineEndings(find);
27
+ const source = isRegex ? logical : escapeRegex(logical);
28
+ try {
29
+ return new RegExp(source, flagStr);
30
+ } catch (e) {
31
+ const msg = errorMessage(e);
32
+ throw new Error(`invalid regex /${source}/${flagStr}: ${msg}`);
33
+ }
34
+ }
35
+
36
+ /** Expand JS replacement tokens against the original match, including prefix/suffix context. */
37
+ function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
38
+ // Without named captures, $<...> is ordinary text and may contain other $ tokens.
39
+ const tokens =
40
+ match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
41
+ return template.replace(tokens, (token, key: string) => {
42
+ if (key === "$") return "$";
43
+ if (key === "&") return match[0];
44
+ if (key === "`") return source.slice(0, match.index);
45
+ if (key === "'") return source.slice(match.index! + match[0].length);
46
+ if (key.startsWith("<"))
47
+ return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
48
+ const index = Number(key);
49
+ if (index > 0 && index < match.length) return match[index] ?? "";
50
+ // $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
51
+ const first = Number(key[0]);
52
+ if (key.length === 2 && first > 0 && first < match.length) return (match[first] ?? "") + key[1];
53
+ return token;
54
+ });
55
+ }
56
+
57
+ export function applyReplacements(
58
+ source: string,
59
+ rules: readonly Replacement[],
60
+ ): { text: string; count: number } {
61
+ const changes: { start: number; end: number; text: string; rule: number }[] = [];
62
+ const view = createLfTextView(source);
63
+ const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
64
+ for (const [index, rule] of rules.entries()) {
65
+ try {
66
+ const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
67
+ let count = 0;
68
+ const replacement = normalizeLineEndings(rule.replace);
69
+ for (const match of view.text.matchAll(regex)) {
70
+ count++;
71
+ const start = view.sourceOffset(match.index!);
72
+ const end = view.sourceOffset(match.index! + match[0].length);
73
+ changes.push({
74
+ start,
75
+ end,
76
+ rule: index,
77
+ text: restoreLineEndings(
78
+ rule.regex ? expandReplacement(replacement, match, view.text) : replacement,
79
+ source.slice(start, end),
80
+ fallbackEnding,
81
+ ),
82
+ });
83
+ }
84
+ if (count === 0)
85
+ throw new Error(
86
+ `no matches for ${rule.regex ? `/${rule.find}/` : JSON.stringify(rule.find)}. Verify the target text with read or grep; check case sensitivity or regex flags if applicable.`,
87
+ );
88
+ } catch (error) {
89
+ throw new Error(`rule ${index}: ${errorMessage(error)}`);
90
+ }
91
+ }
92
+ changes.sort((a, b) => a.start - b.start || a.end - b.end);
93
+ const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
94
+ if (conflict !== undefined) {
95
+ const previous = changes[conflict - 1];
96
+ const current = changes[conflict];
97
+ throw new Error(
98
+ `rules ${previous.rule} and ${current.rule} overlap at offset ${current.start}; no replacements applied`,
99
+ );
100
+ }
101
+ const parts: string[] = [];
102
+ let cursor = 0;
103
+ for (const change of changes) {
104
+ parts.push(source.slice(cursor, change.start), change.text);
105
+ cursor = change.end;
106
+ }
107
+ parts.push(source.slice(cursor));
108
+ return { text: parts.join(""), count: changes.length };
109
+ }
@@ -3,13 +3,13 @@ import assert from "node:assert/strict";
3
3
  import { decodeEditableText, decodeUtf8 } from "./text.ts";
4
4
 
5
5
  test("decodeUtf8 rejects malformed input instead of replacing bytes", () => {
6
- assert.throws(() => decodeUtf8(Uint8Array.from([0xc3, 0x28])), /UNSUPPORTED_ENCODING/);
6
+ assert.throws(() => decodeUtf8(Uint8Array.from([0xc3, 0x28])), /UNSUPPORTED_ENCODING/);
7
7
  });
8
8
 
9
9
  test("decodeUtf8 preserves a leading BOM", () => {
10
- assert.equal(decodeUtf8(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
10
+ assert.equal(decodeUtf8(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
11
11
  });
12
12
 
13
13
  test("decodeEditableText rejects NUL bytes", () => {
14
- assert.throws(() => decodeEditableText(Uint8Array.from([0x61, 0, 0x62])), /UNSUPPORTED_TEXT/);
14
+ assert.throws(() => decodeEditableText(Uint8Array.from([0x61, 0, 0x62])), /UNSUPPORTED_TEXT/);
15
15
  });
package/src/core/text.ts CHANGED
@@ -1,23 +1,40 @@
1
1
  import { TextDecoder } from "node:util";
2
2
 
3
- const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
3
+ import { INVALID_UNICODE, UNSUPPORTED_ENCODING, UNSUPPORTED_TEXT_NUL } from "./errors.ts";
4
+
5
+ /** Why text cannot be written as editable UTF-8 (NUL or unpaired surrogates); undefined when it can. */
6
+ export function unwritableTextReason(text: string): string | undefined {
7
+ if (text.includes("\0")) return UNSUPPORTED_TEXT_NUL;
8
+ if (!text.isWellFormed()) return INVALID_UNICODE;
9
+ return undefined;
10
+ }
11
+
12
+ /** Create an independent UTF-8 decoder; streaming calls preserve split code points and the BOM. */
13
+ export function createUtf8Decoder() {
14
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
15
+ return (bytes?: Uint8Array, stream = false): string => {
16
+ try {
17
+ return decoder.decode(bytes, { stream });
18
+ } catch (error) {
19
+ throw new Error(UNSUPPORTED_ENCODING, { cause: error });
20
+ }
21
+ };
22
+ }
23
+
24
+ const decode = createUtf8Decoder();
4
25
 
5
26
  /** Decode UTF-8 without replacing malformed bytes; preserve a leading BOM for byte-stable rewrites. */
6
27
  export function decodeUtf8(bytes: Uint8Array): string {
7
- try {
8
- return UTF8_DECODER.decode(bytes);
9
- } catch (error) {
10
- throw new Error("UNSUPPORTED_ENCODING: expected valid UTF-8.", { cause: error });
11
- }
28
+ return decode(bytes);
12
29
  }
13
30
 
14
31
  /** Reject byte-oriented/binary content before entering a text mutation pipeline. */
15
32
  export function decodeEditableText(bytes: Uint8Array): string {
16
- if (bytes.includes(0)) throw new Error("UNSUPPORTED_TEXT: NUL bytes are not editable.");
17
- return decodeUtf8(bytes);
33
+ if (bytes.includes(0)) throw new Error(UNSUPPORTED_TEXT_NUL);
34
+ return decodeUtf8(bytes);
18
35
  }
19
36
 
20
37
  /** Escape regex metacharacters for a standalone literal pattern in JS or ripgrep. */
21
38
  export function escapeRegex(text: string): string {
22
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
39
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
40
  }