@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,210 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { extractPrefilter, smartIgnoreCase, type Literal } from "./search-analysis.ts";
4
- import { searchText, type GrepQuery } from "./search.ts";
5
- import { acceptsNative, hasCandidateBytes } from "./search-matrix.testing.ts";
6
-
7
- const query = (pattern: string, ignoreCase = false, literal = false): GrepQuery => ({
8
- patterns: [pattern],
9
- ignoreCase,
10
- literal,
11
- multiline: true,
12
- });
13
- const literal = (text: string): Literal => [...text].map((char) => [char]);
14
-
15
- for (const [pattern, ignoreCase, expected] of [
16
- ["colou?r", false, [literal("color"), literal("colour")]],
17
- ["a*", false, undefined],
18
- ["(?:word|)", false, undefined],
19
- ["[^a]+", false, undefined],
20
- ["(?=word)", false, [literal("word")]],
21
- ["(?i:a)(?-i:b)", false, [[["A", "a"], ["b"]]]],
22
- ["(?-i:a)(?i:b)", true, [[["a"], ["B", "b"]]]],
23
- ["k", true, [[["K", "k"]]]],
24
- ["s", true, [[["S", "s"]]]],
25
- [
26
- "abéz",
27
- true,
28
- [
29
- [
30
- ["A", "a"],
31
- ["B", "b"],
32
- ["É", "é"],
33
- ["Z", "z"],
34
- ],
35
- ],
36
- ],
37
- ["é", true, [[["É", "é"]]]],
38
- ["[\\u0100-\\u0200]", false, undefined],
39
- ["foo.*bar", false, [literal("foo")]],
40
- ["(?:abcdef.*xy|zz.*ghijkl)", false, [literal("abcdef"), literal("ghijkl")]],
41
- ["foo|bar.*baz", false, [literal("foo"), literal("bar")]],
42
- ["(?=foo|bar).*baz", false, [literal("baz")]],
43
- ] as const) {
44
- test(`${pattern.slice(0, 80)} ignoreCase=${ignoreCase} → conservative candidate literals`, () => {
45
- assert.deepEqual(
46
- extractPrefilter(query(pattern, ignoreCase)),
47
- expected ? { kind: "literals", literals: expected } : { kind: "all" },
48
- );
49
- });
50
- }
51
-
52
- for (const boundary of ["\n", "\r\n", "\uFFFD", "\uD800", "\uDC00", "\0"]) {
53
- test(`literal ${JSON.stringify(boundary)} boundary → no candidate spans changed bytes`, () => {
54
- const prefilter = extractPrefilter(query(`left${boundary}right`, false, true));
55
- assert.deepEqual(prefilter, { kind: "literals", literals: [literal("right")] });
56
- assert.ok(hasCandidateBytes(Buffer.from(`left${boundary}right`), prefilter));
57
- assert.ok(hasCandidateBytes(Buffer.from("left\nright"), prefilter));
58
- assert.equal(hasCandidateBytes(Buffer.from("left"), prefilter), false);
59
- assert.ok(hasCandidateBytes(Buffer.from("right"), prefilter));
60
- assert.deepEqual(extractPrefilter(query(boundary, false, true)), { kind: "all" });
61
- });
62
- }
63
-
64
- for (const [patterns, isLiteral, expected] of [
65
- [["foo", "bar"], false, true],
66
- [["foo", "Bar"], false, false],
67
- [["foo\\S*", "\\D", "\\W"], false, true],
68
- [["\\u0041"], false, false],
69
- [["\\x41"], false, false],
70
- [["\\u0061"], false, true],
71
- [["[A-Z]"], false, false],
72
- [["(?<UPPER>foo)"], false, true],
73
- [["ς", "σ"], false, true],
74
- [["σ", "Σ"], false, false],
75
- [["foo\\S*"], true, false],
76
- [["\\u0041"], true, true],
77
- [["foo", "BAR"], true, false],
78
- ] as const) {
79
- test(`${JSON.stringify(patterns)} literal=${isLiteral} → smart case follows decoded letters`, () => {
80
- assert.equal(smartIgnoreCase(patterns, isLiteral), expected);
81
- });
82
- }
83
-
84
- test("smart case: a supplementary uppercase letter → case-sensitive", () => {
85
- for (const [pattern, isLiteral] of [
86
- ["𐐀é", true],
87
- ["𐐀é", false],
88
- ["\\uD801\\uDC00", false],
89
- ["[𐐀]", false],
90
- ] as const) {
91
- assert.equal(
92
- smartIgnoreCase([pattern], isLiteral),
93
- false,
94
- `${JSON.stringify(pattern)} literal=${isLiteral}`,
95
- );
96
- }
97
- });
98
-
99
- test("seeded random patterns × raw bytes → a JS hit always retains a candidate byte literal", () => {
100
- let seed = 0x5eed1234;
101
- const next = (bound: number) => {
102
- seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
103
- return seed % bound;
104
- };
105
- const atoms = [
106
- "a",
107
- "b",
108
- "k",
109
- "s",
110
- "é",
111
- "😀",
112
- "\\n",
113
- "\\r",
114
- "\\uFFFD",
115
- "\\uD83D",
116
- "[ab]",
117
- "[^b]",
118
- "\\w",
119
- ".",
120
- ];
121
- const pieces = [
122
- Buffer.from("abksABKSéÉKſ😀"),
123
- Buffer.from("\r\n"),
124
- Buffer.from("\n"),
125
- Buffer.from([0xff]),
126
- Buffer.from([0xc3, 0x28]),
127
- Buffer.from([0xed, 0xa0, 0x80]),
128
- ];
129
- const sources = Array.from({ length: 60 }, (_, index) =>
130
- index % 2 === 0
131
- ? Buffer.concat(Array.from({ length: 1 + next(8) }, () => pieces[next(pieces.length)]))
132
- : Buffer.from(Array.from({ length: 1 + next(80) }, () => 1 + next(255))),
133
- );
134
- const patterns = [
135
- "colou?r",
136
- "a\\uFFFDb",
137
- "😀",
138
- "k",
139
- "s",
140
- "(?:a|é)?b",
141
- "a\\nb",
142
- "[ab]+",
143
- "(?i:a)(?-i:b)",
144
- ];
145
- for (let index = 0; index < 200; index++) {
146
- const a = atoms[next(atoms.length)];
147
- const b = atoms[next(atoms.length)];
148
- patterns.push(
149
- [`${a}${b}`, `(?:${a}|${b})`, `(?:${a})?${b}`, `(?:${a})+${b}`, `(?=${a})${b}`][next(5)],
150
- );
151
- }
152
- let checkedHits = 0;
153
- let filteredHits = 0;
154
- for (const pattern of patterns) {
155
- for (const ignoreCase of [false, true]) {
156
- if (!acceptsNative(query(pattern, ignoreCase))) continue;
157
- for (const multiline of [false, true]) {
158
- const request = { ...query(pattern, ignoreCase), multiline };
159
- const prefilter = extractPrefilter(request);
160
- for (const bytes of sources) {
161
- if (
162
- !searchText({ source: bytes.toString("utf8"), query: request, limit: 1 }).lines.length
163
- )
164
- continue;
165
- checkedHits++;
166
- if (prefilter.kind === "all") continue;
167
- filteredHits++;
168
- assert.ok(
169
- hasCandidateBytes(bytes, prefilter),
170
- JSON.stringify({
171
- pattern,
172
- ignoreCase,
173
- multiline,
174
- bytes: bytes.toString("hex"),
175
- prefilter,
176
- }),
177
- );
178
- }
179
- }
180
- }
181
- }
182
- assert.ok(checkedHits > 1000, `Only ${checkedHits} matching cases exercised`);
183
- assert.ok(filteredHits > 1000, `Only ${filteredHits} filtered matches exercised`);
184
- });
185
-
186
- test("oversized literal alternation → retains necessary prefixes without dropping a branch", () => {
187
- const words = Array.from({ length: 100 }, (_, index) => `word${index}`);
188
- const prefilter = extractPrefilter(query(words.join("|")));
189
- for (const word of words) assert.ok(hasCandidateBytes(Buffer.from(word), prefilter));
190
- assert.equal(hasCandidateBytes(Buffer.from("unrelated"), prefilter), false);
191
- });
192
-
193
- test("empty expression with a huge repeat → completes without iterating the repeat count", () => {
194
- assert.deepEqual(extractPrefilter(query("(?:){1000000000}")), { kind: "all" });
195
- });
196
-
197
- test("word escape → keeps word-containing files and rejects punctuation-only files", () => {
198
- const prefilter = extractPrefilter(query("\\w+"));
199
- assert.ok(hasCandidateBytes(Buffer.from("---a---"), prefilter));
200
- assert.equal(hasCandidateBytes(Buffer.from("---"), prefilter), false);
201
- });
202
-
203
- test("deeply nested uppercase pattern → smart case stays sensitive and prefilter retains native hits", () => {
204
- for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
205
- const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
206
- assert.equal(new RegExp(pattern).test("A"), true);
207
- assert.equal(smartIgnoreCase([pattern], false), false);
208
- assert.equal(hasCandidateBytes(Buffer.from("A"), extractPrefilter(query(pattern))), true);
209
- }
210
- });
@@ -1,64 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { extractPrefilter } from "./search-analysis.ts";
4
- import { searchText } from "./search.ts";
5
- import {
6
- acceptsNative,
7
- hasCandidateBytes,
8
- matrixCases,
9
- MATRIX_INPUTS,
10
- } from "./search-matrix.testing.ts";
11
-
12
- test("Cartesian JS syntax × quantifiers × contexts × case modes × line modes × bytes → prefilter never drops a native match", (t) => {
13
- let accepted = 0;
14
- let rejected = 0;
15
- let evaluations = 0;
16
- let hits = 0;
17
- let filteredHits = 0;
18
- let misses = 0;
19
- const examples: string[] = [];
20
- const candidateCache = new Map<string, readonly boolean[]>();
21
- for (const scenario of matrixCases()) {
22
- if (!acceptsNative(scenario.query)) {
23
- rejected++;
24
- continue;
25
- }
26
- accepted++;
27
- const prefilter = extractPrefilter(scenario.query);
28
- const key = JSON.stringify(prefilter);
29
- let candidates = candidateCache.get(key);
30
- if (!candidates) {
31
- candidates = MATRIX_INPUTS.map(([, bytes]) => hasCandidateBytes(bytes, prefilter));
32
- candidateCache.set(key, candidates);
33
- }
34
- for (const [index, [input, bytes]] of MATRIX_INPUTS.entries()) {
35
- evaluations++;
36
- if (
37
- !searchText({ source: bytes.toString("utf8"), query: scenario.query, limit: 1 }).lines
38
- .length
39
- )
40
- continue;
41
- hits++;
42
- if (prefilter.kind !== "all") filteredHits++;
43
- if (candidates[index]) continue;
44
- misses++;
45
- if (examples.length < 10)
46
- examples.push(
47
- JSON.stringify({ ...scenario, input, bytes: bytes.toString("hex"), prefilter }),
48
- );
49
- }
50
- }
51
- t.diagnostic(
52
- JSON.stringify({
53
- accepted,
54
- rejected,
55
- evaluations,
56
- hits,
57
- filteredHits,
58
- prefilters: candidateCache.size,
59
- misses,
60
- }),
61
- );
62
- assert.ok(accepted > 0 && filteredHits > 0);
63
- assert.equal(misses, 0, examples.join("\n"));
64
- });
@@ -1,171 +0,0 @@
1
- /** Deterministic Cartesian inputs shared by the pure prefilter and real-rg boundary tests. */
2
- import type { GrepQuery } from "./search.ts";
3
- import type { Prefilter } from "./search-analysis.ts";
4
-
5
- export const MATRIX_SYNTAX = [
6
- ["ASCII literal", "a"],
7
- ["non-ASCII literal", "é"],
8
- ["Kelvin folding", "k"],
9
- ["long-s folding", "s"],
10
- ["sigma folding", "Σ"],
11
- ["supplementary literal", "😀"],
12
- ["high surrogate", "\\uD83D"],
13
- ["low surrogate", "\\uDE00"],
14
- ["escaped surrogate pair", "\\uD83D\\uDE00"],
15
- ["identity escape", "\\K"],
16
- ["escaped punctuation", "\\."],
17
- ["control escape", "\\cA"],
18
- ["hex escape", "\\x61"],
19
- ["Unicode escape", "\\u0061"],
20
- ["code-point escape", "\\u{1F600}"],
21
- ["legacy octal", "\\141"],
22
- ["legacy decimal escape", "\\8"],
23
- ["NUL", "\\0"],
24
- ["LF", "\\n"],
25
- ["CR", "\\r"],
26
- ["line separator", "\\u2028"],
27
- ["paragraph separator", "\\u2029"],
28
- ["replacement character", "\\uFFFD"],
29
- ["dot", "."],
30
- ["positive class", "[a-c]"],
31
- ["negative class", "[^a]"],
32
- ["digit", "\\d"],
33
- ["non-digit", "\\D"],
34
- ["word", "\\w"],
35
- ["non-word", "\\W"],
36
- ["space", "\\s"],
37
- ["non-space", "\\S"],
38
- ["start", "^"],
39
- ["end", "$"],
40
- ["word boundary", "\\b"],
41
- ["non-word boundary", "\\B"],
42
- ["positive lookahead", "(?=a)"],
43
- ["negative lookahead", "(?!a)"],
44
- ["positive lookbehind", "(?<=a)"],
45
- ["negative lookbehind", "(?<!a)"],
46
- ["unbounded lookbehind", "(?<=a+)b"],
47
- ["lookbehind capture", "(?<=(a))\\1"],
48
- ["numeric backreference", "(a)\\1"],
49
- ["forward backreference", "\\1(a)"],
50
- ["named backreference", "(?<word>a)\\k<word>"],
51
- ["unset capture", "(?:(a)|b)\\1"],
52
- ["alternation", "(?:a|b)"],
53
- ["empty group", "(?:)"],
54
- ["add i", "(?i:a)"],
55
- ["remove i", "(?-i:a)"],
56
- ["add s", "(?s:.)"],
57
- ["remove s", "(?-s:.)"],
58
- ["add m", "(?m:^a$)"],
59
- ["remove m", "(?-m:^a$)"],
60
- ["Unicode property", "\\p{Letter}"],
61
- ["negated Unicode property", "\\P{ASCII}"],
62
- ] as const;
63
-
64
- export const MATRIX_QUANTIFIERS = ["", "?", "*", "+", "*?", "+?", "{0}", "{2}", "{1,3}?"] as const;
65
- export const MATRIX_CONTEXTS = ["bare", "sequence", "alternative", "capture", "OR query"] as const;
66
-
67
- export const MATRIX_IGNORE_CASE = [false, true] as const;
68
-
69
- export const MATRIX_INPUTS = [
70
- ["empty", Buffer.alloc(0)],
71
- ["LF", Buffer.from("a\nb\nab\naa\nxay\nZ\n1\n8\n_\nk\ns\nA\nB\nK\nS\n.\n")],
72
- ["CRLF", Buffer.from("a\r\nb\r\nab\r\naa\r\nxay\r\nZ\r\n")],
73
- ["empty lines", Buffer.from("\n\r\n\n")],
74
- ["Unicode", Buffer.from("é\nÉ\nΣ\nσ\nς\nK\nſ\n😀\n😀😀\nx😀y\n")],
75
- ["standalone CR", Buffer.from("a\rb\r\r\nZ\r")],
76
- ["BOM and separators", Buffer.from("\uFEFFa\u2028b\u2029Z\n")],
77
- ["controls", Buffer.from("\t\f\v\x01 \n")],
78
- [
79
- "malformed bytes",
80
- Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a, 0xc3, 0x28, 0x0a, 0xed, 0xa0, 0x80]),
81
- ],
82
- ["literal U+FFFD", Buffer.from("a\uFFFDb\n\uFFFD\n")],
83
- ["unterminated", Buffer.from("ab")],
84
- ["mixed boundaries", Buffer.from("aa\r\nab\nxay\rZ\n\u2028\u2029😀")],
85
- ] as const;
86
-
87
- export interface MatrixCase {
88
- readonly syntax: string;
89
- readonly quantifier: string;
90
- readonly context: (typeof MATRIX_CONTEXTS)[number];
91
- readonly query: GrepQuery;
92
- }
93
-
94
- export function* matrixCases(): Generator<MatrixCase> {
95
- for (const [syntax, atom] of MATRIX_SYNTAX) {
96
- for (const quantifier of MATRIX_QUANTIFIERS) {
97
- const part = `(?:${atom})${quantifier}`;
98
- for (const context of MATRIX_CONTEXTS) {
99
- const patterns =
100
- context === "bare"
101
- ? [part]
102
- : context === "sequence"
103
- ? [`x${part}y`]
104
- : context === "alternative"
105
- ? [`(?:${part}|Z)`]
106
- : context === "capture"
107
- ? [`(${part})\\1`]
108
- : [part, "Z"];
109
- for (const ignoreCase of MATRIX_IGNORE_CASE) {
110
- for (const multiline of [false, true])
111
- yield {
112
- syntax,
113
- quantifier,
114
- context,
115
- query: { patterns, ignoreCase, multiline, literal: false },
116
- };
117
- }
118
- }
119
- }
120
- }
121
- }
122
-
123
- export function acceptsNative(query: GrepQuery): boolean {
124
- try {
125
- for (const pattern of query.patterns) new RegExp(pattern, query.ignoreCase ? "mi" : "m");
126
- return true;
127
- } catch (error) {
128
- if (error instanceof SyntaxError) return false;
129
- throw error;
130
- }
131
- }
132
-
133
- /** Match literal bytes directly, without relying on the candidate regex formatter or expanding products. */
134
- export function hasCandidateBytes(bytes: Buffer, prefilter: Prefilter): boolean {
135
- if (prefilter.kind === "all") return true;
136
- return prefilter.literals.some((literal) => {
137
- const positions = literal.map((chars) => chars.map((char) => Buffer.from(char)));
138
- for (let start = 0; start < bytes.length; start++) {
139
- let ends = new Set([start]);
140
- for (const variants of positions) {
141
- const next = new Set<number>();
142
- for (const end of ends)
143
- for (const variant of variants)
144
- if (bytes.subarray(end, end + variant.length).equals(variant))
145
- next.add(end + variant.length);
146
- ends = next;
147
- if (!ends.size) break;
148
- }
149
- if (ends.size) return true;
150
- }
151
- return false;
152
- });
153
- }
154
-
155
- /** Pair every syntax fragment with every other fragment, including independent OR-array entries. */
156
- export function* pairedMatrixCases(): Generator<{ readonly query: GrepQuery }> {
157
- for (const [, left] of MATRIX_SYNTAX) {
158
- for (const [, right] of MATRIX_SYNTAX) {
159
- for (const patterns of [
160
- [`(?:${left})(?:${right})`],
161
- [`(?:${left}|${right})`],
162
- [left, right],
163
- ]) {
164
- for (const ignoreCase of MATRIX_IGNORE_CASE) {
165
- for (const multiline of [false, true])
166
- yield { query: { patterns, ignoreCase, multiline, literal: false } };
167
- }
168
- }
169
- }
170
- }
171
- }
@@ -1,132 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { searchLines, searchText } from "./search.ts";
4
- import { unsupportedByHost } from "../testing/regex-host.testing.ts";
5
-
6
- const cases = [
7
- { name: "dot counts UTF-16 units", pattern: "^..$", source: "😀\na\nab\n", lines: [1, 3] },
8
- {
9
- name: "negated class counts UTF-16 units",
10
- pattern: "^[^x]{2}$",
11
- source: "😀\nab\nx😀\n",
12
- lines: [1, 2],
13
- },
14
- { name: "surrogate half in a class", pattern: "[😀]", source: "😀\nx\n", lines: [1] },
15
- {
16
- name: "repeated capture resets",
17
- pattern: "^(?:(a)|b)+\\1$",
18
- source: "ab\naba\naa\n",
19
- lines: [1, 3],
20
- },
21
- { name: "unbounded lookbehind", pattern: "(?<=a+)b", source: "aab\nb\n", lines: [1] },
22
- {
23
- name: "backwards capture evaluation",
24
- pattern: "(?<=(a)\\1)b",
25
- source: "ab\naab\n",
26
- lines: [1, 2],
27
- },
28
- {
29
- name: "case folding in a referenced capture",
30
- pattern: "^(é)\\1$",
31
- source: "éÉ\nÉé\nee\n",
32
- lines: [1, 2],
33
- ignoreCase: true,
34
- },
35
- {
36
- name: "CRLF normalized before backreference",
37
- pattern: "(a\\n)\\1",
38
- source: "a\r\na\nb\n",
39
- lines: [1, 2],
40
- multiline: true,
41
- },
42
- {
43
- name: "empty matches on consecutive empty lines",
44
- pattern: "(?=^$)",
45
- source: "\n\r\n\n",
46
- lines: [1, 2, 3],
47
- multiline: true,
48
- },
49
- {
50
- name: "match ends before next physical line",
51
- pattern: "a\\n",
52
- source: "a\r\nb\n",
53
- lines: [1],
54
- multiline: true,
55
- },
56
- { name: "line mode excludes separators", pattern: "\\n", source: "a\nb\n", lines: [] },
57
- { name: "empty file has no physical rows", pattern: "^$", source: "", lines: [] },
58
- {
59
- name: "terminal empty match stays on the unterminated physical line",
60
- pattern: "(?=$)",
61
- source: "ab",
62
- lines: [1],
63
- multiline: true,
64
- },
65
- {
66
- name: "scoped flags stay native",
67
- pattern: "^(?i:a)(?-i:b)$",
68
- source: "Ab\nAB\nab\n",
69
- lines: [1, 3],
70
- },
71
- ];
72
- for (const scenario of cases) {
73
- test(`JS search: ${scenario.name}`, { skip: unsupportedByHost([scenario.pattern], "m") }, () => {
74
- const result = searchText({
75
- source: scenario.source,
76
- query: {
77
- patterns: [scenario.pattern],
78
- literal: false,
79
- ignoreCase: scenario.ignoreCase ?? false,
80
- multiline: scenario.multiline ?? false,
81
- },
82
- limit: 100,
83
- });
84
- assert.deepEqual(
85
- result.lines.map(({ lineNumber }) => lineNumber),
86
- scenario.lines,
87
- );
88
- });
89
- }
90
-
91
- test("JS search: alternatives merge before the physical row limit", () => {
92
- const result = searchText({
93
- source: "zero\na\nb\nc\n",
94
- query: {
95
- patterns: ["c", "a\\nb", "(?=b)"],
96
- literal: false,
97
- ignoreCase: false,
98
- multiline: true,
99
- },
100
- limit: 2,
101
- });
102
- assert.deepEqual(result.lines, [
103
- { lineNumber: 2, column: 0 },
104
- { lineNumber: 3, column: 0 },
105
- ]);
106
- });
107
-
108
- test("JS search: columns retain UTF-16 positions inside supplementary characters", () => {
109
- const result = searchText({
110
- source: "😀x\n",
111
- query: { patterns: ["\\uDE00"], literal: false, ignoreCase: false, multiline: false },
112
- limit: 1,
113
- });
114
- assert.deepEqual(result.lines, [{ lineNumber: 1, column: 1 }]);
115
- });
116
-
117
- test("selected lines ending in CR → matching preserves the CR and uses 1-based positions", () => {
118
- const query = { patterns: ["\\r$"], literal: false, ignoreCase: false, multiline: false };
119
- assert.deepEqual(searchLines({ lines: "skip\na\r\nb\r\n", query, limit: 10 }), {
120
- lines: [
121
- { lineNumber: 2, column: 1 },
122
- { lineNumber: 3, column: 1 },
123
- ],
124
- });
125
- });
126
-
127
- test("selected lines exceed limit → matching rows truncate at the limit", () => {
128
- const query = { patterns: ["a", "b"], literal: true, ignoreCase: false, multiline: false };
129
- assert.deepEqual(searchLines({ lines: "skip\nxa\nb\na\n", query, limit: 1 }), {
130
- lines: [{ lineNumber: 2, column: 1 }],
131
- });
132
- });
@@ -1,52 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { createUtf8Decoder, decodeEditableText, Utf8DecodingError } from "./text.ts";
4
- import { HashlineError, TEXT_ERROR_MESSAGES } from "./errors.ts";
5
-
6
- test("decodeEditableText rejects malformed input instead of replacing bytes", () => {
7
- assert.throws(
8
- () => decodeEditableText(Uint8Array.from([0xc3, 0x28])),
9
- (error: unknown) =>
10
- error instanceof HashlineError && error.errorCode === "UNSUPPORTED_ENCODING",
11
- );
12
- });
13
-
14
- test("decodeEditableText preserves a leading BOM", () => {
15
- assert.equal(decodeEditableText(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
16
- });
17
-
18
- test("decodeEditableText rejects NUL bytes", () => {
19
- assert.throws(
20
- () => decodeEditableText(Uint8Array.from([0x61, 0, 0x62])),
21
- (error: unknown) => error instanceof HashlineError && error.errorCode === "UNSUPPORTED_TEXT",
22
- );
23
- });
24
-
25
- test("streaming UTF-8 decoders preserve a split BOM in strict and lossy modes", () => {
26
- for (const mode of ["strict", "lossy"] as const) {
27
- const decode = createUtf8Decoder(mode);
28
- assert.equal(decode(Uint8Array.from([0xef]), true), "");
29
- assert.equal(decode(Uint8Array.from([0xbb, 0xbf, 0x61]), true), "\ufeffa");
30
- assert.equal(decode(), "");
31
- }
32
- });
33
-
34
- test("lossy decoding replaces malformed bytes and flushes incomplete sequences at EOF", () => {
35
- const decode = createUtf8Decoder("lossy");
36
- assert.equal(decode(Uint8Array.from([0xef, 0xbb, 0xbf, 0xff, 0xc3, 0x28]), true), "\ufeff��(");
37
- assert.equal(decode(Uint8Array.from([0xf0]), true), "");
38
- assert.equal(decode(Uint8Array.from([0x9f]), true), "");
39
- assert.equal(decode(), "�");
40
- });
41
-
42
- test("strict decoding rejects malformed sequences and incomplete EOF → one encoding classification", () => {
43
- const isEncodingError = (error: unknown) =>
44
- error instanceof Utf8DecodingError &&
45
- error.errorCode === "UNSUPPORTED_ENCODING" &&
46
- error.message === TEXT_ERROR_MESSAGES.UNSUPPORTED_ENCODING &&
47
- error.cause === undefined;
48
- assert.throws(() => createUtf8Decoder("strict")(Uint8Array.from([0xff])), isEncodingError);
49
- const decode = createUtf8Decoder("strict");
50
- assert.equal(decode(Uint8Array.from([0xf0, 0x9f]), true), "");
51
- assert.throws(() => decode(), isEncodingError);
52
- });