-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
1402 lines (1204 loc) · 44.7 KB
/
parser.ts
File metadata and controls
1402 lines (1204 loc) · 44.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* github-mobile-reader - Diff to Logical Flow Parser v0.2
*
* Philosophy:
* - Summarize, don't explain
* - Be conservative when ambiguous
* - Show less rather than show wrong
*/
// Priority system for structure detection
export enum Priority {
CHAINING = 1,
CONDITIONAL = 2,
LOOP = 3,
FUNCTION = 4,
OTHER = 5,
}
export interface FlowNode {
type: "root" | "chain" | "condition" | "loop" | "function" | "call";
name: string;
children: FlowNode[];
depth: number;
priority: Priority;
}
export interface ParseResult {
root: FlowNode[];
rawCode: string;
removedCode: string;
}
export interface ReaderMarkdownMeta {
pr?: string;
commit?: string;
file?: string;
repo?: string;
}
export interface ClassNameChange {
component: string;
added: string[];
removed: string[];
}
export type SymbolKind =
| "component" // PascalCase React component
| "function" // regular function / async function
| "setup"; // simple variable assignment, hook call, short initializer
export interface SymbolDiff {
name: string;
kind: SymbolKind;
status: "added" | "removed" | "modified" | "moved";
addedLines: string[];
removedLines: string[];
}
interface DiffHunk {
header: string;
lines: Array<{ kind: "added" | "removed" | "context"; content: string }>;
}
export interface PropsChange {
added: string[];
removed: string[];
}
// ── Test file helpers ──────────────────────────────────────────────────────────
/**
* Returns true if the filename looks like a test/spec file.
*/
export function isTestFile(filename: string): boolean {
return /\.(test|spec)\.(js|jsx|ts|tsx)$/.test(filename);
}
/**
* Returns true if the filename looks like a config file (vitest, jest, etc.)
*/
export function isConfigFile(filename: string): boolean {
return /(?:vitest|jest|vite|tsconfig|eslint|prettier|babel|webpack|rollup)\.config\.(js|ts|cjs|mjs)$/.test(filename)
|| /\.config\.(js|ts|cjs|mjs)$/.test(filename);
}
interface TestCase {
suite: string; // describe block name
name: string; // it/test block name
}
/**
* Extract describe/it/test block names from raw diff lines.
*/
export function extractTestCases(addedLines: string[]): TestCase[] {
const results: TestCase[] = [];
let currentSuite = "";
for (const line of addedLines) {
const t = line.trim();
// describe('suite name', ...) or describe("suite name", ...)
const suiteMatch = t.match(/^describe\s*\(\s*['"`](.+?)['"`]/);
if (suiteMatch) {
currentSuite = suiteMatch[1];
continue;
}
// it('test name', ...) or test('test name', ...)
const caseMatch = t.match(/^(?:it|test)\s*\(\s*['"`](.+?)['"`]/);
if (caseMatch) {
results.push({ suite: currentSuite, name: caseMatch[1] });
}
}
return results;
}
/**
* Generate a readable markdown summary for a test file diff.
* Groups test cases by suite and lists them clearly.
*/
export function generateTestFileSummary(
addedLines: string[],
removedLines: string[],
): string[] {
const sections: string[] = [];
const addedCases = extractTestCases(addedLines);
const removedCases = extractTestCases(removedLines);
// Group added cases by suite
const suiteMap = new Map<string, string[]>();
for (const { suite, name } of addedCases) {
const key = suite || "(root)";
if (!suiteMap.has(key)) suiteMap.set(key, []);
suiteMap.get(key)!.push(name);
}
if (suiteMap.size > 0) {
for (const [suite, cases] of suiteMap) {
sections.push(`**테스트: \`${suite}\`**`);
cases.forEach((c) => sections.push(` + ${c}`));
sections.push("");
}
}
// Removed test cases
if (removedCases.length > 0) {
sections.push("**제거된 테스트**");
removedCases.forEach(({ suite, name }) => {
const label = suite ? `${suite} > ${name}` : name;
sections.push(` - ${label}`);
});
sections.push("");
}
return sections;
}
// ── JSX / Tailwind helpers ─────────────────────────────────────────────────────
export function isJSXFile(filename: string): boolean {
return /\.(jsx|tsx)$/.test(filename);
}
export function hasJSXContent(lines: string[]): boolean {
return lines.some(
(l) => /<[A-Z][A-Za-z]*[\s/>]/.test(l) || /return\s*\(/.test(l),
);
}
export function isClassNameOnlyLine(line: string): boolean {
return /^className=/.test(line.trim());
}
export function extractClassName(line: string): string | null {
// Static: className="flex items-center gap-2"
const staticMatch = line.match(/className="([^"]*)"/);
if (staticMatch) return staticMatch[1];
// Ternary: className={isDark ? "bg-gray-900" : "bg-white"}
const ternaryMatch = line.match(
/className=\{[^?]+\?\s*"([^"]*)"\s*:\s*"([^"]*)"\}/,
);
if (ternaryMatch) return `${ternaryMatch[1]} ${ternaryMatch[2]}`;
// Template literal: className={`base ${condition ? "a" : "b"}`}
const templateMatch = line.match(/className=\{`([^`]*)`\}/);
if (templateMatch) {
const raw = templateMatch[1];
const literals = raw.replace(/\$\{[^}]*\}/g, " ").trim();
const exprStrings = [...raw.matchAll(/"([^"]*)"/g)].map((m) => m[1]);
return [literals, ...exprStrings].filter(Boolean).join(" ");
}
return null;
}
export function extractComponentFromLine(line: string): string {
const tagMatch = line.match(/<([A-Za-z][A-Za-z0-9.]*)/);
if (tagMatch) return tagMatch[1];
return "unknown";
}
export function parseClassNameChanges(
addedLines: string[],
removedLines: string[],
): ClassNameChange[] {
const componentMap = new Map<
string,
{ added: Set<string>; removed: Set<string> }
>();
for (const line of addedLines.filter((l) => /className=/.test(l))) {
const cls = extractClassName(line);
const comp = extractComponentFromLine(line);
if (!cls) continue;
if (!componentMap.has(comp))
componentMap.set(comp, { added: new Set(), removed: new Set() });
cls
.split(/\s+/)
.filter(Boolean)
.forEach((c) => componentMap.get(comp)!.added.add(c));
}
for (const line of removedLines.filter((l) => /className=/.test(l))) {
const cls = extractClassName(line);
const comp = extractComponentFromLine(line);
if (!cls) continue;
if (!componentMap.has(comp))
componentMap.set(comp, { added: new Set(), removed: new Set() });
cls
.split(/\s+/)
.filter(Boolean)
.forEach((c) => componentMap.get(comp)!.removed.add(c));
}
const changes: ClassNameChange[] = [];
for (const [comp, { added, removed }] of componentMap) {
if (comp === "unknown") continue; // skip unresolvable components
const pureAdded = [...added].filter((c) => !removed.has(c));
const pureRemoved = [...removed].filter((c) => !added.has(c));
if (pureAdded.length === 0 && pureRemoved.length === 0) continue;
changes.push({ component: comp, added: pureAdded, removed: pureRemoved });
}
return changes;
}
export function renderStyleChanges(changes: ClassNameChange[]): string[] {
const lines: string[] = [];
for (const change of changes) {
lines.push(`**${change.component}**`);
if (change.added.length > 0) lines.push(` + ${change.added.join(" ")}`);
if (change.removed.length > 0)
lines.push(` - ${change.removed.join(" ")}`);
}
return lines;
}
// ── JSX Structure helpers ──────────────────────────────────────────────────────
export function isJSXElement(line: string): boolean {
const t = line.trim();
return /^<[A-Za-z]/.test(t) || /^<\/[A-Za-z]/.test(t);
}
export function isJSXClosing(line: string): boolean {
return /^<\/[A-Za-z]/.test(line.trim());
}
export function isJSXSelfClosing(line: string): boolean {
return /\/>[\s]*$/.test(line.trim());
}
export function extractJSXComponentName(line: string): string {
const trimmed = line.trim();
const closingMatch = trimmed.match(/^<\/([A-Za-z][A-Za-z0-9.]*)/);
if (closingMatch) return `/${closingMatch[1]}`;
const nameMatch = trimmed.match(/^<([A-Za-z][A-Za-z0-9.]*)/);
if (!nameMatch) return trimmed;
const name = nameMatch[1];
// Collect event handler props (onClick, onChange, etc.)
const eventProps: string[] = [];
for (const m of trimmed.matchAll(/\b(on[A-Z]\w+)=/g)) {
eventProps.push(m[1]);
}
return eventProps.length > 0 ? `${name}(${eventProps.join(", ")})` : name;
}
export function shouldIgnoreJSX(line: string): boolean {
const t = line.trim();
return (
isClassNameOnlyLine(t) ||
/^style=/.test(t) ||
/^aria-/.test(t) ||
/^data-/.test(t) ||
/^strokeLinecap=/.test(t) ||
/^strokeLinejoin=/.test(t) ||
/^strokeWidth=/.test(t) ||
/^viewBox=/.test(t) ||
/^fill=/.test(t) ||
/^stroke=/.test(t) ||
/^d="/.test(t) ||
t === "{" ||
t === "}" ||
t === "(" ||
t === ")" ||
t === "<>" ||
t === "</>" ||
/^\{\/\*/.test(t)
);
}
export function parseJSXToFlowTree(lines: string[]): FlowNode[] {
const roots: FlowNode[] = [];
const stack: Array<{ node: FlowNode; depth: number }> = [];
for (const line of lines) {
if (!isJSXElement(line)) continue;
if (shouldIgnoreJSX(line)) continue;
const depth = getIndentDepth(line);
if (isJSXClosing(line)) {
while (stack.length > 0 && stack[stack.length - 1].depth >= depth) {
stack.pop();
}
continue;
}
const name = extractJSXComponentName(line);
const selfClosing = isJSXSelfClosing(line);
const node: FlowNode = {
type: "call",
name,
children: [],
depth,
priority: Priority.OTHER,
};
while (stack.length > 0 && stack[stack.length - 1].depth >= depth) {
stack.pop();
}
if (stack.length === 0) {
roots.push(node);
} else {
stack[stack.length - 1].node.children.push(node);
}
if (!selfClosing) {
stack.push({ node, depth });
}
}
return roots;
}
/**
* Step 1: Filter diff lines — added (+) and removed (-) separately
*/
export function filterDiffLines(diffText: string): {
added: string[];
removed: string[];
} {
const lines = diffText.split("\n");
const added = lines
.filter(
(l) => l.startsWith("+") && !l.startsWith("+++") && l.trim() !== "+",
)
.map((l) => l.substring(1));
const removed = lines
.filter(
(l) => l.startsWith("-") && !l.startsWith("---") && l.trim() !== "-",
)
.map((l) => l.substring(1));
return { added, removed };
}
/**
* Step 2: Normalize code — remove noise, preserve structure
*/
export function normalizeCode(lines: string[]): string[] {
return lines
.map((line) => {
let normalized = line;
normalized = normalized.replace(/\/\/.*$/, "");
normalized = normalized.replace(/\/\*.*?\*\//, "");
normalized = normalized.trim();
normalized = normalized.replace(/;$/, "");
return normalized;
})
.filter((line) => line.length > 0);
}
/**
* Step 3: Calculate indentation depth (2 spaces = 1 level)
*/
export function getIndentDepth(line: string): number {
const match = line.match(/^(\s*)/);
if (!match) return 0;
return Math.floor(match[1].length / 2);
}
/**
* Step 4: Detect chaining pattern (P1 — Highest Priority)
*/
export function isChaining(line: string, prevLine: string | null): boolean {
if (!prevLine) return false;
if (!line.trim().startsWith(".")) return false;
if (!prevLine.match(/[)\}]$/)) return false;
return true;
}
/**
* Step 5: Extract method name from chaining
*/
export function extractChainMethod(line: string): string {
const match = line.match(/\.(\w+)\(/);
if (match) return `${match[1]}()`;
return line.trim();
}
/**
* Step 6: Simplify callback arguments
*/
export function simplifyCallback(methodCall: string): string {
// .method(param => param.property)
const arrowMatch = methodCall.match(/(\w+)\((\w+)\s*=>\s*(\w+)\.(\w+)\)/);
if (arrowMatch) {
const [, method, param, , prop] = arrowMatch;
return `${method}(${param} → ${prop})`;
}
// .method(anything) → method(callback)
const callbackMatch = methodCall.match(/(\w+)\([^)]+\)/);
if (callbackMatch) return `${callbackMatch[1]}(callback)`;
return methodCall;
}
/**
* Step 7: Detect conditional (P2)
*/
export function isConditional(line: string): boolean {
return /^(if|else|switch)\s*[\(\{]/.test(line.trim());
}
/**
* Step 8: Detect loop (P3)
*/
export function isLoop(line: string): boolean {
return /^(for|while)\s*\(/.test(line.trim());
}
/**
* Step 9: Detect function declaration (P4)
*/
export function isFunctionDeclaration(line: string): boolean {
const t = line.trim();
return (
// function foo() / async function foo()
/^(async\s+)?function\s+\w+/.test(t) ||
// const foo = () => / const foo = async () => / const foo = async (x: T) =>
/^(const|let|var)\s+\w+\s*=\s*(async\s*)?\(/.test(t) ||
// const foo = function / const foo = async function
/^(const|let|var)\s+\w+\s*=\s*(async\s+)?function/.test(t)
);
}
/**
* Step 10: Lines that should not appear in the flow
*/
export function shouldIgnore(line: string): boolean {
const ignorePatterns = [
/^import\s+/,
/^export\s+/,
/^type\s+/,
/^interface\s+/,
/^console\./,
/^return$/,
/^throw\s+/,
];
return ignorePatterns.some((p) => p.test(line.trim()));
}
/**
* Step 11: Extract root identifier from a line
*/
export function extractRoot(line: string): string | null {
// const result = getData()
const assignMatch = line.match(/(?:const|let|var)\s+(\w+)\s*=\s*(\w+)/);
if (assignMatch) return assignMatch[2];
// getData()
const callMatch = line.match(/^(\w+)\(/);
if (callMatch) return `${callMatch[1]}()`;
// data.map()
const methodMatch = line.match(/^(\w+)\./);
if (methodMatch) return methodMatch[1];
return null;
}
/**
* Main parser: convert normalized lines → FlowNode tree
*/
export function parseToFlowTree(lines: string[]): FlowNode[] {
const roots: FlowNode[] = [];
let currentChain: FlowNode | null = null;
let prevLine: string | null = null;
let baseDepth = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (shouldIgnore(line)) {
prevLine = line;
continue;
}
const depth = getIndentDepth(lines[i]);
if (baseDepth === -1) baseDepth = depth;
const relativeDepth = depth - baseDepth;
// P1: chaining
if (isChaining(line, prevLine)) {
const method = extractChainMethod(line);
const simplified = simplifyCallback(method);
if (currentChain) {
const chainNode: FlowNode = {
type: "chain",
name: simplified,
children: [],
depth: relativeDepth,
priority: Priority.CHAINING,
};
let parent = currentChain;
while (
parent.children.length > 0 &&
parent.children[parent.children.length - 1].depth >= relativeDepth
) {
const last = parent.children[parent.children.length - 1];
if (last.children.length > 0) parent = last;
else break;
}
parent.children.push(chainNode);
}
prevLine = line;
continue;
}
// P4: function declaration — must be checked BEFORE extractRoot,
// because "const foo = async ..." would otherwise match extractRoot first.
if (isFunctionDeclaration(line)) {
const funcMatch = line.match(/(?:function|const|let|var)\s+(\w+)/);
roots.push({
type: "function",
name: funcMatch ? `${funcMatch[1]}()` : "function()",
children: [],
depth: relativeDepth,
priority: Priority.FUNCTION,
});
currentChain = null;
prevLine = line;
continue;
}
// New root / chain start
const root = extractRoot(line);
if (root) {
currentChain = {
type: "root",
name: root,
children: [],
depth: relativeDepth,
priority: Priority.CHAINING,
};
roots.push(currentChain);
} else if (isConditional(line)) {
const condMatch = line.match(/(if|else|switch)\s*\(([^)]+)\)/);
const condName = condMatch
? `${condMatch[1]} (${condMatch[2]})`
: line.trim();
roots.push({
type: "condition",
name: condName,
children: [],
depth: relativeDepth,
priority: Priority.CONDITIONAL,
});
currentChain = null;
} else if (isLoop(line)) {
roots.push({
type: "loop",
name: "loop",
children: [],
depth: relativeDepth,
priority: Priority.LOOP,
});
currentChain = null;
}
prevLine = line;
}
return roots;
}
/**
* Render flow tree as markdown lines
*/
export function renderFlowTree(nodes: FlowNode[], indent = 0): string[] {
const lines: string[] = [];
const prefix = indent === 0 ? "" : " ".repeat((indent - 1) * 4) + " └─ ";
for (const node of nodes) {
lines.push(prefix + node.name);
if (node.children.length > 0) {
lines.push(...renderFlowTree(node.children, indent + 1));
}
}
return lines;
}
/**
* Main entry: parse a raw diff string → ParseResult
*/
export function parseDiffToLogicalFlow(diffText: string): ParseResult {
const { added, removed } = filterDiffLines(diffText);
const normalizedAdded = normalizeCode(added);
const flowTree = parseToFlowTree(normalizedAdded);
return {
root: flowTree,
rawCode: added.join("\n"),
removedCode: removed.join("\n"),
};
}
// ── Import change detection ────────────────────────────────────────────────────
/**
* Extract named imports from a single import line.
* e.g. `import { foo, bar } from 'baz'` → ['foo', 'bar']
* e.g. `import DefaultExport from 'baz'` → ['DefaultExport']
*/
function extractImportNames(line: string): string[] {
const named = line.match(/\{\s*([^}]+)\s*\}/);
if (named) {
return named[1].split(",").map((s) => s.trim().replace(/\s+as\s+\w+/, "")).filter(Boolean);
}
const def = line.match(/^import\s+(\w+)\s+from/);
if (def) return [def[1]];
return [];
}
/**
* Detect newly imported and removed imported names between added/removed lines.
*/
export function extractImportChanges(
addedLines: string[],
removedLines: string[],
): { added: string[]; removed: string[] } {
const getImports = (lines: string[]) =>
lines
.filter((l) => l.trim().startsWith("import "))
.flatMap(extractImportNames);
const addedImports = new Set(getImports(addedLines));
const removedImports = new Set(getImports(removedLines));
return {
added: [...addedImports].filter((i) => !removedImports.has(i)),
removed: [...removedImports].filter((i) => !addedImports.has(i)),
};
}
// ── Function parameter change detection ───────────────────────────────────────
/**
* Extract parameter names from a function declaration line.
* Handles: function foo(a, b, c), const foo = (a, b) =>, const foo = async (a: T, b: T) =>
*/
function extractParams(line: string): string[] {
// Match the first (...) group
const m = line.match(/\(\s*([^)]*)\s*\)/);
if (!m || !m[1].trim()) return [];
return m[1]
.split(",")
.map((p) =>
p
.trim()
.replace(/:.*$/, "") // strip type annotation
.replace(/=.*$/, "") // strip default value
.replace(/^\.\.\./,"") // strip rest ...
.trim(),
)
.filter(Boolean);
}
/**
* Compare function parameters between added and removed declaration lines.
* Returns { added, removed } param names.
*/
export function extractParamChanges(
addedLines: string[],
removedLines: string[],
): { added: string[]; removed: string[] } {
const DECL_RE = /^(?:export\s+)?(?:async\s+)?(?:function\s+\w+|(?:const|let|var)\s+\w+\s*=\s*(?:async\s*)?\()/;
const getParams = (lines: string[]): Set<string> => {
const result = new Set<string>();
for (const line of lines) {
if (DECL_RE.test(line.trim())) {
extractParams(line).forEach((p) => result.add(p));
}
}
return result;
};
const addedParams = getParams(addedLines);
const removedParams = getParams(removedLines);
return {
added: [...addedParams].filter((p) => !removedParams.has(p)),
removed: [...removedParams].filter((p) => !addedParams.has(p)),
};
}
// ── Shared symbol detection regexes ───────────────────────────────────────────
// Matches lowercase functions AND ALL_CAPS export functions (e.g. DELETE, GET, POST)
const FUNC_RE =
/^(?:export\s+)?(?:async\s+)?function\s+(\w+)|^(?:export\s+)?(?:const|let|var)\s+([a-z]\w+)\s*=\s*(?:async\s+)?\(?|^(?:export\s+)?(?:const|let|var)\s+([a-z]\w+)\s*=\s*[a-z]\w+\s*[<(]/;
// React component: PascalCase (uppercase first, then at least one lowercase)
const COMPONENT_RE =
/^(?:export\s+)?(?:default\s+)?(?:function|const)\s+([A-Z][a-z][A-Za-z0-9]*)/;
// A declaration line that opens a function body on the same line
const FUNCTION_BODY_RE = /(?:=>\s*\{|(?:async\s+)?function\s*\w*\s*\()|\)\s*\{/;
// Arrow function assigned to a const where the body starts on the NEXT line
// e.g. `const foo = () => someCall(` — multiline, no { on this line
const ARROW_MULTILINE_RE = /^(?:export\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\(/;
function extractSymbolFromLine(line: string): string | undefined {
const trimmed = line.trim();
const cm = trimmed.match(COMPONENT_RE) || trimmed.match(FUNC_RE);
if (cm) {
const name = cm[1] || cm[2] || cm[3];
if (name) return name;
}
return undefined;
}
/**
* Classify a symbol declaration line as component, function, or setup.
* - component: PascalCase (React component)
* - function: function keyword, arrow with body, or multiline arrow assignment
* - setup: simple one-liner assignment / hook call (e.g. const x = useRouter())
*/
function classifySymbol(declarationLine: string): SymbolKind {
const trimmed = declarationLine.trim();
// PascalCase → component
if (COMPONENT_RE.test(trimmed)) return "component";
// `function foo` / `async function foo` keyword → function
if (/^(?:export\s+)?(?:async\s+)?function\s+/.test(trimmed)) return "function";
// Arrow function with body opener on same line → function
if (FUNCTION_BODY_RE.test(trimmed)) return "function";
// `const foo = (` or `const foo = async (` — multiline arrow, body on next line
if (ARROW_MULTILINE_RE.test(trimmed)) return "function";
// Assigned arrow without parens: `const foo = () => someExpr(` (no {)
// Only treat as function if it calls something non-trivially (has parens)
if (/=\s*(?:async\s+)?\(\)\s*=>\s*\w+\s*\(/.test(trimmed)) return "function";
// Everything else: const router = useRouter(), const x = 'value', etc.
return "setup";
}
// ── Hunk parsing & symbol attribution ─────────────────────────────────────────
/**
* Split raw diff text into structured hunks.
* Each hunk has a header line and classified lines (added/removed/context).
*/
export function parseDiffHunks(diffText: string): DiffHunk[] {
const hunks: DiffHunk[] = [];
let current: DiffHunk | null = null;
for (const line of diffText.split("\n")) {
if (line.startsWith("@@")) {
current = { header: line, lines: [] };
hunks.push(current);
continue;
}
if (!current) continue;
// Skip diff file headers
if (line.startsWith("+++") || line.startsWith("---")) continue;
if (line.startsWith("+")) {
current.lines.push({ kind: "added", content: line.substring(1) });
} else if (line.startsWith("-")) {
current.lines.push({ kind: "removed", content: line.substring(1) });
} else {
current.lines.push({ kind: "context", content: line });
}
}
return hunks;
}
/**
* Extract the trailing function/component name from a @@ hunk header.
* e.g. "@@ -10,5 +10,8 @@ function UserProfileModal(" → "UserProfileModal"
*/
function extractSymbolFromHunkHeader(header: string): string | undefined {
const m = header.match(/@@[^@]*@@\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s+(\w+)|(?:const|let|var)\s+(\w+))/);
if (m) return m[1] || m[2];
return undefined;
}
/**
* Attribute each added/removed line to the nearest enclosing symbol (function/component).
* Uses hunk headers and line-by-line declaration scanning.
*/
export function attributeLinesToSymbols(hunks: DiffHunk[]): SymbolDiff[] {
const symbolMap = new Map<string, { added: string[]; removed: string[]; kind: SymbolKind }>();
const getOrCreate = (name: string, kind: SymbolKind) => {
if (!symbolMap.has(name)) symbolMap.set(name, { added: [], removed: [], kind });
return symbolMap.get(name)!;
};
for (const hunk of hunks) {
let currentSymbol = extractSymbolFromHunkHeader(hunk.header) ?? "module-level";
let currentKind: SymbolKind = "function";
for (const { kind, content } of hunk.lines) {
// Update current symbol when a declaration is encountered (context or added)
if (kind !== "removed") {
const declared = extractSymbolFromLine(content);
if (declared) {
currentSymbol = declared;
currentKind = classifySymbol(content);
}
}
if (kind === "added") getOrCreate(currentSymbol, currentKind).added.push(content);
else if (kind === "removed") getOrCreate(currentSymbol, currentKind).removed.push(content);
}
}
const results: SymbolDiff[] = [];
for (const [name, { added, removed, kind }] of symbolMap) {
if (added.length === 0 && removed.length === 0) continue;
// If all removed lines are comments or blank, don't classify as "removed"
const meaningfulRemoved = removed.filter(
(l) => l.trim().length > 0 && !l.trim().startsWith("//") && !l.trim().startsWith("/*") && !l.trim().startsWith("*"),
);
const effectiveAdded = added.length > 0;
const effectiveRemoved = meaningfulRemoved.length > 0;
results.push({
name,
kind,
status: effectiveAdded && effectiveRemoved ? "modified"
: effectiveAdded ? "added"
: effectiveRemoved ? "removed"
: "modified", // only comment changes → treat as modified (minor)
addedLines: added,
removedLines: removed,
});
}
return results;
}
// ── Props / behavior analysis ──────────────────────────────────────────────────
/**
* Detect TypeScript prop/interface changes from added vs removed lines.
*/
export function extractPropsChanges(
addedLines: string[],
removedLines: string[],
): PropsChange {
// Match interface member lines: " propName?: SomeType;"
const MEMBER_RE = /^\s*(\w+\??)\s*:\s*(.+?)(?:;|,)?\s*$/;
const extractMembers = (lines: string[]): Set<string> => {
const members = new Set<string>();
for (const line of lines) {
const m = line.match(MEMBER_RE);
if (m) members.add(`${m[1]}: ${m[2].trim()}`);
}
return members;
};
const addedMembers = extractMembers(addedLines);
const removedMembers = extractMembers(removedLines);
return {
added: [...addedMembers].filter((m) => !removedMembers.has(m)),
removed: [...removedMembers].filter((m) => !addedMembers.has(m)),
};
}
/**
* Summarize behavioral signals from a set of diff lines.
* Returns at most 8 human-readable bullet strings.
*/
function buildBehaviorSummary(lines: string[], mode: "added" | "removed" = "added"): string[] {
const summary: string[] = [];
const normalized = normalizeCode(lines);
for (const line of normalized) {
// React state: const [x, setX] = useState(initialValue)
const stateMatch = line.match(/const\s+\[(\w+),\s*set\w+\]\s*=\s*useState\s*\(([^)]*)\)/);
if (stateMatch) {
const init = stateMatch[2].trim();
const initLabel = init.length > 0 && init !== "" ? ` = ${init}` : "";
const label = mode === "removed"
? `state \`${stateMatch[1]}\` 제거`
: `state \`${stateMatch[1]}\`${initLabel} 추가`;
summary.push(label);
continue;
}
// useEffect with deps array
const effectMatch = line.match(/useEffect\s*\(\s*(?:async\s*)?\(\s*\)\s*=>\s*\{?|useEffect\s*\(\s*\(\s*\)\s*=>/);
if (effectMatch) {
// Try to find deps on same line: useEffect(() => { ... }, [dep1, dep2])
const depsMatch = line.match(/useEffect[^,]*,\s*\[([^\]]*)\]/);
if (depsMatch) {
const deps = depsMatch[1].trim();
summary.push(deps.length === 0 ? `\`useEffect\` — 마운트 시 1회 실행` : `\`useEffect\` — [${deps}] 변경 시 실행`);
} else {
summary.push(`\`useEffect\` 등록`);
}
continue;
}
// Hook calls assigned to variable: const x = useSomeHook(arg)
const hookAssignMatch = line.match(/const\s+(\w+)\s*=\s*(use[A-Z]\w+)\s*\(([^)]*)\)/);
if (hookAssignMatch) {
const arg = hookAssignMatch[3].trim();
const argLabel = arg.length > 0 && arg.length <= 30 ? `(${arg})` : "";
summary.push(`\`${hookAssignMatch[1]}\` ← \`${hookAssignMatch[2]}${argLabel}\``);
continue;
}
// Hook calls (bare, not assigned): useCallback(...), useMemo(...)
const hookMatch = line.match(/^\s*(use[A-Z]\w+)\s*\(/);
if (hookMatch) { summary.push(`\`${hookMatch[1]}\` 호출`); continue; }
// Async/await calls: const x = await foo.bar(arg)
const awaitAssignMatch = line.match(/(?:const|let|var)\s+(\w+)\s*=\s*await\s+([\w.]+)\s*\(([^)]{0,40})\)/);
if (awaitAssignMatch) {
const arg = awaitAssignMatch[3].trim();
const argLabel = arg.length > 0 && arg.length <= 25 ? `(${arg})` : "()";
summary.push(`\`${awaitAssignMatch[1]}\` ← await \`${awaitAssignMatch[2]}${argLabel}\``);
continue;
}
// Bare await call: await foo(arg)
const awaitMatch = line.match(/^await\s+([\w.]+)\s*\(([^)]{0,40})\)/);
if (awaitMatch) {
const arg = awaitMatch[2].trim();
const argLabel = arg.length > 0 && arg.length <= 25 ? `(${arg})` : "()";
summary.push(`await \`${awaitMatch[1]}${argLabel}\``);
continue;
}
// Conditionals
const condMatch = line.match(/^(if|else if)\s*\((.{1,60})\)/);
if (condMatch) { summary.push(`조건: \`${condMatch[2].trim()}\``); continue; }
// Error handling
const catchMatch = line.match(/^catch\s*\(\s*(\w+)\s*\)/);
if (catchMatch) { summary.push(`에러 처리 (catch \`${catchMatch[1]}\`)`); continue; }