@criogaid/pi-hashline-edit 0.7.0 → 0.8.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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
package/src/core/apply.ts CHANGED
@@ -21,7 +21,8 @@
21
21
  * deferred until anchors are corrected.
22
22
  *
23
23
  * Other strict semantics:
24
- * - Operation ranges must not overlap (including the same insertion point).
24
+ * - Operation ranges must not overlap. Insertions at one position, or at the start of a
25
+ * replaced or deleted range, apply in batch order before that range.
25
26
  * - Byte-identical output is a success; the commit layer reports it as a no-op.
26
27
  *
27
28
  * @module pi-hashline-edit/core
@@ -31,6 +32,7 @@ import { computeLineHash } from "./hash.ts";
31
32
  import {
32
33
  detectLineEnding,
33
34
  hasFinalNewline,
35
+ joinTextFragments,
34
36
  lineSeparators,
35
37
  replacementSeparator,
36
38
  splitLines,
@@ -113,10 +115,7 @@ function verifyAnchor(
113
115
  recovery = { kind: "none" };
114
116
  }
115
117
 
116
- const current =
117
- line >= 1 && line <= lines.length
118
- ? { hash: computeLineHash(line, lines[line - 1], hashLen), content: lines[line - 1] }
119
- : null;
118
+ const current = line >= 1 && line <= lines.length ? { content: lines[line - 1] } : null;
120
119
 
121
120
  return { opIndex, which, op, cited, recovery, current };
122
121
  }
@@ -129,13 +128,11 @@ type TranslateResult =
129
128
  type RangeError = Pick<Extract<ApplyFailure, { kind: "range" }>, "code" | "message">;
130
129
 
131
130
  function checkedAnchor(
132
- edit: Edit,
133
131
  opIndex: number,
134
132
  which: AnchorCheck["which"],
135
- cited: Anchor,
136
133
  failure: AnchorFailure | null,
137
134
  ): AnchorCheck {
138
- return { opIndex, which, op: edit.op, cited, status: failure ? "mismatched" : "matched" };
135
+ return { opIndex, which, status: failure ? "mismatched" : "matched" };
139
136
  }
140
137
 
141
138
  /** Verify an Edit against the snapshot and plan its mutation spans and captured source. */
