codehere 2.1.0-rc.0 → 2.1.0-rc.3

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.
package/src/noskip.js ADDED
@@ -0,0 +1,585 @@
1
+ // Changed expected values, replaced tests and dropped test cases, read from a diff of test files.
2
+ // Ported from noskip 1.2.0, src/rules/tests.js and src/util.js (github.com/DariusHQ/noskip), with the
3
+ // findings reworded for Codehere and the file model built from a unified diff plus the files as they are now.
4
+ // Only the finish check runs this: it is the one caller that can read the files.
5
+ //
6
+ // MIT License
7
+ //
8
+ // Copyright (c) 2026 DariusHQ
9
+ //
10
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ // of this software and associated documentation files (the "Software"), to deal
12
+ // in the Software without restriction, including without limitation the rights
13
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ // copies of the Software, and to permit persons to whom the Software is
15
+ // furnished to do so, subject to the following conditions:
16
+ //
17
+ // The above copyright notice and this permission notice shall be included in all
18
+ // copies or substantial portions of the Software.
19
+ //
20
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ // SOFTWARE.
27
+
28
+ // ---------- helpers (noskip src/util.js) ----------
29
+
30
+ const normalizeLine = (text) => text.trim().replace(/\s+/g, ' ');
31
+ const isCommentLine = (text) => /^\s*(?:\/\/|\/\*|\*(?:\s|\/|$)|<!--|#(?![[!]|pragma\b|if\b|include\b|define\b|expect\b|require\b))/.test(text);
32
+ const truncate = (text, max = 120) => {
33
+ const t = text.trim();
34
+ return t.length > max ? t.slice(0, max - 1) + '…' : t;
35
+ };
36
+
37
+ function splitArgs(text) {
38
+ const out = [];
39
+ let depth = 0;
40
+ let quote = null;
41
+ let cur = '';
42
+ for (let i = 0; i < text.length; i++) {
43
+ const ch = text[i];
44
+ if (quote) {
45
+ cur += ch;
46
+ if (ch === '\\') cur += text[++i] ?? '';
47
+ else if (ch === quote) quote = null;
48
+ continue;
49
+ }
50
+ if (ch === '"' || ch === "'" || ch === '`') (quote = ch), (cur += ch);
51
+ else if (ch === '(' || ch === '[' || ch === '{') depth++, (cur += ch);
52
+ else if (ch === ')' || ch === ']' || ch === '}') depth--, (cur += ch);
53
+ else if (ch === ',' && depth === 0) out.push(cur.trim()), (cur = '');
54
+ else cur += ch;
55
+ }
56
+ if (cur.trim()) out.push(cur.trim());
57
+ return out;
58
+ }
59
+
60
+ function matchParen(text, open) {
61
+ let depth = 0;
62
+ let quote = null;
63
+ for (let i = open; i < text.length; i++) {
64
+ const ch = text[i];
65
+ if (quote) {
66
+ if (ch === '\\') i++;
67
+ else if (ch === quote) quote = null;
68
+ continue;
69
+ }
70
+ if (ch === '"' || ch === "'" || ch === '`') quote = ch;
71
+ else if (ch === '(') depth++;
72
+ else if (ch === ')' && --depth === 0) return i;
73
+ }
74
+ return -1;
75
+ }
76
+
77
+ // ---------- test names (noskip src/rules/tests.js) ----------
78
+
79
+ const EXT_LANG = {
80
+ js: 'js', jsx: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', mts: 'js', cts: 'js', vue: 'js', svelte: 'js', astro: 'js',
81
+ py: 'py', pyi: 'py', go: 'go', rs: 'rs', java: 'java', kt: 'java', kts: 'java', groovy: 'java', scala: 'java', cs: 'cs',
82
+ rb: 'rb', php: 'php', swift: 'swift', dart: 'dart', c: 'c', cc: 'c', cpp: 'c', cxx: 'c', h: 'c', hh: 'c', hpp: 'c', hxx: 'c', ex: 'ex', exs: 'ex',
83
+ };
84
+ const languageOf = (p) => EXT_LANG[(/\.([^./]+)$/.exec(p) || [])[1]?.toLowerCase()] ?? null;
85
+
86
+ const STR = String.raw`(['"\x60])((?:\\.|(?!\1)[^\\])*)\1`;
87
+ const NAME_PATTERNS = {
88
+ js: [
89
+ {
90
+ re: new RegExp(
91
+ String.raw`\b(?:it|test|specify)(?:\s*\.\s*(?:only|skip|concurrent|sequential|failing|fails|todo|fixme|skipIf\([^)]*\)|runIf\([^)]*\)|each\s*(?:\([^)]*\)|\x60[^\x60]*\x60)))*\s*\(\s*` + STR,
92
+ 'g',
93
+ ),
94
+ pick: (m) => m[2],
95
+ },
96
+ ],
97
+ py: [{ re: /^[ \t]*(?:async[ \t]+)?def[ \t]+(test\w*)[ \t]*\(/gm }],
98
+ go: [{ re: /^func\s+(?:\([^)]*\)\s*)?((?:Test|Benchmark|Fuzz|Example)\w*)\s*\(/gm }, { re: /\bt\.Run\(\s*"((?:\\.|[^"\\])*)"/g }, { re: /\bname:\s*"((?:\\.|[^"\\])*)"/g }],
99
+ rs: [{ re: /#\[(?:[\w:]+::)?test\b[^\]]*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+(\w+)/g }],
100
+ java: [
101
+ { re: /@(?:Test|ParameterizedTest|RepeatedTest|TestFactory|TestTemplate)\b[^\n]*\n(?:\s*@[^\n]*\n)*\s*(?:(?:public|private|protected|internal|open|override|suspend|static|final)\s+)*(?:void\s+|fun\s+)?`?([^`(\n]+?)`?\s*\(/g },
102
+ { re: /\bvoid\s+(test\w+)\s*\(/g },
103
+ ],
104
+ cs: [{ re: /\[\s*(?:Fact|Theory|Test|TestMethod|TestCase|TestCaseSource|SkippableFact)\b[^\]]*\]\s*(?:\[[^\]]*\]\s*)*(?:(?:public|private|protected|internal|async|static|virtual|override)\s+)*[\w<>[\],.?]+\s+(\w+)\s*\(/g }],
105
+ rb: [{ re: new RegExp(String.raw`^\s*(?:it|specify|scenario|example|test)\s*\(?\s*` + STR, 'gm'), pick: (m) => m[2] }, { re: /^\s*def\s+(test_\w+)/gm }],
106
+ php: [{ re: /function\s+(test\w+)\s*\(/g }, { re: /(?:#\[Test\]|@test\b)[^]{0,200}?function\s+(\w+)\s*\(/g }, { re: new RegExp(String.raw`\b(?:it|test)\s*\(\s*` + STR, 'g'), pick: (m) => m[2] }],
107
+ swift: [{ re: /func\s+(test\w+)\s*\(/g }, { re: /@Test\b(?:\([^)]*\))?\s*(?:@\w+(?:\([^)]*\))?\s*)*func\s+(\w+)\s*\(/g }],
108
+ dart: [{ re: new RegExp(String.raw`\b(?:test|testWidgets)\s*\(\s*` + STR, 'g'), pick: (m) => m[2] }],
109
+ c: [{ re: /\b(?:TEST|TEST_F|TEST_P|TYPED_TEST)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/g, pick: (m) => `${m[1]}.${m[2]}` }, { re: /\bTEST_CASE\s*\(\s*"((?:\\.|[^"\\])*)"/g }],
110
+ ex: [{ re: /\btest\s+"((?:\\.|[^"\\])*)"/g }],
111
+ };
112
+
113
+ function extractTestNames(text, lang) {
114
+ const names = new Map();
115
+ if (!text) return names;
116
+ for (const { re, pick } of NAME_PATTERNS[lang] ?? []) {
117
+ re.lastIndex = 0;
118
+ for (const m of text.matchAll(re)) {
119
+ const name = (pick ? pick(m) : m[m.length - 1] ?? m[1])?.trim();
120
+ if (!name) continue;
121
+ const entry = names.get(name);
122
+ if (entry) entry.count++;
123
+ else names.set(name, { count: 1, index: m.index });
124
+ }
125
+ }
126
+ return names;
127
+ }
128
+
129
+ const NAME_STOPWORDS = new Set(['a', 'an', 'the', 'is', 'are', 'it', 'to', 'of', 'on', 'in', 'and', 'or', 'when', 'if', 'with', 'for', 'should', 'be', 'not', 'still', 'that', 'does', 'do', 'test']);
130
+ const nameTokens = (name) => new Set(name.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1 && !NAME_STOPWORDS.has(t)));
131
+
132
+ // Two test names describe the same behaviour: a test split or moved under a new name, not one that went.
133
+ function similarNames(a, b) {
134
+ const A = nameTokens(a);
135
+ const B = nameTokens(b);
136
+ if (!A.size || !B.size) return false;
137
+ let shared = 0;
138
+ for (const t of A) if (B.has(t)) shared++;
139
+ return shared >= 2 && shared / Math.min(A.size, B.size) >= 0.5;
140
+ }
141
+
142
+ // ---------- assertions ----------
143
+
144
+ const STRONG = new Set([
145
+ 'toBe', 'toEqual', 'toStrictEqual', 'toMatchObject', 'toHaveBeenCalledWith', 'toHaveBeenNthCalledWith',
146
+ 'toHaveBeenLastCalledWith', 'toHaveBeenCalledTimes', 'toHaveLength', 'toHaveProperty', 'toThrow', 'toThrowError',
147
+ 'toMatch', 'toContainEqual', 'toBeCloseTo', 'equal', 'equals', 'eql', 'eq', 'isEqualTo', 'containsExactly',
148
+ 'hasSize', 'isSameAs', 'assertEqual', 'assertEquals', 'assertSame', 'assertIs', 'assertDictEqual',
149
+ 'assertListEqual', 'assertCountEqual', 'assertAlmostEqual', 'assertRaises', 'assertStrictEqual', 'assert_equal',
150
+ 'assert_eq!', 'Equal', 'Equals', 'AreEqual', 'Same', 'Exactly', 'EqualValues', 'StrictEqual', 'deepEqual',
151
+ 'deepStrictEqual', 'strictEqual', 'XCTAssertEqual', 'EXPECT_EQ', 'ASSERT_EQ', 'to eq', 'to eql', 'to equal',
152
+ 'to match', 'to raise_error', '==',
153
+ ]);
154
+ const WEAK = new Set([
155
+ 'toBeDefined', 'toBeTruthy', 'toBeFalsy', 'toBeInstanceOf', 'toBeTypeOf', 'toHaveBeenCalled', 'not.toBeNull',
156
+ 'not.toBeUndefined', 'ok', 'exist', 'exists', 'isNotNull', 'isNotEmpty', 'isInstanceOf', 'assertTrue', 'assertFalse',
157
+ 'assertIsNotNone', 'assertIsInstance', 'assertIn', 'assertNotNull', 'assertNotNil', 'assert_not_nil', 'assert',
158
+ 'assert!', 'NotNil', 'NotNull', 'NotEmpty', 'True', 'IsNotNull', 'IsTrue', 'XCTAssertNotNil', 'XCTAssertTrue',
159
+ 'EXPECT_TRUE', 'ASSERT_TRUE', 'to be_truthy', 'to be_present', 'not_to be_nil', 'to_not be_nil', 'is not',
160
+ 'truthy',
161
+ ]);
162
+
163
+ const norm = (s) => normalizeLine(String(s ?? '')).replace(/;$/, '').replace(/\s*,\s*$/, '');
164
+
165
+ function parseExpectStyle(t, opener) {
166
+ const m = opener.exec(t);
167
+ if (!m) return null;
168
+ const open = m.index + m[0].length - 1;
169
+ const close = matchParen(t, open);
170
+ if (close < 0) return null;
171
+ const subject = t.slice(open + 1, close);
172
+ const rest = t.slice(close + 1).replace(/->/g, '.');
173
+ let mm = /^\s*((?:\.\s*(?:not|resolves|rejects|to|be|been|is|deep|own|nested|and|has|have)\s*)*)\.\s*(\w+)\s*\(/.exec(rest);
174
+ if (mm) {
175
+ const argOpen = mm[0].length - 1;
176
+ const argClose = matchParen(rest, argOpen);
177
+ const chain = mm[1].replace(/\s+/g, '').replace(/^\./, '');
178
+ const matcher = (chain ? chain + '.' : '') + mm[2];
179
+ const args = argClose > 0 ? rest.slice(argOpen + 1, argClose) : rest.slice(argOpen + 1);
180
+ return { kind: 'expect', subject: norm(subject), matcher, args: norm(args) };
181
+ }
182
+ mm = /^\s*\.\s*(to|not_to|to_not)\s+(\w+)\s*\(?(.*?)\)?\s*$/.exec(rest);
183
+ if (mm) return { kind: 'expect', subject: norm(subject), matcher: `${mm[1]} ${mm[2]}`, args: norm(mm[3]) };
184
+ return null;
185
+ }
186
+
187
+ const CALL_OPENER =
188
+ /(?:^|[^\w.$])((?:self\s*\.\s*|this\s*\.\s*|\$this\s*->\s*)?(?:assert[A-Z_]\w*|assert_\w+|assert_eq!|assert_ne!|assert!)|(?:assert|Assert|require)\s*\.\s*\w+|XCTAssert\w*|(?:EXPECT|ASSERT)_[A-Z_]+)\s*\(/;
189
+
190
+ function parseCallStyle(t) {
191
+ const m = CALL_OPENER.exec(t);
192
+ if (!m) return null;
193
+ const open = m.index + m[0].length - 1;
194
+ const close = matchParen(t, open);
195
+ if (close < 0) return null;
196
+ let fn = m[1].replace(/\s+/g, '').replace(/^(?:self\.|this\.|\$this->)/, '');
197
+ let args = splitArgs(t.slice(open + 1, close)).map(norm);
198
+ if (/^(?:assert|require)\./.test(fn) && /^[A-Z]/.test(fn.split('.')[1] ?? '') && args[0] === 't') args = args.slice(1); // Go testify
199
+ fn = fn.replace(/^(?:assert|Assert|require)\./, '');
200
+ return { kind: 'call', matcher: fn, args };
201
+ }
202
+
203
+ function parsePyAssert(t) {
204
+ const m = /^assert\s+(.+)$/.exec(t);
205
+ if (!m) return null;
206
+ const cond = splitArgs(m[1])[0] ?? '';
207
+ const op = /\s(==|!=|<=|>=|is not|is|not in|in)\s/.exec(cond);
208
+ if (!op) return { kind: 'py', subject: norm(cond), matcher: 'assert', args: '' };
209
+ const left = cond.slice(0, op.index);
210
+ const right = cond.slice(op.index + op[0].length);
211
+ if (op[1] === 'is not' && /^None$/.test(right.trim())) return { kind: 'py', subject: norm(left), matcher: 'is not', args: 'None' };
212
+ return { kind: 'py', subject: norm(left), matcher: op[1], args: norm(right) };
213
+ }
214
+
215
+ const KV = /^\s*(?:(?:const|let|var|val|final|auto|my)\s+)?["']?((?:want|wanted|expected|expect|exp|golden|answer)\w*)["']?\s*(?::=|=|:)\s*(.+?)\s*[,;]?\s*$/i;
216
+
217
+ function parseAssertion(text) {
218
+ const t = text.trim().replace(/;\s*$/, '');
219
+ if (!t || isCommentLine(t)) return null;
220
+ return (
221
+ parseExpectStyle(t, /\bexpect\s*\(/) ||
222
+ parseExpectStyle(t, /\bassertThat\s*\(/) ||
223
+ parseCallStyle(t) ||
224
+ parsePyAssert(t) ||
225
+ (() => {
226
+ const m = KV.exec(t);
227
+ return m ? { kind: 'kv', subject: m[1].toLowerCase(), matcher: 'kv', args: norm(m[2]) } : null;
228
+ })()
229
+ );
230
+ }
231
+
232
+ const LITERALISH = /^(?:-?\d[\d_.]*n?|'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`[^`$]*`|true|false|null|undefined|None|True|False|nil|\/.+\/[a-z]*|\{[^()]*\}|\[[^()]*\]|[A-Z][A-Z0-9_]+)$/;
233
+
234
+ // The expression with its literals blanked out: `count + 3` and `count + 4` share a shape.
235
+ const shapeOf = (s) => s.replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, 'S').replace(/\b\d+(?:\.\d+)?n?\b/g, '#');
236
+
237
+ // The expectation moved (`46` to `47`, `n + 3` to `n + 4`), as opposed to the expression computing the actual value.
238
+ const goalpostMoved = (before, after) => LITERALISH.test(before) || LITERALISH.test(after) || shapeOf(before) === shapeOf(after);
239
+
240
+ const OPPOSITES = new Map(
241
+ [
242
+ ['assertTrue', 'assertFalse'], ['assertEqual', 'assertNotEqual'], ['assertEquals', 'assertNotEquals'],
243
+ ['assertIs', 'assertIsNot'], ['assertIn', 'assertNotIn'], ['assertIsNone', 'assertIsNotNone'],
244
+ ['assertNull', 'assertNotNull'], ['assertSame', 'assertNotSame'], ['assertRegex', 'assertNotRegex'],
245
+ ['assertIsInstance', 'assertNotIsInstance'], ['assert_equal', 'refute_equal'], ['assert_nil', 'refute_nil'],
246
+ ['assert_eq!', 'assert_ne!'], ['equal', 'notEqual'], ['strictEqual', 'notStrictEqual'], ['deepEqual', 'notDeepEqual'],
247
+ ['deepStrictEqual', 'notDeepStrictEqual'], ['throws', 'doesNotThrow'], ['rejects', 'doesNotReject'],
248
+ ['match', 'doesNotMatch'], ['True', 'False'], ['Equal', 'NotEqual'], ['Nil', 'NotNil'], ['Error', 'NoError'],
249
+ ['Empty', 'NotEmpty'], ['Contains', 'NotContains'], ['Zero', 'NotZero'], ['IsTrue', 'IsFalse'],
250
+ ['AreEqual', 'AreNotEqual'], ['IsNull', 'IsNotNull'], ['XCTAssertTrue', 'XCTAssertFalse'],
251
+ ['XCTAssertEqual', 'XCTAssertNotEqual'], ['XCTAssertNil', 'XCTAssertNotNil'], ['EXPECT_TRUE', 'EXPECT_FALSE'],
252
+ ['ASSERT_TRUE', 'ASSERT_FALSE'], ['EXPECT_EQ', 'EXPECT_NE'], ['ASSERT_EQ', 'ASSERT_NE'],
253
+ ].flatMap(([a, b]) => [[a, b], [b, a]]),
254
+ );
255
+
256
+ function negated(a, b) {
257
+ const strip = (s) => {
258
+ const m = /^(?:!\s*|not\s+)(.+)$/.exec(s);
259
+ return m ? m[1].replace(/^\((.*)\)$/, '$1').trim() : null;
260
+ };
261
+ const unwrap = (s) => s.replace(/^\((.*)\)$/, '$1').trim();
262
+ return strip(a) === unwrap(b) || strip(b) === unwrap(a);
263
+ }
264
+
265
+ // `f(x)` to `f(x, opts)`: the same function, called with arguments added or dropped at the end.
266
+ function callArgsExtended(before, after) {
267
+ const call = (s) => {
268
+ const m = /^([\w$.]+)\s*\(/.exec(s);
269
+ if (!m) return null;
270
+ const close = matchParen(s, m[0].length - 1);
271
+ if (close !== s.length - 1) return null;
272
+ return { callee: m[1], args: splitArgs(s.slice(m[0].length, close)).map(norm).filter(Boolean) };
273
+ };
274
+ const b = call(before);
275
+ const a = call(after);
276
+ if (!b || !a || b.callee !== a.callee || b.args.length === a.args.length) return false;
277
+ const [short, long] = b.args.length < a.args.length ? [b.args, a.args] : [a.args, b.args];
278
+ return short.every((x, i) => x === long[i]);
279
+ }
280
+
281
+ // A removed assertion against an added one: null, or { type, what, from, to }.
282
+ // type 'weakened' or 'changed'; what says which change, for the finding's wording.
283
+ const pair = (type, what, from, to) => ({ type, what, from: truncate(from, 50), to: truncate(to, 50) });
284
+ function compareAssertions(r, a) {
285
+ if (r.kind === 'call' && a.kind === 'call') {
286
+ const showCall = (x) => `${x.matcher}(${x.args.join(', ')})`;
287
+ if (r.matcher === a.matcher && r.args.length === a.args.length && r.args.length >= 2) {
288
+ const diffs = [0, 1].filter((i) => r.args[i] !== a.args[i]);
289
+ if (diffs.length !== 1) return null;
290
+ const i = diffs[0];
291
+ if (goalpostMoved(r.args[i], a.args[i])) return pair('changed', 'expected', r.args[i], a.args[i]);
292
+ return callArgsExtended(r.args[i], a.args[i]) ? pair('changed', 'call', r.args[i], a.args[i]) : null;
293
+ }
294
+ if (r.matcher === a.matcher && r.args.length === 1 && a.args.length === 1 && negated(r.args[0], a.args[0])) return pair('changed', 'flipped', showCall(r), showCall(a));
295
+ if (OPPOSITES.get(r.matcher) === a.matcher && r.args.length === a.args.length && r.args.every((x, i) => x === a.args[i])) return pair('changed', 'flipped', showCall(r), showCall(a));
296
+ if (STRONG.has(r.matcher) && WEAK.has(a.matcher) && a.args.some((x) => r.args.slice(0, 2).includes(x))) return pair('weakened', 'weakened', `${r.matcher}(…)`, `${a.matcher}(…)`);
297
+ return null;
298
+ }
299
+ if (r.kind === 'py' && a.kind === 'py' && r.matcher === 'assert' && a.matcher === 'assert' && negated(r.subject, a.subject)) return pair('changed', 'flipped', `assert ${r.subject}`, `assert ${a.subject}`);
300
+ if (r.kind === a.kind && r.kind !== 'kv' && r.subject !== a.subject && r.matcher === a.matcher && r.args === a.args && callArgsExtended(r.subject, a.subject)) return pair('changed', 'call', r.subject, a.subject);
301
+ if (r.kind !== a.kind || r.subject === undefined || r.subject !== a.subject) return null;
302
+ if (r.kind === 'kv') return r.args === a.args || !goalpostMoved(r.args, a.args) ? null : pair('changed', 'expected', `${r.subject} ${r.args}`, `${a.subject} ${a.args}`);
303
+ if (r.matcher === a.matcher) {
304
+ if (r.args === a.args) return null;
305
+ if (a.args === '' && r.args !== '') return pair('weakened', 'weakened', `${r.matcher}(${truncate(r.args, 40)})`, `${a.matcher}()`);
306
+ return pair('changed', 'expected', r.args, a.args);
307
+ }
308
+ const strongOld = STRONG.has(r.matcher) || STRONG.has(r.matcher.replace(/^not\./, ''));
309
+ const weakNew = WEAK.has(a.matcher) || (r.kind === 'py' && (a.matcher === 'assert' || a.matcher === 'is not'));
310
+ const show = (x) => (x.kind === 'py' ? `assert ${x.subject}${x.matcher === 'assert' ? '' : ` ${x.matcher} ${truncate(x.args, 40)}`}` : `${x.matcher}(${truncate(x.args, 40)})`);
311
+ if (strongOld && weakNew) return pair('weakened', 'weakened', show(r), show(a));
312
+ return pair('changed', 'assertion', show(r), show(a));
313
+ }
314
+
315
+ // ---------- test tables (table-driven tests, parametrize lists, `for (x of [..])`) ----------
316
+
317
+ const STRING_SRC = String.raw`'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"`;
318
+ const LITERAL_SRC = String.raw`${STRING_SRC}|-?\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?n?|\b(?:true|false|null|undefined|None|True|False|nil)\b`;
319
+ const ROW_TOKEN = new RegExp(String.raw`(\s+)|((?:[A-Za-z_$][\w$]*|${STRING_SRC})\s*:(?!:))|(${LITERAL_SRC})|([[\](){},;])`, 'y');
320
+
321
+ // A line that is only data, such as `[1900, true],`, `(1900, True),`, `{ in: 5, want: 120 },` or `1900,`.
322
+ function dataRow(text) {
323
+ const t = text.trim();
324
+ if (!t || !(/^[[({]/.test(t) || /,$/.test(t))) return null;
325
+ const literals = [];
326
+ let shape = '';
327
+ let depth = 0;
328
+ ROW_TOKEN.lastIndex = 0;
329
+ while (ROW_TOKEN.lastIndex < t.length) {
330
+ const m = ROW_TOKEN.exec(t);
331
+ if (!m) return null;
332
+ if (m[1]) continue;
333
+ if (m[3]) {
334
+ literals.push(m[3]);
335
+ shape += 'L';
336
+ continue;
337
+ }
338
+ if (m[4] && '[({'.includes(m[4])) depth++;
339
+ if (m[4] && '])}'.includes(m[4]) && --depth < 0) return null; // the tail of a call: `{ name: 'X' });`
340
+ shape += (m[2] ?? m[4]).replace(/\s+/g, '');
341
+ }
342
+ // open brackets are the start of a multi-line value (`[true,`); a key with one value (`code: 1,`) is a property
343
+ if (depth !== 0 || !literals.length || (!/^[[({]/.test(t) && (literals.length > 1 || shape.includes(':')))) return null;
344
+ return { literals, shape };
345
+ }
346
+
347
+ const INLINE_LIST = new RegExp(String.raw`\[\s*((?:${LITERAL_SRC})(?:\s*,\s*(?:${LITERAL_SRC}))*)\s*,?\s*\]`, 'g');
348
+ function inlineLists(text) {
349
+ const lists = [];
350
+ const shape = text.replace(INLINE_LIST, (_, items) => {
351
+ lists.push(items.match(new RegExp(LITERAL_SRC, 'g')));
352
+ return '[L]';
353
+ });
354
+ return { lists, shape: normalizeLine(shape) };
355
+ }
356
+
357
+ // What is gone from big, if small is big with some items removed and nothing else.
358
+ function dropped(big, small) {
359
+ if (!small || small.length >= big.length) return null;
360
+ const gone = [];
361
+ let j = 0;
362
+ for (const item of big) {
363
+ if (j < small.length && small[j] === item) j++;
364
+ else gone.push(item);
365
+ }
366
+ return j === small.length ? gone : null;
367
+ }
368
+
369
+ // Items dropped from a list on one line whose rest is unchanged, and rows moved within their table. Whole rows
370
+ // that disappear from multi-line tables are not reported: tables shrink when features go, so that signal is noise.
371
+ function tableChanges(file) {
372
+ const out = [];
373
+ for (const hunk of file.hunks) {
374
+ const used = new Set();
375
+ for (const r of hunk.removed) {
376
+ if (parseAssertion(r.text) || dataRow(r.text)) continue;
377
+ const before = inlineLists(r.text);
378
+ if (!before.lists.length) continue;
379
+ const a = hunk.added.find((x) => !used.has(x.line) && inlineLists(x.text).shape === before.shape);
380
+ if (!a) continue;
381
+ used.add(a.line);
382
+ const after = inlineLists(a.text);
383
+ before.lists.forEach((items, i) => {
384
+ const gone = dropped(items, after.lists[i]);
385
+ if (gone) out.push({ type: 'changed', what: 'dropped', from: truncate(gone.join(', '), 40) });
386
+ });
387
+ }
388
+ }
389
+ if (!file.oldLines || !file.newLines) return out;
390
+ const key = (text) => normalizeLine(text).replace(/,$/, '');
391
+ const rowLines = (lines) => lines.filter((l) => dataRow(l.text) && !parseAssertion(l.text));
392
+ const table = (lines, at) => {
393
+ let start = at - 1;
394
+ let end = at - 1;
395
+ while (start > 0 && dataRow(lines[start - 1])) start--;
396
+ while (end < lines.length - 1 && dataRow(lines[end + 1])) end++;
397
+ return lines.slice(start, end + 1).map(key);
398
+ };
399
+ const addedRows = rowLines(file.added);
400
+ for (const r of rowLines(file.removed)) {
401
+ const a = addedRows.find((x) => key(x.text) === key(r.text));
402
+ if (!a) continue;
403
+ const before = table(file.oldLines, r.line);
404
+ const after = table(file.newLines, a.line);
405
+ const sorted = (list) => [...list].sort().join('\n');
406
+ if (before.join('\n') !== after.join('\n') && sorted(before) === sorted(after)) {
407
+ out.push({ type: 'changed', what: 'reordered', from: truncate(key(r.text), 50) });
408
+ break;
409
+ }
410
+ }
411
+ return out;
412
+ }
413
+
414
+ // ---------- the file model, from a unified diff and the files as they are now ----------
415
+
416
+ function parseDiff(diff) {
417
+ const files = [];
418
+ let f = null;
419
+ let h = null;
420
+ let oldLine = 0;
421
+ let newLine = 0;
422
+ let from = '';
423
+ for (const line of diff.split('\n')) {
424
+ if (line.startsWith('diff --git ')) {
425
+ f = null;
426
+ h = null;
427
+ continue;
428
+ }
429
+ if (line.startsWith('--- ') && !h) {
430
+ from = line.slice(4).replace(/^a\//, '');
431
+ continue;
432
+ }
433
+ if (line.startsWith('+++ ') && !h) {
434
+ const to = line.slice(4).replace(/^b\//, '');
435
+ f = { path: to === '/dev/null' ? from : to, status: from === '/dev/null' ? 'A' : to === '/dev/null' ? 'D' : 'M', hunks: [], removed: [], added: [] };
436
+ files.push(f);
437
+ continue;
438
+ }
439
+ const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
440
+ if (m && f) {
441
+ h = { oldStart: +m[1], newStart: +m[3], newCount: m[4] === undefined ? 1 : +m[4], removed: [], added: [], lines: [] };
442
+ f.hunks.push(h);
443
+ [oldLine, newLine] = [h.oldStart, h.newStart];
444
+ continue;
445
+ }
446
+ if (!h || line.startsWith('\\')) continue;
447
+ if (line.startsWith('-')) {
448
+ const r = { line: oldLine++, text: line.slice(1, 10001) }; // the patterns can take quadratic time on a long line
449
+ h.removed.push(r), f.removed.push(r), h.lines.push(line);
450
+ } else if (line.startsWith('+')) {
451
+ const a = { line: newLine++, text: line.slice(1, 10001) };
452
+ h.added.push(a), f.added.push(a), h.lines.push(line);
453
+ } else if (line.startsWith(' ')) oldLine++, newLine++, h.lines.push(line);
454
+ else h = null; // the end of this file's hunks
455
+ }
456
+ return files;
457
+ }
458
+
459
+ // The file before the change: the file as it is now with each hunk undone. Null if they do not match.
460
+ function undo(newLines, hunks) {
461
+ const old = [];
462
+ let cur = 0;
463
+ for (const h of hunks) {
464
+ const upto = h.newCount === 0 ? h.newStart : h.newStart - 1;
465
+ if (upto < cur || upto > newLines.length) return null;
466
+ while (cur < upto) old.push(newLines[cur++]);
467
+ for (const l of h.lines) {
468
+ if (l[0] === '-') old.push(l.slice(1));
469
+ else if (newLines[cur]?.replace(/\r$/, '') !== l.slice(1).replace(/\r$/, '')) return null;
470
+ else if (l[0] === ' ') old.push(newLines[cur++]);
471
+ else cur++;
472
+ }
473
+ }
474
+ while (cur < newLines.length) old.push(newLines[cur++]);
475
+ return old;
476
+ }
477
+
478
+ const OPTIONS_SKIP = /\b(?:it|test|describe|suite|specify)\s*\(\s*(['"`])((?:\\.|(?!\1).)*)\1\s*,\s*\{[^}]*\b(?:skip|todo)\b(?!\s*:\s*(?:false|null|undefined|0)\b)/;
479
+ const lineOfIndex = (text, index) => text.slice(0, index).split('\n').length;
480
+
481
+ // The changes, as { type: 'changed' | 'weakened' | 'replaced' | 'skipped', file, what, from, to }.
482
+ // isTestFile picks the test files; read(file) returns a file as it is now, or null.
483
+ export function testChanges(diff, { read, isTestFile }) {
484
+ const files = parseDiff(diff).filter((f) => isTestFile(f.path) && languageOf(f.path));
485
+ for (const f of files) {
486
+ const now = f.status === 'D' ? null : read(f.path);
487
+ f.newLines = now == null ? null : now.split('\n');
488
+ f.oldLines = f.status === 'A' ? [] : f.status === 'D' ? f.removed.map((r) => r.text) : f.newLines && undo(f.newLines, f.hunks);
489
+ f.newText = f.status === 'D' ? '' : f.newLines && f.newLines.join('\n');
490
+ f.oldText = f.oldLines && f.oldLines.join('\n');
491
+ }
492
+ const changes = [];
493
+
494
+ // Tests that went: moved to another file, replaced by a new one, or removed. Only replaced ones are reported
495
+ // here; a removed test is counted with the removed assertions, and a deleted file on its own.
496
+ const perFile = [];
497
+ const addedPool = new Map();
498
+ for (const file of files.filter((x) => x.oldText != null && x.newText != null)) {
499
+ const lang = languageOf(file.path);
500
+ const oldNames = extractTestNames(file.oldText, lang);
501
+ const newNames = extractTestNames(file.newText, lang);
502
+ const removed = [];
503
+ const added = [];
504
+ for (const [name, { count, index }] of oldNames) for (let i = newNames.get(name)?.count ?? 0; i < count; i++) removed.push({ name, index });
505
+ for (const [name, { count, index }] of newNames) {
506
+ const before = oldNames.get(name)?.count ?? 0;
507
+ for (let i = before; i < count; i++) added.push({ name, index });
508
+ if (count > before) addedPool.set(name, (addedPool.get(name) ?? 0) + (count - before));
509
+ }
510
+ perFile.push({ file, removed, added });
511
+ }
512
+ for (const entry of perFile) {
513
+ entry.removed = entry.removed.filter(({ name }) => {
514
+ const n = addedPool.get(name) ?? 0;
515
+ if (n === 0) return true;
516
+ addedPool.set(name, n - 1);
517
+ return false;
518
+ });
519
+ }
520
+ const removedIn = new Set();
521
+ const addedIn = (pred) => perFile.filter((e) => e.file.status !== 'D' && pred(e.file)).flatMap((e) => e.added.map((a) => ({ ...a, file: e.file })));
522
+ const take = (list, pick) => {
523
+ const i = list.findIndex((a) => (addedPool.get(a.name) ?? 0) > 0 && pick(a));
524
+ if (i < 0) return null;
525
+ const [hit] = list.splice(i, 1);
526
+ addedPool.set(hit.name, addedPool.get(hit.name) - 1);
527
+ return hit;
528
+ };
529
+ for (const { file, removed } of perFile) {
530
+ if (file.status === 'D') {
531
+ if (removed.length) removedIn.add(file.path);
532
+ continue;
533
+ }
534
+ const own = addedIn((x) => x === file);
535
+ const elsewhere = addedIn((x) => x !== file);
536
+ for (const r of removed) {
537
+ const replacement = take(own, () => true) ?? take(elsewhere, (a) => similarNames(r.name, a.name));
538
+ if (replacement) changes.push({ type: 'replaced', file: file.path, what: 'replaced', from: truncate(r.name, 50), to: truncate(replacement.name, 50), where: replacement.file === file ? null : replacement.file.path, line: lineOfIndex(file.newText, replacement.index) });
539
+ else removedIn.add(file.path);
540
+ }
541
+ }
542
+
543
+ // Assertions changed in place: each removed assertion against the first added one in its hunk that it matches.
544
+ for (const file of files) {
545
+ for (const hunk of file.hunks) {
546
+ if (!hunk.removed.length || !hunk.added.length) continue;
547
+ const rem = hunk.removed.map((r) => ({ ...r, a: parseAssertion(r.text) })).filter((x) => x.a);
548
+ const add = hunk.added.map((x) => ({ ...x, a: parseAssertion(x.text) })).filter((x) => x.a);
549
+ if (rem.length * add.length > 250000) continue; // a rewritten test file, not an edit; the other checks still read it
550
+ const used = new Set();
551
+ for (const r of rem) {
552
+ for (const a of add) {
553
+ if (used.has(a.line)) continue;
554
+ if (normalizeLine(r.text) === normalizeLine(a.text)) {
555
+ used.add(a.line);
556
+ break;
557
+ }
558
+ const cmp = compareAssertions(r.a, a.a);
559
+ if (!cmp) continue;
560
+ used.add(a.line);
561
+ changes.push({ ...cmp, file: file.path });
562
+ break;
563
+ }
564
+ }
565
+ }
566
+ }
567
+
568
+ // A skip option added to a test that already existed: test('name', { skip }, fn). New tests use the same
569
+ // option to declare what they need (`{ skip: !hasCrypto }`), so a test whose name is new does not count.
570
+ for (const file of files) {
571
+ if (languageOf(file.path) !== 'js' || file.oldText == null) continue;
572
+ const before = new Set(file.removed.map((r) => normalizeLine(r.text)));
573
+ for (const a of file.added) {
574
+ const m = OPTIONS_SKIP.exec(a.text);
575
+ if (m && !isCommentLine(a.text) && !before.has(normalizeLine(a.text)) && file.oldText.includes(m[2])) {
576
+ changes.push({ type: 'skipped', file: file.path, what: 'skipped', from: truncate(m[2], 50) });
577
+ break;
578
+ }
579
+ }
580
+ }
581
+
582
+ // Test data dropped or reordered, in files that lost no whole test.
583
+ for (const file of files) if (file.status === 'M' && !removedIn.has(file.path)) for (const c of tableChanges(file)) changes.push({ ...c, file: file.path });
584
+ return changes;
585
+ }