@@ -153,13 +150,13 @@ function translateEdit(
153
150
  case "move": {
154
151
  const failures: AnchorFailure[] = [];
155
152
  const checks: AnchorCheck[] = [];
156
- const startF = verifyAnchor(lines, edit.start, "anchor", opIndex, edit.op, hashLen, radius);
157
- checks.push(checkedAnchor(edit, opIndex, "anchor", edit.start, startF));
158
- if (startF) failures.push(startF);
159
- let endLine = edit.start.line;
153
+ const anchorF = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
154
+ checks.push(checkedAnchor(opIndex, "anchor", anchorF));
155
+ if (anchorF) failures.push(anchorF);
156
+ let endLine = edit.anchor.line;
160
157
  if (edit.end) {
161
158
  const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
162
- checks.push(checkedAnchor(edit, opIndex, "end", edit.end, endF));
159
+ checks.push(checkedAnchor(opIndex, "end", endF));
163
160
  if (endF) failures.push(endF);
164
161
  endLine = edit.end.line;
165
162
  }
@@ -179,28 +176,28 @@ function translateEdit(
179
176
  hashLen,
180
177
  radius,
181
178
  );
182
- checks.push(checkedAnchor(edit, opIndex, destination.which, destination.cited, failure));
179
+ checks.push(checkedAnchor(opIndex, destination.which, failure));
183
180
  if (failure) failures.push(failure);
184
181
  }
185
182
  if (failures.length > 0) return { ok: false, anchorFailures: failures, checks };
186
- if (endLine < edit.start.line)
183
+ if (endLine < edit.anchor.line)
187
184
  return {
188
185
  ok: false,
189
186
  rangeError: {
190
187
  code: "INVALID_RANGE",
191
- message: `Range ${edit.start.line}..${endLine} ends before it starts.`,
188
+ message: `Range ${edit.anchor.line}..${endLine} ends before it starts.`,
192
189
  },
193
190
  checks,
194
191
  };
195
192
  if (destination) {
196
- const sourceLo = edit.start.line - 1;
193
+ const sourceLo = edit.anchor.line - 1;
197
194
  const gap = destination.cited.line - (destination.which === "before" ? 1 : 0);
198
195
  if (edit.op === "move" && sourceLo < gap && gap < endLine) {
199
196
  return {
200
197
  ok: false,
201
198
  rangeError: {
202
199
  code: "INVALID_RANGE",
203
- message: `Destination ${destination.which} line ${destination.cited.line} lies inside moved range ${edit.start.line}..${endLine}.`,
200
+ message: `Destination ${destination.which} line ${destination.cited.line} lies inside moved range ${edit.anchor.line}..${endLine}.`,
204
201
  },
205
202
  checks,
206
203
  };
@@ -229,7 +226,7 @@ function translateEdit(
229
226
  checks,
230
227
  ops: [
231
228
  {
232
- lo: edit.start.line - 1,
229
+ lo: edit.anchor.line - 1,
233
230
  hi: endLine,
234
231
  kind: "body",
235
232
  newLines: edit.op === "replace" ? edit.body : [],
@@ -240,7 +237,7 @@ function translateEdit(
240
237
  case "insert_after":
241
238
  case "insert_before": {
242
239
  const failure = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
243
- const checks = [checkedAnchor(edit, opIndex, "anchor", edit.anchor, failure)];
240
+ const checks = [checkedAnchor(opIndex, "anchor", failure)];
244
241
  if (failure) return { ok: false, anchorFailures: [failure], checks };
245
242
  const line = edit.anchor.line - (edit.op === "insert_before" ? 1 : 0);
246
243
  return { ok: true, checks, ops: [{ lo: line, hi: line, kind: "body", newLines: edit.body }] };
@@ -305,8 +302,12 @@ export function applyEdits(
305
302
  return { ok: false, failure: { kind: "range", ...rangeError, checks: anchorChecks } };
306
303
  }
307
304
 
305
+ // A stable sort keeps batch order among insertions at one position.
308
306
  const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
309
- const conflict = findSortedRangeConflict(sorted.map((op) => [op.lo, op.hi]));
307
+ const conflict = findSortedRangeConflict(
308
+ sorted.map((op) => [op.lo, op.hi]),
309
+ true,
310
+ );
310
311
  if (conflict !== undefined) {
311
312
  return {
312
313
  ok: false,
@@ -372,14 +373,11 @@ export function applyEdits(
372
373
  hasFinalNewline(text) || (result.at(-1)?.content === "" && (result.length > 1 || !bom));
373
374
  const newText =
374
375
  bom +
375
- result
376
- .map(
377
- ({ content, separator: current }, i) =>
378
- content +
379
- (i < result.length - 1 || finalNewline
380
- ? current || (content.endsWith("\r") ? "\r\n" : separator)
381
- : ""),
382
- )
383
- .join("");
376
+ joinTextFragments(
377
+ result.flatMap(({ content, separator: current }, i) => [
378
+ content,
379
+ i < result.length - 1 || finalNewline ? current || separator : "",
380
+ ]),
381
+ );
384
382
  return { ok: true, text: newText };
385
383
  }
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { caseVariants, equivalentCases } from "./case-fold.ts";
3
+ import { caseVariants } from "./case-fold.ts";
4
+ import { MAX_UNIT } from "./character-set.ts";
4
5
 
5
6
  for (const [char, unicode, expected] of [
6
7
  ["k", false, ["K", "k"]],
@@ -30,11 +31,14 @@ for (const [char, unicode, expected] of [
30
31
  });
31
32
  }
32
33
 
33
- test("non-Unicode equivalence groups → every member agrees with native RegExp", () => {
34
- for (const group of equivalentCases()) {
35
- const source = `^\\u${group[0].toString(16).padStart(4, "0")}$`;
36
- const native = new RegExp(source, "i");
37
- for (const unit of group)
38
- assert.ok(native.test(String.fromCharCode(unit)), `${source}: ${unit}`);
34
+ test("Cartesian non-Unicode code units → case variants agree with native RegExp", () => {
35
+ const allUnits = Array.from({ length: MAX_UNIT + 1 }, (_, unit) =>
36
+ String.fromCharCode(unit),
37
+ ).join("");
38
+ for (let unit = 0; unit <= MAX_UNIT; unit++) {
39
+ const char = String.fromCharCode(unit);
40
+ const source = `\\u${unit.toString(16).padStart(4, "0")}`;
41
+ const expected = allUnits.match(new RegExp(source, "gi"));
42
+ assert.deepEqual(caseVariants(char, false), expected, source);
39
43
  }
40
44
  });
@@ -8,11 +8,8 @@
8
8
  import { MAX_UNIT, MAX_SCALAR, nativeCharacterRanges } from "./character-set.ts";
9
9
  const MAX_ASCII = 0x7f;
10
10
 
11
- let unitGroups: readonly (readonly number[])[] | undefined;
12
-
13
11
  /** Code units that ignoreCase treats as equal: ECMA-262 Canonicalize without the u flag. */
14
- export function equivalentCases(): readonly (readonly number[])[] {
15
- if (unitGroups) return unitGroups;
12
+ function equivalentCases(): readonly (readonly number[])[] {
16
13
  const groups = new Map<number, number[]>();
17
14
  for (let unit = 0; unit <= MAX_UNIT; unit++) {
18
15
  const upper = String.fromCharCode(unit).toUpperCase();
@@ -24,8 +21,7 @@ export function equivalentCases(): readonly (readonly number[])[] {
24
21
  if (group) group.push(unit);
25
22
  else groups.set(canonical, [unit]);
26
23
  }
27
- unitGroups = [...groups.values()].filter((group) => group.length > 1);
28
- return unitGroups;
24
+ return [...groups.values()].filter((group) => group.length > 1);
29
25
  }
30
26
 
31
27
  let unitVariants: ReadonlyMap<number, readonly string[]> | undefined;
@@ -139,6 +139,20 @@ export function foldRanges(ranges: Ranges, unicode: boolean): Ranges {
139
139
  return nativeCharacterRanges(source, unicode ? "iu" : "i");
140
140
  }
141
141
 
142
+ /**
143
+ * The multi-character strings a class node matches under `flags`; undefined when a string
144
+ * property cannot be enumerated here.
145
+ */
146
+ export function acceptedClassStrings(
147
+ node: CharacterNode,
148
+ flags: string,
149
+ ): readonly string[] | undefined {
150
+ const strings = classStrings(node);
151
+ if (!strings?.length) return strings;
152
+ const accepts = membership(node.raw, flags);
153
+ return strings.filter((value) => accepts.test(value));
154
+ }
155
+
142
156
  /** String representatives of a class; undefined means a string property is not enumerable here. */
143
157
  export function classStrings(node: ClassNode): readonly string[] | undefined {
144
158
  switch (node.type) {
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { computeLineHash, hashFileLines } from "./hash.ts";
3
+ import { computeLineHash } from "./hash.ts";
4
4
 
5
5
  const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
6
6
 
@@ -21,10 +21,6 @@ test("different content → different hash", () => {
21
21
  assert.notEqual(computeLineHash(1, "a", 4), computeLineHash(1, "b", 4));
22
22
  });
23
23
 
24
- test("same (line, content) → same hash", () => {
25
- assert.equal(computeLineHash(7, "x", 4), computeLineHash(7, "x", 4));
26
- });
27
-
28
24
  test("base32 alphabet (without I/L/O/U) in bulk", () => {
29
25
  for (let i = 0; i < 2000; i++) {
30
26
  const h = computeLineHash(i + 1, `line ${i}`, 4);
@@ -32,31 +28,11 @@ test("base32 alphabet (without I/L/O/U) in bulk", () => {
32
28
  }
33
29
  });
34
30
 
35
- test("hashFileLines length equals line count", () => {
36
- assert.equal(hashFileLines(["a", "b", "c"], 4).length, 3);
37
- });
38
-
39
- test("hashFileLines empty file", () => {
40
- assert.deepEqual(hashFileLines([], 4), []);
41
- });
42
-
43
- test("hashFileLines normally disambiguates repeated content without changing hash length", () => {
44
- const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
45
- const hashes = hashFileLines(lines, 4);
46
- assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
47
- for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
48
- });
49
-
50
31
  test("truncated checksums can collide", () => {
51
32
  assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
52
33
  assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
53
34
  });
54
35
 
55
- test("hashFileLines respects the length parameter", () => {
56
- assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
57
- assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
58
- });
59
-
60
36
  test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
61
37
  for (let i = 1; i <= 20; i++) {
62
38
  const h = computeLineHash(i, `content ${i}`, 8);
package/src/core/hash.ts CHANGED
@@ -86,8 +86,3 @@ export const HASH_LEN_MAX = 8;
86
86
  export function computeLineHash(line: number, content: string, len: number): string {
87
87
  return toBase32(fnv1a32Line(line, content), len);
88
88
  }
89
-
90
- /** Compute compact per-line checksums; callers must treat collisions as possible. */
91
- export function hashFileLines(lines: readonly string[], len: number): string[] {
92
- return lines.map((content, i) => computeLineHash(i + 1, content, len));
93
- }
package/src/core/lines.ts CHANGED
@@ -37,11 +37,33 @@ export function replacementSeparator(
37
37
  return separators[index] || separators[separators.length - 1] || fallback;
38
38
  }
39
39
 
40
+ /** Keep a trailing CR as content when the following fragment starts with an LF separator. */
41
+ function preserveBoundaryCarriageReturn(previous: string, next: string): string {
42
+ return previous.endsWith("\r") && next.startsWith("\n") ? `\r${next}` : next;
43
+ }
44
+
45
+ /** Join independent raw fragments without absorbing trailing CR content into the next LF. */
46
+ export function joinTextFragments(parts: readonly string[]): string {
47
+ const joined: string[] = [];
48
+ let previous = "";
49
+ for (const part of parts) {
50
+ if (!part) continue;
51
+ joined.push(preserveBoundaryCarriageReturn(previous, part));
52
+ previous = part;
53
+ }
54
+ return joined.join("");
55
+ }
56
+
40
57
  /** Restore a logical replacement without normalizing it a second time. */
41
58
  export function restoreLineEndings(logical: string, original: string, fallback: string): string {
42
59
  const separators = lineSeparators(original);
43
60
  let index = 0;
44
- return logical.replace(/\n/g, () => replacementSeparator(separators, index++, fallback));
61
+ return logical.replace(/\n/g, (_match, offset: number) =>
62
+ preserveBoundaryCarriageReturn(
63
+ logical[offset - 1] ?? "",
64
+ replacementSeparator(separators, index++, fallback),
65
+ ),
66
+ );
45
67
  }
46
68
 
47
69
  /** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
@@ -76,12 +98,8 @@ export function createLfTextView(source: string) {
76
98
  */
77
99
  export function splitLines(text: string): string[] {
78
100
  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;
101
+ const normalized = normalizeLineEndings(text);
102
+ return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
85
103
  }
86
104
 
87
105
  /** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
@@ -2,15 +2,16 @@ import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
4
4
 
5
- test("conflicts distinguish adjacent ranges from insertions at starts and interiors", () => {
6
- const cases: [HalfOpenRange[], number | undefined][] = [
7
- [[], undefined],
5
+ test("sorted ranges → ordered starts allow only empty ranges before a shared start", () => {
6
+ const cases: [HalfOpenRange[], number | undefined, number | undefined][] = [
7
+ [[], undefined, undefined],
8
8
  [
9
9
  [
10
10
  [0, 2],
11
11
  [2, 4],
12
12
  ],
13
13
  undefined,
14
+ undefined,
14
15
  ],
15
16
  [
16
17
  [
@@ -18,6 +19,7 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
18
19
  [2, 2],
19
20
  ],
20
21
  undefined,
22
+ undefined,
21
23
  ],
22
24
  [
23
25
  [
@@ -25,13 +27,24 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
25
27
  [0, 0],
26
28
  ],
27
29
  1,
30
+ undefined,
31
+ ],
32
+ [
33
+ [
34
+ [0, 0],
35
+ [0, 2],
36
+ ],
37
+ 1,
38
+ undefined,
28
39
  ],
29
40
  [
30
41
  [
42
+ [0, 0],
31
43
  [0, 0],
32
44
  [0, 2],
33
45
  ],
34
46
  1,
47
+ undefined,
35
48
  ],
36
49
  [
37
50
  [
@@ -39,6 +52,7 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
39
52
  [1, 1],
40
53
  ],
41
54
  1,
55
+ 1,
42
56
  ],
43
57
  [
44
58
  [
@@ -46,6 +60,15 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
46
60
  [1, 2],
47
61
  ],
48
62
  1,
63
+ 1,
64
+ ],
65
+ [
66
+ [
67
+ [0, 2],
68
+ [0, 3],
69
+ ],
70
+ 1,
71
+ 1,
49
72
  ],
50
73
  [
51
74
  [
@@ -54,14 +77,23 @@ test("conflicts distinguish adjacent ranges from insertions at starts and interi
54
77
  [1, 3],
55
78
  ],
56
79
  2,
80
+ 2,
57
81
  ],
58
82
  ];
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
- );
83
+ for (const [ranges, strictConflict, orderedConflict] of cases) {
84
+ for (const orderedStarts of [false, true]) {
85
+ const expected = orderedStarts ? orderedConflict : strictConflict;
86
+ for (const shift of [0, 10]) {
87
+ assert.equal(
88
+ findSortedRangeConflict(
89
+ ranges.map(([start, end]) => [start + shift, end + shift]),
90
+ orderedStarts,
91
+ ),
92
+ expected,
93
+ JSON.stringify({ ranges, orderedStarts, shift }),
94
+ );
95
+ }
96
+ }
65
97
  }
66
98
  });
67
99
 
@@ -1,13 +1,20 @@
1
1
  /** Half-open bounds in a caller-selected unit (line indices or string offsets). */
2
2
  export type HalfOpenRange = readonly [start: number, end: number];
3
3
 
4
- /** Find the first conflicting pair's second index. Input must be sorted by start, then end. */
5
- export function findSortedRangeConflict(ranges: readonly HalfOpenRange[]): number | undefined {
4
+ /**
5
+ * Find the first conflicting pair's second index. Input must be sorted by start, then end,
6
+ * with ties in caller order. A range starting inside an earlier non-empty range always
7
+ * conflicts. An insertion (empty range) at a shared start conflicts unless `orderedStarts`
8
+ * is set; then it applies in input order before the range that starts there.
9
+ */
10
+ export function findSortedRangeConflict(
11
+ ranges: readonly HalfOpenRange[],
12
+ orderedStarts = false,
13
+ ): number | undefined {
6
14
  for (let i = 1; i < ranges.length; i++) {
7
15
  const previous = ranges[i - 1];
8
16
  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;
17
+ if (current[0] < previous[1] || (!orderedStarts && current[0] === previous[0])) return i;
11
18
  }
12
19
  return undefined;
13
20
  }
package/src/core/regex.ts CHANGED
@@ -1,21 +1,51 @@
1
1
  /** JavaScript regex construction on the shared LF view, used by both grep and replace. */
2
+ import { errorMessage } from "./errors.ts";
2
3
  import { normalizeLineEndings } from "./lines.ts";
3
4
  import { escapeRegex } from "./text.ts";
4
5
 
5
6
  /** JavaScript regex source on the shared LF view; literal text matches exactly. */
6
- export function regexSource(find: string, isRegex: boolean): string {
7
+ export function regexSource(find: string, literal: boolean): string {
7
8
  const logical = normalizeLineEndings(find);
8
- return isRegex ? logical : escapeRegex(logical);
9
+ return literal ? escapeRegex(logical) : logical;
9
10
  }
10
11
 
11
12
  /**
12
- * Both matcher modes operate on the shared LF view. Flag characters are validated by the tool
13
- * schema; replace's and grep's prepareArguments also compile regexes here before any file is read.
13
+ * Both matcher modes operate on the shared LF view. Replace's and grep's prepareArguments
14
+ * validate flags and compile regexes through checkRegexArguments before any file is read.
14
15
  */
15
- export function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
16
+ export function buildRegex(find: string, literal: boolean, flagsRaw: string | undefined): RegExp {
16
17
  const set = new Set((flagsRaw ?? "").split(""));
17
18
  set.add("g");
18
19
  const flagStr = [...set].join("");
19
20
  // The engine's SyntaxError already names the pattern and flags it compiled.
20
- return new RegExp(regexSource(find, isRegex), flagStr);
21
+ return new RegExp(regexSource(find, literal), flagStr);
22
+ }
23
+
24
+ /**
25
+ * Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
26
+ * buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
27
+ * them; values that are not non-empty strings are left to schema validation.
28
+ */
29
+ export function checkRegexArguments(
30
+ flagsField: string,
31
+ flags: string | undefined,
32
+ literal: boolean,
33
+ patterns: readonly (readonly [field: string, value: unknown])[],
34
+ report: (field: string, reason: string) => void,
35
+ ): void {
36
+ try {
37
+ buildRegex("", true, flags);
38
+ } catch (error) {
39
+ report(flagsField, errorMessage(error));
40
+ return;
41
+ }
42
+ if (literal) return;
43
+ for (const [field, value] of patterns) {
44
+ if (typeof value !== "string" || value === "") continue;
45
+ try {
46
+ buildRegex(value, false, flags);
47
+ } catch (error) {
48
+ report(field, errorMessage(error));
49
+ }
50
+ }
21
51
  }
@@ -1,25 +1,22 @@
1
- /** Tool-validated replacement rules and their engine type; no Pi runtime imports. */
1
+ /** Tool-validated replacement rules, the engine's result, and their types; no Pi runtime imports. */
2
2
  import { Type, type Static } from "typebox";
3
3
 
4
- export const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
5
-
6
- export const REPLACEMENT_SCHEMA = Type.Object(
4
+ const REPLACEMENT_SCHEMA = Type.Object(
7
5
  {
8
6
  find: Type.String({
9
7
  minLength: 1,
10
8
  description:
11
- "Text, or a JavaScript regex when regex is true. CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
9
+ "What to match: plain text when literal is true, a JavaScript regex when false. CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
12
10
  }),
13
- replace: Type.String({
11
+ literal: Type.Boolean({
14
12
  description:
15
- "Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
13
+ "true: find matches exactly, including regex punctuation, and replace keeps $ as is. false: find is a JavaScript regex and replace expands $1, $<name>, and $&; use it only for an intentional regex.",
14
+ }),
15
+ replace: Type.String({
16
+ description: "Replacement text; the file's line endings are kept.",
16
17
  }),
17
- regex: Type.Optional(
18
- Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
19
- ),
20
18
  flags: Type.Optional(
21
19
  Type.String({
22
- pattern: REGEX_FLAGS_PATTERN,
23
20
  description: "Extra regex flags, also applied in literal mode; g is always added.",
24
21
  }),
25
22
  ),
@@ -32,3 +29,13 @@ export const REPLACEMENTS_SCHEMA = Type.Array(REPLACEMENT_SCHEMA, {
32
29
  description: "Rules applied to the original content; inserted text is not searched again.",
33
30
  });
34
31
  export type Replacement = Readonly<Static<typeof REPLACEMENT_SCHEMA>>;
32
+
33
+ /** A replacement batch's new text and match count; the host checks it again across the worker boundary. */
34
+ export const REPLACEMENT_RESULT_SCHEMA = Type.Object(
35
+ {
36
+ text: Type.String(),
37
+ count: Type.Integer({ minimum: 1 }),
38
+ },
39
+ { additionalProperties: false },
40
+ );
41
+ export type ReplacementResult = Static<typeof REPLACEMENT_RESULT_SCHEMA>;
@@ -0,0 +1,90 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { applyReplacements, type Replacement } from "./replace.ts";
4
+
5
+ test("replacement joins beside LF → preserve standalone CR content", async (t) => {
6
+ const literal = (find: string, replace: string): Replacement => ({
7
+ find,
8
+ replace,
9
+ literal: true,
10
+ });
11
+ const cases = [
12
+ {
13
+ name: "replacement before original LF",
14
+ source: "a\nb",
15
+ rules: [literal("a", "x\r")],
16
+ expected: "x\r\r\nb",
17
+ },
18
+ {
19
+ name: "original CR before replacement LF",
20
+ source: "a\rb",
21
+ rules: [literal("b", "\nB")],
22
+ expected: "a\r\r\nB",
23
+ },
24
+ {
25
+ name: "deletion joins original CR and LF",
26
+ source: "a\rx\nb",
27
+ rules: [literal("x", "")],
28
+ expected: "a\r\r\nb",
29
+ },
30
+ {
31
+ name: "replacement contains CR before a new LF",
32
+ source: "a\nb",
33
+ rules: [literal("a", "x\r\r\ny")],
34
+ expected: "x\r\r\ny\nb",
35
+ },
36
+ {
37
+ name: "replacement contains CR before a reused LF",
38
+ source: "a\nb",
39
+ rules: [literal("a\nb", "x\r\r\ny")],
40
+ expected: "x\r\r\ny",
41
+ },
42
+ {
43
+ name: "captured CR before replacement LF",
44
+ source: "a\rb\nc",
45
+ rules: [{ find: "(a\r)b", replace: "$1\nB", literal: false }],
46
+ expected: "a\r\r\nB\nc",
47
+ },
48
+ {
49
+ name: "adjacent replacements",
50
+ source: "ab",
51
+ rules: [literal("a", "x\r"), literal("b", "\ny")],
52
+ expected: "x\r\r\ny",
53
+ },
54
+ {
55
+ name: "adjacent replacements separated by a deletion",
56
+ source: "axb",
57
+ rules: [literal("a", "x\r"), literal("x", ""), literal("b", "\ny")],
58
+ expected: "x\r\r\ny",
59
+ },
60
+ {
61
+ name: "zero-width insertion before LF",
62
+ source: "a\nb",
63
+ rules: [{ find: "(?=\\n)", replace: "\r", literal: false }],
64
+ expected: "a\r\r\nb",
65
+ },
66
+ {
67
+ name: "replacement before original CRLF",
68
+ source: "a\r\nb",
69
+ rules: [literal("a", "x\r")],
70
+ expected: "x\r\r\nb",
71
+ },
72
+ {
73
+ name: "unchanged CR content and CRLF separator",
74
+ source: "a\r\r\nb",
75
+ rules: [literal("a\r\r\nb", "a\r\r\nb")],
76
+ expected: "a\r\r\nb",
77
+ },
78
+ {
79
+ name: "CR at EOF needs no separator",
80
+ source: "ab",
81
+ rules: [literal("b", "x\r")],
82
+ expected: "ax\r",
83
+ },
84
+ ];
85
+ for (const { name, source, rules, expected } of cases) {
86
+ await t.test(name, () => {
87
+ assert.equal(applyReplacements(source, rules).text, expected);
88
+ });
89
+ }
90
+ });