cuke-dedup 0.11.0

Static analysis for duplicate and reusable Cucumber step definitions
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
use super::*;
use crate::model::Rule;
use std::fs;
use std::path::PathBuf;

#[test]
fn control_flow_behavior_events_map_typescript_node_kinds_only() {
    use crate::model::{BehaviorEvent, ControlFlowOperation};

    let cases = [
        ("if_statement", ControlFlowOperation::If),
        ("switch_statement", ControlFlowOperation::Switch),
        ("for_statement", ControlFlowOperation::For),
        ("for_in_statement", ControlFlowOperation::ForIn),
        ("while_statement", ControlFlowOperation::While),
        ("do_statement", ControlFlowOperation::Do),
        ("return_statement", ControlFlowOperation::Return),
        ("throw_statement", ControlFlowOperation::Throw),
    ];

    for (node_kind, operation) in cases {
        let event = super::handler::control_flow_behavior_event(node_kind);
        assert_eq!(event, BehaviorEvent::ControlFlow(operation));
        assert_eq!(event.into_legacy(), node_kind);
    }

    let unknown = super::handler::control_flow_behavior_event("custom_statement");
    assert_eq!(
        unknown,
        BehaviorEvent::Legacy("custom_statement".to_owned())
    );
    assert_eq!(unknown.into_legacy(), "custom_statement");
}

fn extract_ts(source: &str) -> Vec<crate::model::StepDefinition> {
    extract(source, &file(SourceLanguage::TypeScript)).unwrap()
}

fn file(language: SourceLanguage) -> SourceFile {
    SourceFile {
        path: PathBuf::from("features/steps/example.ts"),
        language,
    }
}

#[test]
fn framework_entrypoints_preserve_duplicate_findings_and_attribution() {
    let directory = tempfile::tempdir().unwrap();
    let config = crate::config::Config::load(directory.path(), Default::default()).unwrap();
    for (module, framework) in [
        ("@cucumber/cucumber", Framework::CucumberJs),
        ("cucumber", Framework::CucumberJs),
        ("playwright-bdd", Framework::PlaywrightBdd),
        ("playwright-bdd/decorators", Framework::PlaywrightBdd),
        (
            "@badeball/cypress-cucumber-preprocessor",
            Framework::CypressCucumber,
        ),
        (
            "cypress-cucumber-preprocessor/steps",
            Framework::CypressCucumber,
        ),
        ("cypress-cucumber-preprocessor", Framework::Unknown),
        ("playwright-bdd/decorators-extra", Framework::Unknown),
        ("@cucumber/cucumber-extra", Framework::Unknown),
        ("@cucumber/cucumber/unknown", Framework::Unknown),
    ] {
        for binding in [
            format!("import {{ Given as Setup }} from '{module}';"),
            format!("const {{ Given: Setup }} = require('{module}');"),
        ] {
            let body = if module == "playwright-bdd/decorators" {
                "class Steps {
                    @Setup('same step') first() { firstAction(); }
                    @Setup('same step') second() { secondAction(); }
                }"
            } else {
                "Setup('same step', () => firstAction());
                 Setup('same step', () => secondAction());"
            };
            let definitions = extract_ts(&format!("{binding}\n{body}"));
            let supported = framework != Framework::Unknown;
            assert_eq!(
                definitions.len(),
                if supported { 2 } else { 0 },
                "{binding}"
            );
            assert!(
                definitions
                    .iter()
                    .all(|definition| definition.framework == framework),
                "{binding}"
            );
            let result = crate::analysis::analyze(definitions, vec![], &config).unwrap();
            assert_eq!(
                result
                    .findings
                    .iter()
                    .filter(|finding| finding.rule == Rule::DuplicateMatcher)
                    .count(),
                usize::from(supported),
                "{binding}",
            );
            if !supported {
                assert!(result.findings.is_empty(), "{binding}");
            }
        }
    }
}

#[test]
fn extracts_cucumber_import_alias_and_regex() {
    let source = r#"
import { Given as G, Then } from '@cucumber/cucumber';
G('a user named {string}', async (name: string) => {
  await createUser(name);
});
Then(/^the user exists$/, function () { expect(this.user).toBeTruthy(); });
"#;
    let definitions = extract(source, &file(SourceLanguage::TypeScript)).unwrap();
    assert_eq!(definitions.len(), 2);
    assert_eq!(definitions[0].registration, "Given");
    assert_eq!(definitions[0].normalized_matcher, "a user named {string}");
    assert_eq!(definitions[1].matcher_kind, MatcherKind::RegularExpression);
    assert_eq!(definitions[1].matcher, "^the user exists$");
}

#[test]
fn extracts_playwright_bdd_destructuring_alias() {
    let source = r#"
import { createBdd } from 'playwright-bdd';
const { Given: Setup, Then } = createBdd(test);
Setup(`a loaded page`, async ({ page }) => { await page.goto('/'); });
"#;
    let definitions = extract(source, &file(SourceLanguage::TypeScript)).unwrap();
    assert_eq!(definitions.len(), 1);
    assert_eq!(definitions[0].framework, Framework::PlaywrightBdd);
    assert_eq!(definitions[0].registration, "Given");
}

#[test]
fn extracts_cypress_cucumber_preprocessor_definitions() {
    let source = r#"
import { Given as Setup, Then } from '@badeball/cypress-cucumber-preprocessor';
Setup('a Cypress project', () => cy.visit('/'));
Then('the page is visible', () => cy.get('main').should('be.visible'));
"#;
    let definitions = extract(source, &file(SourceLanguage::TypeScript)).unwrap();
    assert_eq!(definitions.len(), 2);
    assert!(definitions
        .iter()
        .all(|definition| definition.framework == Framework::CypressCucumber));
}

#[test]
fn extracts_supported_legacy_cucumber_registration_modules_in_esm_and_cjs() {
    for (module, expected_framework) in [
        ("cucumber", Framework::CucumberJs),
        (
            "cypress-cucumber-preprocessor/steps",
            Framework::CypressCucumber,
        ),
    ] {
        for (syntax, matcher) in [
            (
                format!(
                    "import {{ Given as Setup }} from '{module}';\nSetup('esm {module}', () => work());"
                ),
                format!("esm {module}"),
            ),
            (
                format!(
                    "const legacy = require('{module}');\nlegacy.Given('cjs {module}', () => work());"
                ),
                format!("cjs {module}"),
            ),
        ] {
            let definitions = extract_ts(&syntax);
            assert_eq!(definitions.len(), 1, "{module}: {syntax}");
            assert_eq!(definitions[0].matcher, matcher);
            assert_eq!(definitions[0].registration, "Given");
            assert_eq!(definitions[0].framework, expected_framework);
        }
    }
}

#[test]
fn legacy_cypress_preprocessor_root_and_similar_prefixes_are_not_registration_modules() {
    for module in [
        "cypress-cucumber-preprocessor",
        "cypress-cucumber-preprocessor/steps-extra",
    ] {
        let source = format!(
            "import {{ Given as Setup }} from '{module}';\nSetup('not a registration export', () => work());"
        );
        assert!(extract_ts(&source).is_empty(), "{module}");
    }
}

#[test]
fn playwright_step_decorator_name_is_not_invented_for_other_framework_modules() {
    for source in [
        "import { Step } from '@cucumber/cucumber';\nStep('not exported', () => work());",
        "const { Step } = require('@badeball/cypress-cucumber-preprocessor');\nStep('not exported', () => work());",
    ] {
        assert!(extract_ts(source).is_empty(), "{source}");
    }

    assert!(extract_ts(
        "import { Fixture as Given } from 'playwright-bdd/decorators';\nGiven('not a step registration', () => work());"
    )
    .is_empty());
}

#[test]
fn extracts_playwright_bdd_method_decorators_with_aliases_and_options() {
    let source = r#"
import { Fixture, Given as Setup, Step } from 'playwright-bdd/decorators';

export class TodoSteps {
  @Fixture('ignored fixture metadata')
  page = {};

  @Setup('a prepared todo', { timeout: 1000 })
  async prepare({ page: localPage }) { await localPage.goto('/todos'); }

  @Step(`the todo is visible`)
  async verify({ page }) { await page.goto('/todos'); }
}
"#;

    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 2);
    assert_eq!(definitions[0].matcher, "a prepared todo");
    assert_eq!(definitions[0].registration, "Given");
    assert_eq!(definitions[1].matcher, "the todo is visible");
    assert_eq!(definitions[1].registration, "Step");
    assert!(definitions
        .iter()
        .all(|definition| definition.framework == Framework::PlaywrightBdd));
    assert!(definitions
        .iter()
        .all(|definition| definition.handler.comparable));
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert!(definitions[0]
        .handler
        .source_snippet
        .contains("localPage.goto"));
    assert!(!definitions[0].handler.source_snippet.contains("prepare"));
}

#[test]
fn extracts_playwright_bdd_method_decorators_from_cjs_namespaces() {
    let source = r#"
const decorators = require('playwright-bdd/decorators');
class WorkspaceSteps {
  @decorators.Given('a CJS decorator')
  async prepare() { await work(); }
}
"#;

    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 1);
    assert_eq!(definitions[0].matcher, "a CJS decorator");
    assert_eq!(definitions[0].registration, "Given");
    assert_eq!(definitions[0].framework, Framework::PlaywrightBdd);
}

#[test]
fn extracts_playwright_bdd_method_decorators_with_javascript_grammar() {
    let source = r#"
import { Given } from 'playwright-bdd/decorators';
class JavaScriptSteps {
  @Given('a JavaScript decorator')
  async prepare() { await work(); }
}
"#;
    for extension in ["js", "jsx"] {
        let source_file = SourceFile {
            path: PathBuf::from(format!("features/steps/example.{extension}")),
            language: SourceLanguage::JavaScript,
        };
        let extracted = extract_detailed(source, &source_file).unwrap();
        assert!(extracted.diagnostics.is_empty(), "{extension}");
        assert_eq!(extracted.definitions.len(), 1, "{extension}");
        assert_eq!(extracted.definitions[0].matcher, "a JavaScript decorator");
        assert_eq!(extracted.definitions[0].framework, Framework::PlaywrightBdd);
    }
}

#[test]
fn unsupported_cjs_destructured_exports_shadow_ambient_registration_names() {
    for source in [
        r#"
const { Fixture: Given } = require('playwright-bdd/decorators');
Given('not a decorator registration', () => work());
"#,
        r#"
const { unsupported: Given } = require('cypress-cucumber-preprocessor/steps');
Given('not a legacy Cypress registration', () => work());
"#,
    ] {
        assert!(extract_ts(source).is_empty(), "{source}");
    }
}

#[test]
fn call_and_decorator_registration_apis_are_not_interchangeable() {
    let decorator_as_call = r#"
import { Given } from 'playwright-bdd/decorators';
Given('not an ordinary registration', () => work());
"#;
    assert!(extract_ts(decorator_as_call).is_empty());

    let call_as_decorator = r#"
import { createBdd } from 'playwright-bdd';
const { Given } = createBdd();
class InvalidSteps {
  @Given('not a decorator registration')
  async prepare() { await work(); }
}
"#;
    assert!(extract_ts(call_as_decorator).is_empty());

    let cucumber_call_as_decorator = r#"
import { Given } from '@cucumber/cucumber';
class InvalidCucumberSteps {
  @Given('not a Cucumber decorator')
  prepare() { work(); }
}
"#;
    assert!(extract_ts(cucumber_call_as_decorator).is_empty());

    let unsupported_create_bdd_export = r#"
import { createBdd } from 'playwright-bdd';
const { Step } = createBdd();
Step('not exported by createBdd', () => work());
"#;
    assert!(extract_ts(unsupported_create_bdd_export).is_empty());
}

#[test]
fn project_reexports_preserve_playwright_decorator_registration_provenance() {
    let source = r#"
import { Setup } from './decorators';
class WorkspaceSteps {
  @Setup('a re-exported decorator')
  async prepare() { await work(); }
}
"#;
    let extracted = extract_in_project(
        &[(
            "decorators.ts",
            "export { Given as Setup } from 'playwright-bdd/decorators';\n",
        )],
        source,
    );
    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 1);
    assert_eq!(extracted.definitions[0].registration, "Given");
    assert_eq!(extracted.definitions[0].framework, Framework::PlaywrightBdd);
}

#[test]
fn dynamic_playwright_bdd_decorator_matchers_warn_without_inventing_definitions() {
    let source = r#"
import { Given } from 'playwright-bdd/decorators';
class DynamicSteps {
  @Given(computeMatcher())
  async prepare() { await work(); }
}
"#;
    let file = file(SourceLanguage::TypeScript);
    let extracted = extract_detailed(source, &file).unwrap();

    assert!(extracted.definitions.is_empty());
    assert!(extracted.diagnostics.iter().any(|diagnostic| diagnostic
        .message
        .contains("dynamic or unsupported step matcher")));
}

#[test]
fn decorated_stub_methods_keep_the_existing_trivial_handler_guard() {
    let source = r#"
import { Given, Then } from 'playwright-bdd/decorators';
class PendingSteps {
  @Given('a pending setup')
  async prepare() { await pending(); }

  @Then('a pending result')
  verify() { throw new Error('not implemented'); }
}
"#;
    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 2);
    assert!(definitions
        .iter()
        .all(|definition| definition.handler.trivial));
}

#[test]
fn decorated_method_fingerprints_include_runtime_declaration_semantics() {
    let source = r#"
import { Given, When, Then, Step } from 'playwright-bdd/decorators';
class RuntimeSemantics {
  @Given('async handler')
  async asyncHandler(value) { return work(value); }

  @When('sync handler')
  syncHandler(value) { return work(value); }

  @Then('first default')
  withFirstDefault(value = first()) { return work(value); }

  @Step('second default')
  withSecondDefault(value = second()) { return work(value); }

  @Given('renamed default one')
  renamedDefaultOne(value = seed()) { return work(value); }

  @When('renamed default two')
  renamedDefaultTwo(renamed = seed()) { return work(renamed); }

  @Then('static handler')
  static staticHandler(value) { return work(value); }

  @Step('instance handler')
  instanceHandler(value) { return work(value); }

  @Given('generator handler')
  *generatorHandler(value) { return work(value); }
}
"#;
    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 9);
    assert_ne!(
        definitions[0].handler.alpha_normalized, definitions[1].handler.alpha_normalized,
        "async and sync methods are behaviorally distinct"
    );
    assert_ne!(
        definitions[2].handler.alpha_normalized, definitions[3].handler.alpha_normalized,
        "different default initializers must remain visible"
    );
    assert!(definitions[2]
        .handler
        .behavior_signature
        .iter()
        .any(|event| event == "call:first"));
    assert!(!definitions[2].handler.trivial);
    assert_eq!(
        definitions[4].handler.alpha_normalized, definitions[5].handler.alpha_normalized,
        "renaming a parameter must not change an equivalent defaulted handler"
    );
    assert_ne!(
        definitions[6].handler.alpha_normalized, definitions[7].handler.alpha_normalized,
        "static and instance methods are behaviorally distinct"
    );
    assert_ne!(
        definitions[7].handler.alpha_normalized, definitions[8].handler.alpha_normalized,
        "generator and ordinary methods are behaviorally distinct"
    );
}

#[test]
fn decorated_method_modifiers_are_detected_across_comments() {
    let source = r#"
import { Given, When, Then, Step } from 'playwright-bdd/decorators';
class CommentedModifiers {
  @Given('commented async')
  async/**/commentedAsync(value) { return work(value); }

  @When('ordinary sync')
  ordinarySync(value) { return work(value); }

  @Then('commented static')
  static/* note */commentedStatic(value) { return work(value); }

  @Step('ordinary instance')
  ordinaryInstance(value) { return work(value); }
}
"#;
    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 4);
    assert_ne!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_ne!(
        definitions[2].handler.alpha_normalized,
        definitions[3].handler.alpha_normalized
    );
}

#[test]
fn malformed_decorator_registrations_warn_without_crossing_class_members() {
    let source = r#"
import { Given } from 'playwright-bdd/decorators';
class InvalidSteps {
  @Given()
  emptyMatcher() { work(); }

  @Given('not attached to a method')
  value = 1;
}
"#;
    let extracted = extract_detailed(source, &file(SourceLanguage::TypeScript)).unwrap();
    assert!(extracted.definitions.is_empty());
    assert!(extracted.diagnostics.iter().any(|diagnostic| diagnostic
        .message
        .contains("dynamic or unsupported step matcher")));
    assert!(extracted.diagnostics.iter().any(|diagnostic| diagnostic
        .message
        .contains("dynamic or unsupported step handler")));
}

#[test]
fn project_resolved_registrations_propagate_framework_metadata() {
    let directory = tempfile::tempdir().unwrap();
    fs::create_dir_all(directory.path().join("support")).unwrap();
    fs::create_dir_all(directory.path().join("packages/bdd/src")).unwrap();
    fs::write(
        directory.path().join("package.json"),
        r##"{"imports":{"#bdd":"./support/world.ts"},"workspaces":["packages/*"]}"##,
    )
    .unwrap();
    fs::write(
        directory.path().join("support/world.ts"),
        "export { Given } from '@cucumber/cucumber';\n",
    )
    .unwrap();
    fs::write(
        directory.path().join("packages/bdd/package.json"),
        r#"{"name":"@example/bdd","exports":"./src/index.ts"}"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("packages/bdd/src/index.ts"),
        "export { Given } from 'playwright-bdd';\n",
    )
    .unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    for (name, module, expected) in [
        ("imports.ts", "#bdd", Framework::CucumberJs),
        ("workspace.ts", "@example/bdd", Framework::PlaywrightBdd),
    ] {
        let path = directory.path().join(name);
        fs::write(
            &path,
            format!("import {{ Given }} from '{module}';\nGiven('resolved', () => work());\n"),
        )
        .unwrap();
        let file = SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        };
        let source = fs::read_to_string(&file.path).unwrap();
        let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();
        assert_eq!(extracted.definitions.len(), 1, "{module}");
        assert_eq!(extracted.definitions[0].framework, expected, "{module}");
    }
}

#[test]
fn mixed_framework_detection_is_scoped_to_each_source_file() {
    let directory = tempfile::tempdir().unwrap();
    let cases = [
        (
            "playwright.steps.ts",
            "import { createBdd } from 'playwright-bdd';\nconst { Given } = createBdd();\nGiven('playwright step', () => work());\n",
            Framework::PlaywrightBdd,
        ),
        (
            "cucumber.steps.ts",
            "import { Given } from '@cucumber/cucumber';\nGiven('cucumber step', () => work());\n",
            Framework::CucumberJs,
        ),
        (
            "cypress.steps.ts",
            "import { Given } from '@badeball/cypress-cucumber-preprocessor';\nGiven('cypress step', () => work());\n",
            Framework::CypressCucumber,
        ),
    ];
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    for (name, source, expected) in cases {
        let path = directory.path().join(name);
        fs::write(&path, source).unwrap();
        let source_file = SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        };
        let extracted = extract_detailed_impl(source, &source_file, &mut session).unwrap();
        assert_eq!(extracted.definitions.len(), 1, "{name}");
        assert_eq!(extracted.definitions[0].framework, expected, "{name}");
    }
}

#[test]
fn playwright_bdd_factory_requires_import_evidence_and_supports_aliases() {
    for source in [
        "import { createBdd as makeBdd } from 'playwright-bdd';\n\
         const { Given } = makeBdd();\nGiven('aliased esm', () => work());",
        "const { createBdd: makeBdd } = require('playwright-bdd');\n\
         const { Given } = makeBdd();\nGiven('aliased cjs', () => work());",
        "const { createBdd } = require('playwright-bdd');\n\
         const { Given } = createBdd();\nGiven('shorthand cjs', () => work());",
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(definitions[0].framework, Framework::PlaywrightBdd);
    }

    let unrelated = extract_ts(
        "const createBdd = () => ({ Given: () => {} });\n\
         const { Given } = createBdd();\nGiven('not a step', () => work());",
    );
    assert!(unrelated.is_empty());
}

#[test]
fn mixed_framework_bindings_keep_per_registration_provenance_in_any_import_order() {
    for imports in [
        r#"
import { Given as CypressGiven } from '@badeball/cypress-cucumber-preprocessor';
import { Given as DecoratorGiven } from 'playwright-bdd/decorators';
import { Then as CucumberThen } from '@cucumber/cucumber';
"#,
        r#"
import { Then as CucumberThen } from '@cucumber/cucumber';
import { Given as DecoratorGiven } from 'playwright-bdd/decorators';
import { Given as CypressGiven } from '@badeball/cypress-cucumber-preprocessor';
"#,
    ] {
        let source = format!(
            r#"{imports}
CypressGiven('a Cypress step', () => cy.visit('/'));
CucumberThen('a Cucumber step', () => work());
class MixedSteps {{
  @DecoratorGiven('a Playwright decorator')
  async prepare() {{ await work(); }}
}}
"#
        );
        let definitions = extract_ts(&source);
        assert_eq!(definitions.len(), 3, "{source}");
        let frameworks = definitions
            .iter()
            .map(|definition| (definition.matcher.as_str(), definition.framework))
            .collect::<std::collections::BTreeMap<_, _>>();
        assert_eq!(
            frameworks.get("a Cypress step"),
            Some(&Framework::CypressCucumber)
        );
        assert_eq!(
            frameworks.get("a Cucumber step"),
            Some(&Framework::CucumberJs)
        );
        assert_eq!(
            frameworks.get("a Playwright decorator"),
            Some(&Framework::PlaywrightBdd)
        );
    }
}

#[test]
fn project_resolves_playwright_bdd_registrations_created_and_exported_by_local_fixture() {
    let directory = tempfile::tempdir().unwrap();
    fs::create_dir_all(directory.path().join("fixtures")).unwrap();
    fs::create_dir_all(directory.path().join("steps")).unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("tsconfig.json"),
        r#"{"compilerOptions":{"paths":{"~/*":["./*"]}}}"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("fixtures/test.ts"),
        r#"
import { createBdd as makeBdd } from 'playwright-bdd';
const test = {};
export const { Given, When: Action, Then } = makeBdd(test);
"#,
    )
    .unwrap();
    let path = directory.path().join("steps/example.steps.ts");
    fs::write(
        &path,
        r#"
import { Given, Action, Then } from '~/fixtures/test';
Given('a local fixture', () => prepare());
Action('an aliased registration', () => act());
Then('the result is visible', () => verify());
"#,
    )
    .unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let source = fs::read_to_string(&file.path).unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 3);
    assert_eq!(extracted.definitions[0].registration, "Given");
    assert_eq!(extracted.definitions[1].registration, "When");
    assert_eq!(extracted.definitions[2].registration, "Then");
    assert!(extracted
        .definitions
        .iter()
        .all(|definition| definition.framework == Framework::PlaywrightBdd));
}

#[test]
fn resolved_framework_facades_provide_expect_import_provenance() {
    let directory = tempfile::tempdir().unwrap();
    fs::create_dir_all(directory.path().join("fixtures")).unwrap();
    fs::create_dir_all(directory.path().join("steps")).unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("tsconfig.json"),
        r#"{"compilerOptions":{"paths":{"~/*":["./*"]}}}"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("fixtures/test.ts"),
        r#"
import { createBdd } from 'playwright-bdd';
export const { Then } = createBdd({});
export const expect = createAssertionFactory();
"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("fixtures/lookalike.ts"),
        r#"
export const Then = makeLocalCallback();
export const expect = makeLocalAssertionFactory();
"#,
    )
    .unwrap();
    let path = directory.path().join("steps/example.steps.ts");
    let source = r#"
import { Then } from '~/fixtures/test';
import { expect } from '~/fixtures/test';
import * as api from '~/fixtures/test';
import { Given } from '@cucumber/cucumber';
import { Then as helper, expect as localCheck } from '~/fixtures/lookalike';
Then('a facade assertion', ({ state }) => expect(state).toBe('ready'));
api.Then('a facade namespace is not assertion provenance', ({ state }) => api.expect(state).toBe('ready'));
Given('an unrelated module is not assertion provenance', ({ state }) => localCheck(state).toBe('ready'));
"#;
    fs::write(&path, source).unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(source, &file, &mut session).unwrap();

    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 3);
    assert_eq!(extracted.definitions[0].handler.behavior_signature.len(), 1);
    assert!(
        extracted.definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:")
    );
    assert!(extracted.definitions[1]
        .handler
        .behavior_signature
        .iter()
        .all(|event| !event.starts_with("assert:")));
    assert!(extracted.definitions[2]
        .handler
        .behavior_signature
        .iter()
        .all(|event| !event.starts_with("assert:")));
    for specifier in [
        "../fixtures/test",
        "../fixtures/test.ts",
        "~/fixtures/test.ts",
    ] {
        let split_source = source.replace(
            "import { expect } from '~/fixtures/test';",
            &format!("import {{ expect }} from '{specifier}';"),
        );
        let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);
        let split = extract_detailed_impl(&split_source, &file, &mut session).unwrap();
        assert!(split.diagnostics.is_empty());
        assert_eq!(
            split.definitions[0].handler.behavior_signature,
            extracted.definitions[0].handler.behavior_signature,
            "{specifier}"
        );
    }
}

#[test]
fn project_resolves_commonjs_playwright_bdd_factory_aliases() {
    for (name, fixture) in [
        (
            "alias",
            "const { createBdd: makeBdd } = require('playwright-bdd');\n\
             export const { Given } = makeBdd(test);\n",
        ),
        (
            "shorthand",
            "const { createBdd } = require('playwright-bdd');\n\
             export const { Given } = createBdd(test);\n",
        ),
    ] {
        let directory = tempfile::tempdir().unwrap();
        fs::write(directory.path().join("package.json"), "{}").unwrap();
        fs::write(directory.path().join("fixture.ts"), fixture).unwrap();
        let path = directory.path().join(format!("{name}.steps.ts"));
        fs::write(
            &path,
            "import { Given } from './fixture';\nGiven('from cjs fixture', () => work());\n",
        )
        .unwrap();
        let file = SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        };
        let source = fs::read_to_string(&file.path).unwrap();
        let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

        let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

        assert!(extracted.diagnostics.is_empty(), "{name}");
        assert_eq!(extracted.definitions.len(), 1, "{name}");
        assert_eq!(extracted.definitions[0].framework, Framework::PlaywrightBdd);
    }
}

#[test]
fn project_resolves_reexported_runtime_registration_imports() {
    for source in [
        "import { Given as Setup } from '@cucumber/cucumber';\nexport { Setup as Given };\n",
        "const { Given: Setup } = require('@cucumber/cucumber');\nexport { Setup as Given };\n",
        "const { Given } = require('@cucumber/cucumber');\nexport { Given };\n",
    ] {
        let directory = tempfile::tempdir().unwrap();
        fs::write(directory.path().join("package.json"), "{}").unwrap();
        fs::write(directory.path().join("barrel.ts"), source).unwrap();
        let path = directory.path().join("example.steps.ts");
        fs::write(
            &path,
            "import { Given } from './barrel';\nGiven('through import barrel', () => work());\n",
        )
        .unwrap();
        let file = SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        };
        let source = fs::read_to_string(&file.path).unwrap();
        let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

        let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

        assert!(extracted.diagnostics.is_empty(), "{source}");
        assert_eq!(extracted.definitions.len(), 1, "{source}");
        assert_eq!(extracted.definitions[0].framework, Framework::CucumberJs);
    }
}

#[test]
fn project_resolves_chained_import_then_export_provenance() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("registration-source.ts"),
        "export { Given } from '@cucumber/cucumber';\n",
    )
    .unwrap();
    fs::write(
        directory.path().join("registration-barrel.ts"),
        "import { Given as Setup } from './registration-source';\nexport { Setup as Given };\n",
    )
    .unwrap();
    fs::write(
        directory.path().join("factory-source.ts"),
        "export { createBdd } from 'playwright-bdd';\n",
    )
    .unwrap();
    fs::write(
        directory.path().join("factory-barrel.ts"),
        "import { createBdd as makeBdd } from './factory-source';\nexport { makeBdd };\n",
    )
    .unwrap();
    let path = directory.path().join("example.steps.ts");
    fs::write(
        &path,
        r#"
import { Given as CucumberGiven } from './registration-barrel';
import { makeBdd as buildBdd } from './factory-barrel';
const { Given: PlaywrightGiven } = buildBdd(test);
CucumberGiven('through a registration chain', () => prepare());
PlaywrightGiven('through a factory chain', () => act());
"#,
    )
    .unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let source = fs::read_to_string(&file.path).unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 2);
    assert_eq!(extracted.definitions[0].framework, Framework::CucumberJs);
    assert_eq!(extracted.definitions[1].framework, Framework::PlaywrightBdd);
}

#[test]
fn module_resolution_clears_active_paths_after_recoverable_errors() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    let module = directory.path().join("fixture.ts");
    fs::write(&module, "export { Given from '@cucumber/cucumber';\n").unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let first_path = directory.path().join("first.steps.ts");
    fs::write(
        &first_path,
        "import { Given } from './fixture';\nGiven('first attempt', () => work());\n",
    )
    .unwrap();
    let first_file = SourceFile {
        path: first_path,
        language: SourceLanguage::TypeScript,
    };
    let first_source = fs::read_to_string(&first_file.path).unwrap();
    let first = extract_detailed_impl(&first_source, &first_file, &mut session).unwrap();
    assert!(first.definitions.is_empty());
    assert!(!first.diagnostics.is_empty());

    fs::write(&module, "export { Given } from '@cucumber/cucumber';\n").unwrap();
    let second_path = directory.path().join("second.steps.ts");
    fs::write(
        &second_path,
        "import { Given } from './fixture';\nGiven('second attempt', () => work());\n",
    )
    .unwrap();
    let second_file = SourceFile {
        path: second_path,
        language: SourceLanguage::TypeScript,
    };
    let second_source = fs::read_to_string(&second_file.path).unwrap();
    let second = extract_detailed_impl(&second_source, &second_file, &mut session).unwrap();

    assert!(second.diagnostics.is_empty());
    assert_eq!(second.definitions.len(), 1);
    assert_eq!(second.definitions[0].framework, Framework::CucumberJs);
}

#[test]
fn project_resolves_explicit_exports_but_rejects_untrusted_create_bdd_lookalikes() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("fixture.ts"),
        r#"
import { createBdd } from 'playwright-bdd';
const { Given: Setup } = createBdd(test);
export { Setup as Given };
"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("lookalike.ts"),
        r#"
const createBdd = () => ({ Given: () => {} });
export const { Given } = createBdd();
"#,
    )
    .unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    for (module, expected_definitions) in [("./fixture", 1), ("./lookalike", 0)] {
        let path = directory.path().join(format!("{}.steps.ts", &module[2..]));
        fs::write(
            &path,
            format!(
                "import {{ Given }} from '{module}';\nGiven('resolved safely', () => work());\n"
            ),
        )
        .unwrap();
        let file = SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        };
        let source = fs::read_to_string(&file.path).unwrap();
        let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();
        assert_eq!(
            extracted.definitions.len(),
            expected_definitions,
            "{module}"
        );
    }
}

#[test]
fn project_resolves_wrapped_create_bdd_results_through_star_exports() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("fixture.ts"),
        r#"
import { createBdd } from 'playwright-bdd';
export const { Given } = (createBdd(test) as ReturnType<typeof createBdd>)!;
"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("barrel.ts"),
        "export * from './fixture';\n",
    )
    .unwrap();
    let path = directory.path().join("example.steps.ts");
    fs::write(
        &path,
        "import { Given } from './barrel';\nGiven('through a barrel', () => work());\n",
    )
    .unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let source = fs::read_to_string(&file.path).unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 1);
    assert_eq!(extracted.definitions[0].registration, "Given");
    assert_eq!(extracted.definitions[0].framework, Framework::PlaywrightBdd);
}

#[test]
fn project_does_not_trust_type_only_create_bdd_imports() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("fixture.ts"),
        r#"
import { type createBdd as Factory } from 'playwright-bdd';
export const { Given } = Factory(test);
"#,
    )
    .unwrap();
    let path = directory.path().join("example.steps.ts");
    fs::write(
        &path,
        "import { Given } from './fixture';\nGiven('not trusted', () => work());\n",
    )
    .unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let source = fs::read_to_string(&file.path).unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(&source, &file, &mut session).unwrap();

    assert!(extracted.definitions.is_empty());
    assert_eq!(extracted.diagnostics.len(), 1);
    assert!(extracted.diagnostics[0]
        .message
        .contains("could not be resolved"));
}

#[test]
fn alpha_fingerprint_ignores_local_renames_but_not_opposite_assertions() {
    let first = extract(
            "Then('visible', async ({ page }) => { const item = page.locator('x'); await expect(item).toBeVisible(); });",
            &file(SourceLanguage::TypeScript),
        )
        .unwrap()
        .remove(0);
    let renamed = extract(
            "Then('shown', async ({ page }) => { const element = page.locator('x'); await expect(element).toBeVisible(); });",
            &file(SourceLanguage::TypeScript),
        )
        .unwrap()
        .remove(0);
    let opposite = extract(
            "Then('hidden', async ({ page }) => { const item = page.locator('x'); await expect(item).not.toBeVisible(); });",
            &file(SourceLanguage::TypeScript),
        )
        .unwrap()
        .remove(0);
    assert_eq!(
        first.handler.alpha_normalized,
        renamed.handler.alpha_normalized
    );
    assert_ne!(
        first.handler.alpha_normalized,
        opposite.handler.alpha_normalized
    );
}

#[test]
fn handler_source_snippets_are_normalized_and_bounded() {
    let source = format!("  {}\r\n", "界".repeat(MAX_HANDLER_SNIPPET_CHARS + 1));
    let snippet = bounded_source_snippet(&source, MAX_HANDLER_SNIPPET_CHARS, false);
    assert_eq!(snippet.chars().count(), MAX_HANDLER_SNIPPET_CHARS);
    assert!(snippet.ends_with('…'));
    assert!(!snippet.contains('\r'));

    for (source, max_chars, preserve_prefix_bytes, expected) in [
        ("", 0, false, ""),
        ("abc", 0, false, ""),
        ("abc", 1, false, "…"),
        ("abc", 2, false, "a…"),
        ("ab", 2, false, "ab"),
        ("abc", 0, true, ""),
        ("abc", 1, true, ""),
        ("abc", 2, true, ""),
        ("abcd", 3, true, "…"),
        ("abcde", 4, true, "a…"),
        ("界界", 1, true, "…"),
    ] {
        assert_eq!(
            bounded_source_snippet(source, max_chars, preserve_prefix_bytes),
            expected,
            "source={source:?} max_chars={max_chars} preserve_prefix_bytes={preserve_prefix_bytes}"
        );
    }
}

#[test]
fn extracts_rule_scoped_inline_suppressions_and_rejects_malformed_directives() {
    let extracted = extract_detailed(
        r#"
// cuke-dedup:ignore duplicate-matcher -- wording fixed by an external contract
// cuke-dedup:ignore unused-definition -- exercised by a remote suite
Given('external wording', () => work());
// cuke-dedup:ignore duplicate-handler
Then('broken directive', () => other());
// cuke-dedup:ignore unknown-rule -- not a real rule
When('unknown rule', () => another());
// cuke-dedup:ignore unused-definition --
When('empty reason', () => finalAction());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert_eq!(extracted.definitions[0].inline_suppressions.len(), 2);
    assert_eq!(
        extracted.definitions[0].inline_suppressions[0].rule,
        Rule::DuplicateMatcher
    );
    assert_eq!(extracted.diagnostics.len(), 3);
    assert_eq!(
        extracted.diagnostics[0].level,
        ExtractionDiagnosticLevel::Error
    );
    assert!(extracted.diagnostics[0]
        .message
        .contains("cuke-dedup:ignore RULE -- REASON"));
    assert!(extracted.diagnostics[1].message.contains("unknown rule"));
    assert!(extracted.diagnostics[2]
        .message
        .contains("reason must not be empty"));
}

#[test]
fn rejects_oversized_inline_suppression_reasons() {
    let reason = "x".repeat(crate::resource_limits::MAX_SUPPRESSION_REASON_CHARS + 1);
    let extracted = extract_detailed(
        &format!(
            "// cuke-dedup:ignore duplicate-handler -- {reason}\nGiven('step', () => work());"
        ),
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert!(extracted.definitions[0].inline_suppressions.is_empty());
    assert!(extracted.diagnostics[0]
        .message
        .contains("512-character limit"));
}

#[test]
fn structural_fingerprint_masks_string_literal_contents() {
    let first = extract(
        "Then('save', async ({ page }) => { await page.locator('#save').click(); });",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    let second = extract(
        "Then('saves', async ({ page }) => { await page.locator('#saves').click(); });",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    assert_ne!(
        first.handler.alpha_normalized,
        second.handler.alpha_normalized
    );
    assert_eq!(first.handler.structural, second.handler.structural);
}

#[test]
fn behavior_signatures_canonicalize_calls_without_treating_await_as_behavior() {
    struct Case {
        name: &'static str,
        source: &'static str,
        expected: &'static [&'static str],
    }

    for case in [
        Case {
            name: "direct member call",
            source: "Given('step', async function () { await this.page.click('#save'); });",
            expected: &["call:this.page#click"],
        },
        Case {
            name: "fluent member call",
            source:
                "Given('step', async function () { await this.page.locator('#save').click(); });",
            expected: &["call:this.page#click", "call:this.page#locator"],
        },
        Case {
            name: "parenthesized awaited receiver",
            source:
                "Given('step', async function () { await (await this.page.locator('#save')).click(); });",
            expected: &["call:this.page#click", "call:this.page#locator"],
        },
        Case {
            name: "factory call receiver",
            source: "Given('step', async function () { await browser().click('#save'); });",
            expected: &["call:browser#click", "call:browser"],
        },
        Case {
            name: "free local callback",
            source: "Given('step', async (perform) => { await perform(); });",
            expected: &["call:v0"],
        },
        Case {
            name: "receiver identity",
            source: "Given('step', async ({ audit }) => { await audit.click(); });",
            expected: &["call:v0#click"],
        },
    ] {
        let definition = extract(case.source, &file(SourceLanguage::TypeScript))
            .unwrap()
            .remove(0);
        assert_eq!(
            definition.handler.behavior_signature, case.expected,
            "{}",
            case.name
        );
    }
}

#[test]
fn behavior_signatures_alpha_normalize_declared_receivers() {
    let definitions = extract_ts(
        "Given('first', async (page) => { await page.goto('/'); });\n\
         Given('second', async (browser) => { await browser.goto('/'); });\n\
         Given('third', page => page.goto('/'));\n\
         Given('fourth', browser => browser.goto('/'));",
    );
    assert_eq!(definitions.len(), 4);
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    assert_eq!(definitions[0].handler.behavior_signature, ["call:v0#goto"]);
    assert_eq!(
        definitions[2].handler.alpha_normalized,
        definitions[3].handler.alpha_normalized
    );
    assert_eq!(definitions[2].handler.behavior_signature, ["call:v0#goto"]);
}

#[test]
fn behavior_signatures_preserve_assertion_subjects_and_polarity() {
    let definitions = extract_ts(
        r#"
Then('primary value', async ({ page }, expected) => {
  await expect(new Form(page).primaryInput).toHaveValue(expected);
});
Then('secondary value', async ({ page }, expected) => {
  await expect(new Form(page).secondaryInput).toHaveValue(expected);
});
Then('panel active', async ({ page }) => {
  await expect(new Navigation(page).panel).toHaveClass(/active/);
});
Then('panel inactive', async ({ page }) => {
  await expect(new Navigation(page).panel).not.toHaveClass(/active/);
});
Then('status active', async ({ page }) => {
  await expect(new Navigation(page).status).toBe('active');
});
Then('status inactive', async ({ page }) => {
  await expect(new Navigation(page).status).toBe('inactive');
});
"#,
    );

    assert_eq!(definitions.len(), 6);
    assert_ne!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    assert_ne!(
        definitions[2].handler.behavior_signature,
        definitions[3].handler.behavior_signature
    );
    assert_ne!(
        definitions[4].handler.behavior_signature,
        definitions[5].handler.behavior_signature
    );
    assert!(definitions.iter().all(|definition| {
        definition.handler.behavior_signature.len() == 1
            && definition.handler.behavior_signature[0].starts_with("assert:expect")
    }));
    assert!(definitions[3].handler.behavior_signature[0].contains(".not#toHaveClass"));
}

#[test]
fn behavior_signatures_still_alpha_normalize_assertion_subject_locals() {
    let definitions = extract_ts(
        r#"
Then('first assertion', async ({ page }) => {
  const item = page.locator('#status');
  await expect(item).toBeVisible();
});
Then('second assertion', async ({ page }) => {
  const element = page.locator('#status');
  await expect(element).toBeVisible();
});
"#,
    );

    assert_eq!(definitions.len(), 2);
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
}

#[test]
fn assertion_values_resolve_safe_local_constant_initializers() {
    let definitions = extract_ts(
        r#"
Then('first subject', ({ page }) => {
  const target = new Form(page).primaryInput;
  expect(target).toHaveValue('ready');
});
Then('second subject', ({ page }) => {
  const target = new Form(page).secondaryInput;
  expect(target).toHaveValue('ready');
});
Then('first expected value', ({ state }) => {
  const expected = 'ready';
  expect(state).toBe(expected);
});
Then('second expected value', ({ state }) => {
  const expected = 'idle';
  expect(state).toBe(expected);
});
Then('renamed equivalent constant', ({ state }) => {
  const wanted = 'ready';
  expect(state).toBe(wanted);
});
Then('chained ready constant', ({ state }) => {
  const base = 'ready';
  const expected = base;
  expect(state).toBe(expected);
});
Then('chained idle constant', ({ state }) => {
  const base = 'idle';
  const expected = base;
  expect(state).toBe(expected);
});
"#,
    );

    assert_eq!(definitions.len(), 7);
    assert_ne!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    assert_ne!(
        definitions[2].handler.behavior_signature,
        definitions[3].handler.behavior_signature
    );
    assert_eq!(
        definitions[2].handler.behavior_signature,
        definitions[4].handler.behavior_signature
    );
    assert_ne!(
        definitions[5].handler.behavior_signature,
        definitions[6].handler.behavior_signature
    );
}

#[test]
fn assertion_chains_unwrap_typescript_expression_wrappers() {
    for source in [
        "Then('as wrapper', ({ state }) => (expect(state) as any).toBe('ready'));",
        "Then('satisfies wrapper', ({ state }) => (expect(state) satisfies Assertion).toBe('ready'));",
        "Then('non-null wrapper', ({ state }) => expect(state)!.toBe('ready'));",
        "Then('type assertion wrapper', ({ state }) => (<Assertion>expect(state)).toBe('ready'));",
        "Then('generic call', ({ state }) => expect<string>(state).toBe('ready'));",
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert!(
            definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn assertion_review_scope_boundaries() {
    for body in [
        "const run = () => { const expected = 'ready'; expect(state).toBe(expected); }; run();",
        "const expected = 'ready'; items.forEach(expected => expect(state).toBe(expected));",
    ] {
        let definitions = extract_ts(&format!("Then('nested', () => {{ {body} }});"));
        assert_eq!(definitions.len(), 1);
        assert!(definitions[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")));
    }
    for body in [
        "const status = VALUE; expect(page.status).toBe('ready');",
        "const status = VALUE; expect({ status: page.value }).toBe('ready');",
        "class X { static { const expected = VALUE; } } expect(state).toBe(expected);",
    ] {
        let signatures: Vec<_> = ["'ready'", "'idle'"]
            .into_iter()
            .map(|value| {
                extract_ts(&format!(
                    "Then('scope', () => {{ {} }});",
                    body.replace("VALUE", value)
                ))[0]
                    .handler
                    .behavior_signature
                    .clone()
            })
            .collect();
        assert_eq!(signatures[0], signatures[1], "{body}");
    }
    for keyword in ["namespace", "module"] {
        for binding in ["var", "const"] {
            let source = format!("{keyword} Helpers {{ {binding} expect = custom; Then('inner', () => expect(state).toBe('ready')); }} Then('outer', () => expect(state).toBe('ready'));");
            let definitions = extract_ts(&source);
            assert_eq!(definitions.len(), 2);
            assert!(
                definitions[0]
                    .handler
                    .behavior_signature
                    .iter()
                    .all(|event| !event.starts_with("assert:")),
                "{source}"
            );
            assert!(
                definitions[1]
                    .handler
                    .behavior_signature
                    .iter()
                    .any(|event| event.starts_with("assert:")),
                "{source}"
            );
        }
    }
}

#[test]
fn behavior_signatures_cover_supported_expect_variants_and_incomplete_chains() {
    let definitions = extract_ts(
        r#"
Then('soft assertion', async ({ page }) => {
  await expect.soft(page.locator('#status')).toBeVisible();
});
Then('polled assertion', async ({ state }) => {
  await expect.poll(() => state.value).toBe('ready');
});
Then('standalone expect call', ({ value }) => {
  expect(value);
});
Then('missing assertion subject', () => {
  expect().toBeVisible();
});
"#,
    );

    assert_eq!(definitions.len(), 4);
    assert_eq!(definitions[0].handler.behavior_signature.len(), 1);
    assert!(definitions[0].handler.behavior_signature[0].starts_with("assert:expect.soft#"));
    assert_eq!(definitions[1].handler.behavior_signature.len(), 1);
    assert!(definitions[1].handler.behavior_signature[0].starts_with("assert:expect.poll#"));
    assert_eq!(definitions[2].handler.behavior_signature, ["call:expect"]);
    assert_eq!(
        definitions[3].handler.behavior_signature,
        ["call:expect#toBeVisible", "call:expect"]
    );

    let deep_chain = format!(
        "Then('bounded chain', ({{ value }}) => expect(value){}.toBeVisible());",
        ".not".repeat(20)
    );
    let definition = extract_ts(&deep_chain).remove(0);
    assert!(!definition.handler.behavior_signature.is_empty());
}

#[test]
fn behavior_signatures_resolve_trusted_expect_imports_and_requires() {
    let cases = [
        r#"
import { expect as check } from '@playwright/test';
Then('aliased ESM assertion', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
import * as testApi from '@playwright/test';
Then('namespaced ESM assertion', ({ state }) => testApi.expect(state).toBe('ready'));
"#,
        r#"
const { expect: verify } = require('@jest/globals');
Then('aliased CJS assertion', ({ state }) => verify(state).toBe('ready'));
"#,
        r#"
const testApi = require('@playwright/test');
Then('namespaced CJS assertion', ({ state }) => testApi.expect(state).toBe('ready'));
"#,
        r#"
import check from 'expect';
Then('default assertion import', ({ state }) => check(state).toBe('ready'));
"#,
    ];

    for source in cases {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(
            definitions[0].handler.behavior_signature.len(),
            1,
            "{source}"
        );
        assert!(
            definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn behavior_signatures_do_not_trust_expect_aliases_from_unrelated_modules() {
    let definition = extract_ts(
        r#"
import { expect as check } from 'unrelated-assertion-library';
Then('unrelated assertion alias', ({ state }) => check(state).toBe('ready'));
"#,
    )
    .remove(0);

    assert_eq!(
        definition.handler.behavior_signature,
        ["call:check#toBe", "call:check"]
    );
}

#[test]
fn runtime_expect_bindings_shadow_the_ambient_assertion_factory() {
    let cases = [
        r#"
import { expect } from 'unrelated-assertion-library';
Then('shadowed by ESM import', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
const expect = require('unrelated-assertion-library');
Then('shadowed by CJS require', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
const expect = makeAssertionFactory();
Then('shadowed by variable', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
if (enabled) { var expect = makeAssertionFactory(); }
Then('shadowed by module var hoisting', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
for (var expect of factories) { consume(expect); }
Then('shadowed by module loop var hoisting', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
if (enabled) { var require = makeLoader(); }
const { expect: check } = require('@playwright/test');
Then('shadowed module require var has no provenance', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
function expect(value) { return makeAssertion(value); }
Then('shadowed by declaration', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
Then('shadowed by parameter', (expect, state) => expect(state).toBe('ready'));
"#,
        r#"
expect = makeAssertionFactory();
Then('shadowed by assignment', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
import { expect as check } from '@playwright/test';
Then('trusted alias shadowed by parameter', (check, state) => check(state).toBe('ready'));
"#,
        r#"
import { expect as check } from '@playwright/test';
Then('trusted alias shadowed by one parameter', check => check(state).toBe('ready'));
"#,
        r#"
function helper() {
  const { expect: check } = require('@playwright/test');
  return check;
}
Then('nested trusted binding does not leak', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
function require() { return unrelatedModule(); }
const { expect: check } = require('@playwright/test');
Then('shadowed require has no provenance', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
Then('named function expression shadows ambient', function expect(state) {
  expect(state).toBe('ready');
});
"#,
        r#"
Then('shadowed by catch binding', async ({ state }) => {
  try { await work(); } catch (expect) { expect(state).toBe('ready'); }
});
"#,
        r#"
Then('shadowed by loop binding', ({ state, factories }) => {
  for (const expect of factories) { expect(state).toBe('ready'); }
});
"#,
        r#"
Then('shadowed by function var binding', ({ state, enabled }) => {
  if (enabled) { var expect = makeAssertionFactory(); }
  expect(state).toBe('ready');
});
"#,
        r#"
Then('shadowed by function loop var binding', ({ state, factories }) => {
  for (var expect of factories) { consume(expect); }
  expect(state).toBe('ready');
});
"#,
        r#"
Then('shadowed across switch cases', ({ state }) => {
  switch (state.kind) {
    case 'local': let expect = makeAssertionFactory(); break;
    case 'assert': expect(state).toBe('ready'); break;
  }
});
"#,
        r#"
({ expect } = assertionFactories);
Then('shadowed by destructuring assignment', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
enum expect { Ready }
Then('shadowed by runtime enum', ({ state }) => expect(state).toBe('ready'));
"#,
    ];

    for source in cases {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert!(
            definitions[0]
                .handler
                .behavior_signature
                .iter()
                .all(|event| !event.starts_with("assert:")),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn typescript_runtime_and_erased_declarations_have_distinct_assertion_shadowing() {
    let cases = [
        (
            r#"
namespace expect { export const custom = true; }
Then('runtime namespace shadows ambient', ({ state }) => expect(state).toBe('ready'));
"#,
            false,
        ),
        (
            r#"
module expect { export const custom = true; }
Then('runtime module shadows ambient', ({ state }) => expect(state).toBe('ready'));
"#,
            false,
        ),
        (
            r#"
declare namespace expect { const custom: boolean; }
Then('declared namespace is erased', ({ state }) => expect(state).toBe('ready'));
"#,
            true,
        ),
        (
            r#"
declare const expect: AssertionFactory;
Then('declared constant is erased', ({ state }) => expect(state).toBe('ready'));
"#,
            true,
        ),
    ];

    for (source, expected_assertion) in cases {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(
            definitions[0]
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("assert:")),
            expected_assertion,
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn assertion_namespaces_named_expect_do_not_restore_the_callable_ambient() {
    for source in [
        r#"
import * as expect from '@playwright/test';
Then('ESM namespace occupies expect', ({ state }) => expect(state).toBe('ready'));
Then('ESM namespace property remains trusted', ({ state }) => expect.expect(state).toBe('ready'));
"#,
        r#"
const expect = require('@playwright/test');
Then('CJS namespace occupies expect', ({ state }) => expect(state).toBe('ready'));
Then('CJS namespace property remains trusted', ({ state }) => expect.expect(state).toBe('ready'));
"#,
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 2, "{source}");
        assert!(
            definitions[0]
                .handler
                .behavior_signature
                .iter()
                .all(|event| !event.starts_with("assert:")),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
        assert!(
            definitions[1]
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("assert:")),
            "{source}: {:?}",
            definitions[1].handler.behavior_signature
        );
    }
}

#[test]
fn handler_local_shadows_do_not_disable_assertions_in_other_handlers() {
    let cases = [
        r#"
const { expect: check } = require('@playwright/test');
function helper(require) { return require('local-helper'); }
Then('module CJS assertion remains trusted', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
import { expect as check } from '@playwright/test';
const helper = check => check;
Then('module ESM assertion remains trusted', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
Then('local function name is shadowed', function expect(state) {
  expect(state).toBe('ready');
});
Then('ambient assertion remains trusted elsewhere', ({ state }) => expect(state).toBe('ready'));
"#,
    ];

    for source in cases {
        let definitions = extract_ts(source);
        let trusted = definitions.last().expect("assertion step");
        assert!(
            trusted
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("assert:")),
            "{source}: {:?}",
            trusted.handler.behavior_signature
        );
        if definitions.len() == 2 {
            assert!(definitions[0]
                .handler
                .behavior_signature
                .iter()
                .all(|event| !event.starts_with("assert:")));
        }
    }
}

#[test]
fn nested_scope_shadows_do_not_disable_outer_assertions_in_the_same_handler() {
    let definition = extract_ts(
        r#"
Then('outer assertion remains trusted', ({ state }) => {
  expect(state).toBe('ready');
  function helper(expect) { return expect(state).toBe('local'); }
});
"#,
    )
    .remove(0);

    assert_eq!(
        definition
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .count(),
        1
    );
}

#[test]
fn property_and_lexically_resolved_assignments_preserve_assertion_provenance() {
    let cases = [
        r#"
import * as pw from '@playwright/test';
Then('namespace property assignment', ({ state }) => {
  pw.someConfig = true;
  pw.expect(state).toBe('ready');
});
"#,
        r#"
Then('bare assertion property assignment', ({ state }) => {
  expect.custom = true;
  expect(state).toBe('ready');
});
"#,
        r#"
Then('destructured assertion property assignment', ({ state, source }) => {
  ({ value: expect.custom } = source);
  expect(state).toBe('ready');
});
"#,
        r#"
import * as pw from '@playwright/test';
Then('array namespace property assignment', ({ state, source }) => {
  [pw.value] = source;
  pw.expect(state).toBe('ready');
});
"#,
        r#"
{ let expect; expect = makeAssertionFactory(); }
Then('block assignment stays local', ({ state }) => expect(state).toBe('ready'));
"#,
    ];

    for source in cases {
        let definition = extract_ts(source).remove(0);
        assert!(
            definition
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("assert:")),
            "{source}: {:?}",
            definition.handler.behavior_signature
        );
    }

    let definition = extract_ts(
        r#"
function mutate() { expect = makeAssertionFactory(); }
Then('unresolved outer mutation is conservative', ({ state }) => expect(state).toBe('ready'));
"#,
    )
    .remove(0);
    assert!(definition
        .handler
        .behavior_signature
        .iter()
        .all(|event| !event.starts_with("assert:")));
}

#[test]
fn javascript_using_loop_bindings_shadow_ambient_expect() {
    let source = r#"
Then('using loop binding', ({ state, resources }) => {
  for (using expect of resources) { expect(state).toBe('ready'); }
});
"#;
    let definitions = extract(source, &file(SourceLanguage::JavaScript)).unwrap();
    assert_eq!(definitions.len(), 1);
    assert!(definitions[0]
        .handler
        .behavior_signature
        .iter()
        .all(|event| !event.starts_with("assert:")));
}

#[test]
fn runtime_class_names_shadow_ambient_expect_only_inside_the_class() {
    for class in [
        "class expect",
        "const Wrapper = class expect",
        "abstract class expect",
    ] {
        let source = format!(
            r#"
import {{ Then }} from 'playwright-bdd/decorators';
import {{ Given }} from '@cucumber/cucumber';
{class} {{
  @Then('class name is runtime binding')
  verify(state) {{ expect(state).toBe('ready'); }}
}}
Given('ambient remains trusted outside the class', ({{ state }}) => expect(state).toBe('ready'));
"#
        );
        let definitions = extract_ts(&source);
        assert_eq!(definitions.len(), 2, "{source}");
        assert!(
            definitions[0]
                .handler
                .behavior_signature
                .iter()
                .all(|event| !event.starts_with("assert:")),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
        assert_eq!(
            definitions[1]
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.starts_with("assert:")),
            class.starts_with("const "),
            "{source}: {:?}",
            definitions[1].handler.behavior_signature
        );
    }
}

#[test]
fn block_and_class_static_bindings_stay_within_their_lexical_scopes() {
    let cases = [
        r#"
{ class expect {} }
Then('block class does not shadow ambient assertion', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
{ function expect(value) { return value; } }
Then('block function does not shadow ambient assertion', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
Then('class static var stays local', ({ state }) => {
  class Helper { static { var expect = makeAssertionFactory(); consume(expect); } }
  expect(state).toBe('ready');
});
"#,
    ];

    for source in cases {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(
            definitions[0]
                .handler
                .behavior_signature
                .iter()
                .filter(|event| event.starts_with("assert:"))
                .count(),
            1,
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn method_names_do_not_shadow_assertion_bindings_inside_their_bodies() {
    let definitions = extract_ts(
        r#"
import { Then } from 'playwright-bdd/decorators';
class Assertions {
  @Then('method name is not a lexical binding')
  expect({ state }) { expect(state).toBe('ready'); }
}
"#,
    );

    assert_eq!(definitions.len(), 1);
    assert!(definitions[0]
        .handler
        .behavior_signature
        .iter()
        .any(|event| event.starts_with("assert:")));
}

#[test]
fn shadowed_expect_calls_retain_generic_behavior_comparison() {
    let definitions = extract_ts(
        r#"
import { expect } from 'unrelated-assertion-library';
Then('the local state shows the first condition', ({ state }) => expect(state).toBe('ready'));
Then('the local state shows the final condition', ({ state }) => expect(state).toBe('idle'));
"#,
    );

    assert_eq!(definitions.len(), 2);
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    assert!(definitions[0]
        .handler
        .behavior_signature
        .iter()
        .all(|event| !event.starts_with("assert:")));
}

#[test]
fn trusted_and_type_only_expect_imports_preserve_assertion_semantics() {
    for source in [
        r#"
import { expect } from '@playwright/test';
Then('trusted runtime binding', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
import type { expect } from 'unrelated-types';
Then('ambient binding remains', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
const check = require('expect');
Then('standalone CJS binding', ({ state }) => check(state).toBe('ready'));
"#,
        r#"
const { expect } = require('@playwright/test');
Then('shorthand CJS binding', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
import check = require('expect');
Then('TypeScript import require binding', ({ state }) => check(state).toBe('ready'));
"#,
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(
            definitions[0].handler.behavior_signature.len(),
            1,
            "{source}"
        );
        assert!(
            definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
            "{source}: {:?}",
            definitions[0].handler.behavior_signature
        );
    }
}

#[test]
fn ambient_variable_declarations_do_not_shadow_runtime_assertion_provenance() {
    for source in [
        r#"
declare var expect: unknown;
Then('ambient expect remains available', ({ state }) => expect(state).toBe('ready'));
"#,
        r#"
declare var require: unknown;
const { expect } = require('@playwright/test');
Then('CommonJS expect remains available', ({ state }) => expect(state).toBe('ready'));
"#,
    ] {
        let definitions = extract_ts(source);

        assert_eq!(definitions.len(), 1, "{source}");
        assert!(
            definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
            "{source}"
        );
    }
}

#[test]
fn decorated_method_metadata_does_not_inflate_executable_behavior_similarity() {
    let definitions = extract_ts(
        r#"
import { Given } from 'playwright-bdd/decorators';
import { expect as check } from '@playwright/test';
class StatusSteps {
  @Given('the account status shows the first condition')
  first({ page }) { check(page.status).toBe('ready'); }

  @Given('the account status shows the final condition')
  second({ page }) { check(page.status).toBe('idle'); }
}
"#,
    );

    assert_eq!(definitions.len(), 2);
    assert!(definitions.iter().all(|definition| {
        definition.handler.behavior_signature.len() == 2
            && definition.handler.behavior_signature[0] == "method:instance sync"
            && definition.handler.behavior_signature[1].starts_with("assert:expect#toBe:")
    }));
    assert_ne!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
}

#[test]
fn alpha_fingerprints_assign_identifiers_by_declaration_order() {
    let definitions = extract_ts(
        "Given('first', (z, a) => z.goto(a));\n\
         Given('second', (b, y) => b.goto(y));",
    );

    assert_eq!(definitions.len(), 2);
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
}

#[test]
fn defaulted_destructured_parameters_preserve_initializer_behavior() {
    let definitions = extract_ts(
        "Given('first', ({ page: browser = makePage() } = {}) => browser.goto('/'));\n\
         Given('second', ({ page: tab = makePage() } = {}) => tab.goto('/'));",
    );
    assert_eq!(definitions.len(), 2);
    assert_eq!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
    assert_eq!(
        definitions[0].handler.behavior_signature,
        ["call:makePage", "call:v0#goto"]
    );
    assert!(definitions
        .iter()
        .all(|definition| !definition.handler.trivial));
}

#[test]
fn computed_callees_keep_the_structural_fallback() {
    let definition = extract(
        "Given('step', ({ page, method }) => page[method]());",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    assert_eq!(definition.handler.behavior_signature.len(), 1);
    assert!(definition.handler.behavior_signature[0].starts_with("call:(subscript_expression"));
}

#[test]
fn ignores_unrelated_member_calls_and_destructuring_aliases() {
    let source = r#"
somePromise.then('not a step', () => {});
const { Given: G } = require('unrelated-lib');
G('also not a step', () => {});
"#;
    assert!(extract(source, &file(SourceLanguage::JavaScript))
        .unwrap()
        .is_empty());
}

#[test]
fn retains_regex_flags_and_decodes_javascript_hex_escapes() {
    let definitions = extract(
        r#"Then(/^THE USER$/i, namedHandler); Given("letter \x41 and \u{1F600}", namedHandler);"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 2);
    assert_eq!(definitions[0].matcher_flags, "i");
    assert_eq!(definitions[1].matcher, "letter A and 😀");
}

#[test]
fn preserves_all_flags_but_normalizes_only_semantic_regex_flags() {
    let definition = extract(
        r"Then(/^VALUE$/ygusm, () => work());",
        &file(SourceLanguage::JavaScript),
    )
    .unwrap()
    .remove(0);
    assert_eq!(definition.matcher_flags, "ygusm");
    assert_eq!(definition.normalized_matcher, "[regex-flags:msu] ^VALUE$");
}

#[test]
fn resolves_named_handlers_to_bodies_without_cross_file_name_collisions() {
    let first = extract(
        "function handler() { doAlpha(); } Given('alpha step', handler);",
        &SourceFile {
            path: PathBuf::from("steps/a.ts"),
            language: SourceLanguage::TypeScript,
        },
    )
    .unwrap()
    .remove(0);
    let second = extract(
        "function handler() { doBetaDifferently(); } Given('bravo step', handler);",
        &SourceFile {
            path: PathBuf::from("steps/b.ts"),
            language: SourceLanguage::TypeScript,
        },
    )
    .unwrap()
    .remove(0);

    assert!(first.handler.comparable);
    assert!(second.handler.comparable);
    assert!(first.handler.source_snippet.contains("doAlpha"));
    assert_ne!(
        first.handler.alpha_normalized,
        second.handler.alpha_normalized
    );
}

#[test]
fn resolves_bound_named_handlers_without_dropping_the_definition() {
    let definition = extract(
        "function handler() { doWork(); } Given('bound step', handler.bind(world));",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    assert!(definition.handler.comparable);
    assert!(definition.handler.source_snippet.contains("doWork"));
}

#[test]
fn bound_arguments_are_part_of_handler_identity() {
    let definitions = extract(
        r#"
function handler(value) { doWork(value); }
Given('one', handler.bind(null, 1));
Given('two', handler.bind(null, 2));
Given('another one', handler.bind(null, 1));
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert_ne!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[2].handler.alpha_normalized
    );
    assert!(definitions[0]
        .handler
        .source_snippet
        .contains("bound with (null, 1)"));
}

#[test]
fn unresolved_handler_references_are_not_comparable() {
    let definition = extract(
        "import { handler } from './shared'; Given('a step', handler);",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    assert!(!definition.handler.comparable);
    assert!(!definition.handler.trivial);
}

#[test]
fn recognizes_resolved_and_inline_stub_handler_shapes() {
    let definitions = extract(
        r#"
function notImplemented() { throw new Error('pending'); }
Given('named stub', notImplemented);
Given('expression stub', () => pending());
Given('return stub', function () { return 'pending'; });
Given('await stub', async () => await pending());
Given('block await stub', async () => { await this.pending(); });
Given('return await stub', async function () { return await pending(); });
Given('promise stub', () => Promise.resolve());
Given('void stub', () => void 0);
Given('real handler', () => doWork());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 9);
    assert!(
        definitions[0].handler.trivial,
        "resolved named stub: {:?}",
        definitions[0].handler
    );
    assert!(definitions[1].handler.trivial);
    assert!(definitions[2].handler.trivial);
    assert!(definitions[3].handler.trivial);
    assert!(definitions[4].handler.trivial);
    assert!(definitions[5].handler.trivial);
    assert!(definitions[6].handler.trivial);
    assert!(definitions[7].handler.trivial);
    assert!(!definitions[8].handler.trivial);
}

#[test]
fn real_handlers_with_stub_like_text_remain_comparable() {
    let definitions = extract(
        r#"
Given('append', () => appending(row));
Given('timer', () => world.suspendingTimer());
Given('return value', () => { return 'the confirmed order id'; });
Given('domain error', () => { throw new DomainError(order.id); });
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 4);
    assert!(definitions
        .iter()
        .all(|definition| !definition.handler.trivial));
}

#[test]
fn structural_templates_preserve_substitution_behavior() {
    let definitions = extract(
        r#"
Given('user name', () => render(`${user.firstName} ${user.lastName}`));
Given('order total', () => render(`${order.subtotal + order.tax}`));
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_ne!(
        definitions[0].handler.structural,
        definitions[1].handler.structural
    );
}

#[test]
fn lowercase_registrations_require_supported_import_evidence() {
    let unrelated = extract(
            "function fn() { work(); } then('not a step', fn); const alias = then; alias('also not a step', fn);",
            &file(SourceLanguage::JavaScript),
        )
        .unwrap();
    assert!(unrelated.is_empty());

    let supported = extract(
        r#"
import { createBdd } from 'playwright-bdd';
const { given } = createBdd(test);
given('a real step', () => work());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_eq!(supported.len(), 1);

    for source in [
        "// import { given } from '@cucumber/cucumber';\ngiven('phantom', () => work());",
        "const documentation = \"import { given } from 'playwright-bdd'\";\ngiven('phantom', () => work());",
    ] {
        assert!(extract(source, &file(SourceLanguage::TypeScript))
            .unwrap()
            .is_empty());
    }
}

#[test]
fn regular_expression_normalization_preserves_matching_semantics() {
    assert_eq!(
        normalize_regular_expression(r"^I have (\d{2}) (foo|bar)$"),
        r"^I have (\d{2}) (foo|bar)$"
    );
    assert_eq!(
        normalize_regular_expression(r"^value (?=ahead)(\w+)$"),
        r"^value (?=ahead)(\w+)$"
    );
    assert_eq!(
        normalize_regular_expression(r"^(?<name>\w+) wins$"),
        normalize_regular_expression(r"^(\w+) wins$")
    );
    assert_ne!(
        normalize_regular_expression(r"^I wait (\d+) seconds$"),
        normalize_regular_expression(r"^I wait (a few|several) seconds$")
    );
    assert_ne!(
        normalize_regular_expression(r"^(a)\1$"),
        normalize_regular_expression(r"^(b)\1$")
    );
    assert_eq!(
        normalize_regular_expression(r"^a (?:optional )?step$"),
        "^a (?:optional )?step$"
    );
    assert_ne!(
        normalize_regular_expression(r"^a step$"),
        normalize_regular_expression(r"a step")
    );
    assert_eq!(normalize_regular_expression(r"[\s+]"), r"[\s+]");
}

#[test]
fn regex_flag_encoding_cannot_collide_with_literal_matcher_text() {
    let definitions = extract(
        r#"
Given(/^a step here$/i, () => first());
Given('a step here /i', () => second());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_ne!(
        definitions[0].normalized_matcher,
        definitions[1].normalized_matcher
    );
}

#[test]
fn resolves_supported_registration_import_shapes_and_alias_chains() {
    for source in [
        "export { given } from '@cucumber/cucumber'; given('step', () => work());",
        "import * as c from '@cucumber/cucumber'; const { given } = c; given('step', () => work());",
        "const G = Given; const H = G; H('step', () => work());",
        "const { given: g } = require('@cucumber/cucumber'); const h = g; h('step', () => work());",
    ] {
        let definitions = extract(source, &file(SourceLanguage::TypeScript)).unwrap();
        assert_eq!(definitions.len(), 1, "source: {source}");
    }
}

#[test]
fn runtime_absent_and_shadowed_registrations_are_ignored() {
    for source in [
        "import type { given } from '@cucumber/cucumber'; given('phantom', () => work());",
        "function Given(name, handler) { return handler; } Given('phantom', () => work());",
        "const Given = (name, handler) => handler; Given('phantom', () => work());",
        "let Given; Given = wrap; Given('phantom', () => work());",
        "const Given = wrap; Given('phantom', () => work());",
        "class Given {} Given('phantom', () => work());",
        "type Given = (name: string) => void; export type { Given }; Given('phantom', () => work());",
    ] {
        let definitions = extract(source, &file(SourceLanguage::TypeScript)).unwrap();
        assert!(definitions.is_empty(), "source: {source}");
    }
}

#[test]
fn type_only_imports_neither_resolve_modules_nor_shadow_runtime_globals() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("broken.ts"),
        "export { Given } from '@cucumber/cucumber'; const broken = ;\n",
    )
    .unwrap();
    let path = directory.path().join("steps.ts");
    let source = r#"
import /* comment */ type { Given } from './broken';
import { type Then } from './missing';
Given('ambient runtime registration', () => work());
"#;
    fs::write(&path, source).unwrap();
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);
    let extracted = extract_detailed_impl(
        source,
        &SourceFile {
            path,
            language: SourceLanguage::TypeScript,
        },
        &mut session,
    )
    .unwrap();

    assert!(extracted.diagnostics.is_empty());
    assert_eq!(extracted.definitions.len(), 1);
    assert_eq!(
        extracted.definitions[0].matcher,
        "ambient runtime registration"
    );
    assert_eq!(extracted.definitions[0].framework, Framework::Unknown);
}

#[test]
fn side_effect_framework_imports_preserve_runtime_framework_metadata() {
    for (module, expected) in [
        ("@cucumber/cucumber", Framework::CucumberJs),
        (
            "@badeball/cypress-cucumber-preprocessor",
            Framework::CypressCucumber,
        ),
    ] {
        let definitions = extract_ts(&format!(
            "import '{module}';\nGiven('side effect framework', () => work());\n"
        ));
        assert_eq!(definitions.len(), 1, "{module}");
        assert_eq!(definitions[0].framework, expected, "{module}");
    }
}

#[test]
fn reports_unsupported_regexes_and_malformed_string_matchers() {
    let extracted = extract_detailed(
        r#"
Given(/value (?=ahead)/, () => work());
Given('broken \xZZ', () => broken());
Given('valid step', () => valid());
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(extracted.definitions.len(), 2);
    assert_eq!(extracted.diagnostics.len(), 3);
    assert!(extracted.diagnostics.iter().any(|diagnostic| {
        // A whole-file parse failure is a tolerated completeness warning, not a hard error; the
        // CLI decides fatality via `--fail-on-unparseable`/`--fail-on-incomplete`.
        diagnostic.level == ExtractionDiagnosticLevel::Warning
            && diagnostic.message.contains("syntax errors")
    }));
    assert!(extracted.diagnostics.iter().any(|diagnostic| {
        diagnostic.level == ExtractionDiagnosticLevel::Warning
            && diagnostic
                .message
                .contains("unsupported by static usage analysis")
    }));
    assert!(extracted.diagnostics.iter().any(|diagnostic| {
        diagnostic.level == ExtractionDiagnosticLevel::Error
            && diagnostic.message.contains("invalid JavaScript escape")
    }));
}

#[test]
fn supported_regexes_remain_authoritative_under_resource_limits() {
    for (matcher, flags) in [
        (r"^the user exists$", ""),
        (r"^the USER exists$", "i"),
        (r"^(?:one|two|three) users$", "u"),
    ] {
        assert_eq!(
            rust_regex_support(matcher, flags),
            RegexSupport::Supported,
            "{matcher}/{flags}"
        );
    }
}

// Canary for valid constructs outside the pinned grammars. When an upgrade accepts a row, move its
// expectation to the parseable controls rather than deleting coverage. Every case is synthetic.
#[test]
fn grammar_limitations_stay_incomplete() {
    let controls = [
        (
            SourceLanguage::Tsx,
            "const n=<panel>body</panel>; Given('clean',()=>n);",
        ),
        (
            SourceLanguage::TypeScript,
            "const x=<T>(v:T)=>v; const b=1<2; Given('clean',()=>x(b));",
        ),
        (
            SourceLanguage::JavaScript,
            "import x from './x.json' with {type:'json'}; Given('clean',()=>x);",
        ),
    ];
    for (language, source) in controls {
        let extracted = extract_detailed(source, &file(language)).unwrap();
        assert!(extracted.diagnostics.is_empty(), "{source}");
        assert_eq!(extracted.definitions.len(), 1, "{source}");
    }
    let limitations = [
        (
            SourceLanguage::TypeScript,
            "const x=f<typeof import('x')>();",
        ),
        (
            SourceLanguage::TypeScript,
            "const x=tag.a<{on:boolean}>`x`;",
        ),
        (
            SourceLanguage::TypeScript,
            "export type * as ns from './x';",
        ),
        (SourceLanguage::TypeScript, "type F=(string)=>void;"),
        (SourceLanguage::TypeScript, "type T=import('x').T[];"),
        (
            SourceLanguage::TypeScript,
            "const x={} as unknown as (typeof module)['key'];",
        ),
        (SourceLanguage::Tsx, "const x=<a href='?a=1&b=2' />;"),
        (SourceLanguage::Tsx, "const x=<a>a&b</a>;"),
        (SourceLanguage::Tsx, "const x=<a>&#128465;</a>;"),
        (SourceLanguage::Tsx, "const x=<a title='&#128465;' />;"),
        (SourceLanguage::JavaScript, "const x=<a href='?a=1&b=2' />;"),
        (SourceLanguage::JavaScript, "const x=<a>&#128465;</a>;"),
        (SourceLanguage::JavaScript, "const x=<button in />;"),
    ];
    for (language, construct) in limitations {
        let source =
            format!("Given('before',()=>first());\n{construct}\nGiven('after',()=>last());");
        let extracted = extract_detailed(&source, &file(language)).unwrap();
        let diagnostics: Vec<_> = extracted
            .diagnostics
            .iter()
            .filter(|diagnostic| crate::source_adapter::is_unparseable_diagnostic(diagnostic))
            .collect();
        assert_eq!(diagnostics.len(), 1, "{construct}");
        assert_eq!(
            diagnostics[0].level,
            ExtractionDiagnosticLevel::Warning,
            "{construct}"
        );
    }
}

#[test]
fn deeply_nested_handlers_do_not_use_the_process_stack() {
    let depth = 8_000;
    let source = format!(
        "Given('deep step', () => {}value{});",
        "[".repeat(depth),
        "]".repeat(depth)
    );
    let extracted = extract_detailed(&source, &file(SourceLanguage::TypeScript)).unwrap();
    assert_eq!(extracted.definitions.len(), 1);
}

#[test]
fn source_locations_count_unicode_code_points() {
    let definition = extract(
        "const prefix = '日本語'; Given('unicode column', () => work());",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap()
    .remove(0);
    assert_eq!(definition.location.column, 23);
}

#[test]
fn generator_handlers_are_extracted_and_comparable() {
    let definitions = extract(
        "Given('generator', function* () { yield performWork(); });",
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 1);
    assert!(definitions[0].handler.comparable);
}

#[test]
fn dynamic_matchers_and_handlers_emit_diagnostics_instead_of_disappearing() {
    let extracted = extract_detailed(
        "Given(dynamicMatcher, () => work()); Given('wrapped', wrap(handler)); Given('object handler', { timeout: 1 }); Given('missing handler');",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert_eq!(extracted.definitions.len(), 1);
    assert!(!extracted.definitions[0].handler.comparable);
    assert!(extracted
        .diagnostics
        .iter()
        .any(|diagnostic| diagnostic.message.contains("step matcher")));
    assert!(extracted
        .diagnostics
        .iter()
        .any(|diagnostic| diagnostic.message.contains("step handler")));
}

#[test]
fn unresolved_registration_shaped_calls_are_visible_without_flagging_helpers() {
    let cases = [
        (
            "import { Given } from '@company/bdd';\nGiven('missing', () => work());",
            1,
        ),
        ("const bdd = {}; bdd.Then('missing', () => work());", 1),
        (
            "Step('missing', () => work()); And('also missing', () => work());",
            2,
        ),
        ("helper('ordinary call', () => work());", 0),
        ("load().then(() => work());", 0),
        (
            "import * as utilities from '@company/helpers'; utilities.log('ordinary call');",
            0,
        ),
    ];

    for (source, expected_calls) in cases {
        let extracted = extract_detailed(source, &file(SourceLanguage::TypeScript)).unwrap();
        assert!(extracted.definitions.is_empty(), "{source}");
        let completeness = extracted
            .diagnostics
            .iter()
            .filter(|diagnostic| crate::source_adapter::is_completeness_diagnostic(diagnostic))
            .collect::<Vec<_>>();
        if expected_calls == 0 {
            assert!(completeness.is_empty(), "{source}");
        } else {
            assert_eq!(completeness.len(), 1, "{source}");
            assert!(
                completeness[0]
                    .message
                    .contains(&format!("{expected_calls} call(s)")),
                "{source}"
            );
        }
    }
}

#[test]
fn unresolved_registration_imports_name_the_module_in_diagnostics() {
    for source in [
        "import { Given } from '@company/bdd'; Given('missing', () => work());",
        "import * as bdd from '@company/bdd'; bdd.Given('missing', () => work());",
    ] {
        let extracted = extract_detailed(source, &file(SourceLanguage::TypeScript)).unwrap();
        let diagnostics = extracted
            .diagnostics
            .iter()
            .filter(|diagnostic| crate::source_adapter::is_completeness_diagnostic(diagnostic))
            .collect::<Vec<_>>();
        assert_eq!(diagnostics.len(), 1, "{source}");
        assert!(
            diagnostics[0]
                .message
                .contains("unresolved module `@company/bdd`"),
            "{source}: {}",
            diagnostics[0].message
        );
    }
}

#[test]
fn resolved_registration_with_an_unsupported_matcher_is_not_called_unresolved() {
    let extracted = extract_detailed(
        "Given(dynamicMatcher, () => work());",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert!(extracted.definitions.is_empty());
    assert!(extracted
        .diagnostics
        .iter()
        .any(|diagnostic| diagnostic.message.contains("step matcher")));
    assert!(extracted
        .diagnostics
        .iter()
        .any(crate::source_adapter::is_completeness_diagnostic));
    assert!(!extracted.diagnostics.iter().any(|d| d
        .message
        .starts_with(UNRESOLVED_REGISTRATION_DIAGNOSTIC_PREFIX)));
}

#[test]
fn unresolved_calls_remain_visible_when_the_same_file_yields_definitions() {
    let extracted = extract_detailed(
        r#"
import { Given } from '@cucumber/cucumber';
import { Then } from '@company/bdd';
Given('visible step', () => visible());
Then('invisible step', () => invisible());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert_eq!(extracted.definitions.len(), 1);
    let completeness = extracted
        .diagnostics
        .iter()
        .filter(|diagnostic| crate::source_adapter::is_completeness_diagnostic(diagnostic))
        .collect::<Vec<_>>();
    assert_eq!(completeness.len(), 1);
    assert_eq!(completeness[0].location.line, 5);
    assert!(completeness[0].message.contains("1 call(s)"));
}

#[test]
fn extracts_registrations_through_transparent_wrappers_and_static_subscripts() {
    let extracted = extract_detailed(
        r#"
import { Given } from '@cucumber/cucumber';
import * as bdd from '@cucumber/cucumber';
(Given)('parenthesized', () => first());
(Given as typeof Given)('asserted', () => second());
(Given satisfies typeof Given)('satisfied', () => third());
Given!('non-null', () => fourth());
(<typeof Given>Given)('type-asserted', () => fifth());
(Given<string>)('instantiated', () => sixth());
bdd['Then']('subscripted', () => seventh());
bdd['Th\u0065n']('escaped subscript', () => eighth());
(bdd as typeof bdd).When('wrapped namespace', () => ninth());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert_eq!(extracted.definitions.len(), 9);
    assert_eq!(extracted.definitions[0].matcher, "parenthesized");
    assert_eq!(extracted.definitions[1].matcher, "asserted");
    assert_eq!(extracted.definitions[2].matcher, "satisfied");
    assert_eq!(extracted.definitions[3].matcher, "non-null");
    assert_eq!(extracted.definitions[4].matcher, "type-asserted");
    assert_eq!(extracted.definitions[5].matcher, "instantiated");
    assert_eq!(extracted.definitions[6].registration, "Then");
    assert_eq!(extracted.definitions[7].matcher, "escaped subscript");
    assert_eq!(extracted.definitions[8].matcher, "wrapped namespace");
    assert!(!extracted
        .diagnostics
        .iter()
        .any(crate::source_adapter::is_completeness_diagnostic));
}

#[test]
fn static_subscript_registrations_are_included_in_completeness_diagnostics() {
    let extracted = extract_detailed(
        r#"
import { Given } from '@cucumber/cucumber';
import * as custom from '@company/bdd';
Given('visible step', () => visible());
custom['Then']('invisible step', () => invisible());
"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert_eq!(extracted.definitions.len(), 1);
    let completeness = extracted
        .diagnostics
        .iter()
        .filter(|diagnostic| crate::source_adapter::is_completeness_diagnostic(diagnostic))
        .collect::<Vec<_>>();
    assert_eq!(completeness.len(), 1);
    assert_eq!(completeness[0].location.line, 5);
}

#[test]
fn computed_subscripts_and_lowercase_then_calls_are_not_registration_evidence() {
    let extracted = extract_detailed(
        "const property = 'Then'; custom[property]('dynamic', handler); promise['then'](handler);",
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();

    assert!(extracted.definitions.is_empty());
    assert!(!extracted
        .diagnostics
        .iter()
        .any(crate::source_adapter::is_completeness_diagnostic));
}

#[test]
fn deeply_parenthesized_registration_callees_are_unwrapped_iteratively() {
    let depth = 1_000;
    let source = format!(
        "{}Given{}('deep', () => work());",
        "(".repeat(depth),
        ")".repeat(depth)
    );
    let extracted = extract_detailed(&source, &file(SourceLanguage::TypeScript)).unwrap();

    assert_eq!(extracted.definitions.len(), 1);
    assert_eq!(extracted.definitions[0].matcher, "deep");
}

#[test]
fn positional_registration_wrappers_are_inferred_but_reordering_ones_are_not() {
    let inferred = extract_ts(
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { Given(text, handler); }
step("wrapped step", () => work());"#,
    );
    assert_eq!(inferred.len(), 1);
    assert_eq!(inferred[0].matcher, "wrapped step");
    // A wrapper resolves to the registration it forwards to, so the step is a Given.
    assert_eq!(inferred[0].registration, "Given");

    let returned = extract_ts(
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { return Given(text, handler); }
step("returned step", () => work());"#,
    );
    assert_eq!(returned.len(), 1);
    assert_eq!(returned[0].matcher, "returned step");

    // Every shape below breaks the positional correspondence the rule depends on, so extracting
    // argument 0 as the matcher would attribute the wrong text to the wrong handler.
    for source in [
        // Reordered forward.
        r#"import { Given } from "@cucumber/cucumber";
function step(handler, text) { Given(text, handler); }
step(() => work(), "wrapped step");"#,
        // Rewritten matcher.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { Given("prefix " + text, handler); }
step("wrapped step", () => work());"#,
        // Destructured parameters carry no positional guarantee.
        r#"import { Given } from "@cucumber/cucumber";
function step({ text }, handler) { Given(text, handler); }
step({ text: "wrapped step" }, () => work());"#,
        // A local helper that never reaches a registration is not a wrapper.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { return [text, handler]; }
step("wrapped step", () => work());"#,
        // A returned callback defers registration until that callback is invoked.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { return () => Given(text, handler); }
step("wrapped step", () => work());"#,
        // A conditional call is not guaranteed to register when the wrapper is invoked.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { if (enabled) Given(text, handler); }
step("wrapped step", () => work());"#,
        // Multiple statements require data-flow reasoning and use the explicit config escape hatch.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { trace(text); Given(text, handler); }
step("wrapped step", () => work());"#,
        // Async bodies can suspend before reaching the registration call.
        r#"import { Given } from "@cucumber/cucumber";
async function step(text, handler) { Given(text, handler); }
step("wrapped step", () => work());"#,
        // Generator bodies do not run merely because the generator function is called.
        r#"import { Given } from "@cucumber/cucumber";
function* step(text, handler) { Given(text, handler); }
step("wrapped step", () => work());"#,
        // A nested declaration must not escape its lexical scope into a file-wide alias.
        r#"import { Given } from "@cucumber/cucumber";
function outer() { function step(text, handler) { Given(text, handler); } }
step("wrapped step", () => work());"#,
    ] {
        assert!(
            extract_ts(source).is_empty(),
            "must not infer a wrapper from: {source}"
        );
    }
}

#[test]
fn wrapper_inference_follows_chains_without_looping_on_self_reference() {
    let chained = extract_ts(
        r#"import { Given } from "@cucumber/cucumber";
function inner(text, handler) { Given(text, handler); }
function outer(text, handler) { inner(text, handler); }
outer("chained step", () => work());"#,
    );
    assert_eq!(chained.len(), 1);
    assert_eq!(chained[0].matcher, "chained step");

    // A self-recursive helper never reaches a registration, so it must not resolve to itself.
    assert!(extract_ts(
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { step(text, handler); }
step("looping step", () => work());"#,
    )
    .is_empty());
}

#[test]
fn wrapper_inference_resolves_long_chains_without_quadratic_work() {
    // Wrappers form a forward graph. Walking it from the known registrations visits each wrapper
    // once, so a chain declared in reverse order — the worst ordering for a naive fixpoint —
    // still resolves in linear time.
    let chain = |depth: usize| {
        let mut source = String::from("import { Given } from \"@cucumber/cucumber\";\n");
        for index in (1..depth).rev() {
            source.push_str(&format!(
                "function w{index}(text, handler) {{ w{}(text, handler); }}\n",
                index - 1
            ));
        }
        source.push_str("function w0(text, handler) { Given(text, handler); }\n");
        source.push_str(&format!("w{}(\"chained\", () => work());\n", depth - 1));
        source
    };

    assert_eq!(extract_ts(&chain(200)).len(), 1);
    assert_eq!(extract_ts(&chain(4000)).len(), 1);
}

#[test]
fn registration_discovery_covers_static_alias_and_shadowing_forms() {
    let source = r#"
import type { Given as TypeGiven } from '@cucumber/cucumber';
import /* comment before the modifier */ type { Given as CommentTypeGiven } from '@cucumber/cucumber';
import { type Then as SpecifierTypeThen } from '@cucumber/cucumber';
import { Given as ImportedGiven } from '@cucumber/cucumber';
export /* comment before the modifier */ type { When as ExportedTypeWhen } from '@cucumber/cucumber';
export { type Then as ExportedSpecifierTypeThen } from '@cucumber/cucumber';
const cucumber = require('@cucumber/cucumber');
const { When: RequiredWhen, Then } = require('@cucumber/cucumber');
const { Given: NamespaceGiven } = cucumber;
const AliasGiven = ImportedGiven;
let AssignedGiven;
AssignedGiven = AliasGiven;

export function wrapped(text: string, handler: () => void) {
  return (((ImportedGiven)))(text, handler);
}

ImportedGiven('imported', () => work());
cucumber.Then('namespace', () => work());
cucumber['When']('subscript', () => work());
RequiredWhen('required', () => work());
Then('destructured', () => work());
NamespaceGiven('namespace destructured', () => work());
AliasGiven('alias', () => work());
AssignedGiven('assigned', () => work());
wrapped('wrapped', () => work());
TypeGiven('type only', () => work());
CommentTypeGiven('commented type only', () => work());
SpecifierTypeThen('specifier type only', () => work());
ExportedTypeWhen('exported type only', () => work());
ExportedSpecifierTypeThen('exported specifier type only', () => work());
"#;
    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 9);
    assert!(definitions
        .iter()
        .all(|definition| definition.framework == Framework::CucumberJs));
    for matcher in [
        "type only",
        "commented type only",
        "specifier type only",
        "exported type only",
        "exported specifier type only",
    ] {
        assert!(!definitions
            .iter()
            .any(|definition| definition.matcher == matcher));
    }

    let untrusted_create_bdd = extract_ts(
        "const factory = createBdd(); const { Given } = factory; Given('not bdd', () => work());",
    );
    assert!(untrusted_create_bdd.is_empty());
}

#[test]
fn configured_assertion_modules_are_trusted_in_every_import_form() {
    let configured = vec!["./fixtures".to_owned()];
    let assertion = |header: &str, factory: &str, modules: &[String]| {
        let mut session =
            TypeScriptExtractionSession::for_root(std::path::Path::new("."), &[], modules);
        let source = format!(
            "{header}\nimport {{ Given }} from '@cucumber/cucumber';\n\
             Given('a declared factory', () => {factory}(gauge()).toBe(1));"
        );
        let extracted =
            extract_detailed_impl(&source, &file(SourceLanguage::TypeScript), &mut session)
                .unwrap();
        assert_eq!(extracted.definitions.len(), 1, "{header}");
        extracted.definitions[0]
            .handler
            .behavior_signature
            .iter()
            .any(|event| event.starts_with("assert:"))
    };

    // A declared module carries the same provenance a recognized package does, so every import form
    // it supports is trusted. The namespace form was previously accepted only for a built-in
    // module, which made the setting silently depend on how the import was spelled.
    for (header, factory) in [
        ("import { expect } from './fixtures';", "expect"),
        ("import * as fixtures from './fixtures';", "fixtures.expect"),
    ] {
        assert!(
            assertion(header, factory, &configured),
            "declared module must be trusted: {header}"
        );
        assert!(
            !assertion(header, factory, &[]),
            "undeclared module must stay untrusted: {header}"
        );
    }
}

#[test]
fn configured_registration_names_override_inference_without_duplicating_known_aliases() {
    let configured = vec!["step".to_owned(), "Given".to_owned()];
    let mut session =
        TypeScriptExtractionSession::for_root(std::path::Path::new("."), &configured, &[]);
    let source = "function step(text, handler) { dynamic(text, handler); }\nstep('configured', () => work());";
    let extracted =
        extract_detailed_impl(source, &file(SourceLanguage::TypeScript), &mut session).unwrap();
    assert_eq!(extracted.definitions.len(), 1);
    assert_eq!(extracted.definitions[0].registration, "step");
}

/// Pins the wrapper forwards that may and may not be followed. Wrapping the forwarded call in
/// parentheses does not change what it calls, so the wrapper must still resolve; a namespaced
/// callee and a call that forwards fewer than two arguments both break the positional
/// correspondence the extractor depends on, so inferring a wrapper from them would pair a matcher
/// with a handler that never travelled together.
#[test]
fn wrapper_forwards_unwrap_parentheses_but_reject_namespaced_or_short_calls() {
    let parenthesized = extract_ts(
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { return (Given(text, handler)); }
step("parenthesized forward", () => work());"#,
    );
    assert_eq!(parenthesized.len(), 1);
    assert_eq!(parenthesized[0].matcher, "parenthesized forward");
    assert_eq!(parenthesized[0].registration, "Given");

    for source in [
        // A namespaced callee is not the positional identifier forward the rule accepts.
        r#"import * as bdd from "@cucumber/cucumber";
function step(text, handler) { bdd.Given(text, handler); }
step("namespaced forward", () => work());"#,
        // Fewer than two forwarded arguments cannot carry both the matcher and the handler.
        r#"import { Given } from "@cucumber/cucumber";
function step(text, handler) { Given(text); }
step("short forward", () => work());"#,
    ] {
        assert!(
            extract_ts(source).is_empty(),
            "must not infer a wrapper from: {source}"
        );
    }
}

/// Pins that a type-only specifier standing beside a runtime one never becomes a registration
/// binding, whether its module resolves or not. `import { type Given as Shape, Given as Setup }`
/// erases `Shape` at compile time, so treating it as an alias would invent a step definition for a
/// call that cannot exist — and, for an unresolved module, would overstate how many
/// registration-shaped calls the file actually lost.
#[test]
fn type_only_specifiers_never_alias_registrations_in_resolved_or_unresolved_imports() {
    let definitions = extract_ts(
        r#"import { type Given as Shape, Given as Setup } from '@cucumber/cucumber';
Setup('a step', () => work());
Shape('not a step', () => work());"#,
    );
    assert_eq!(definitions.len(), 1);
    assert_eq!(definitions[0].matcher, "a step");
    assert_eq!(definitions[0].registration, "Given");

    let extracted = extract_detailed(
        r#"import { type Given as Shape, When as Setup } from '@company/bdd';
Setup('missing', () => work());
Shape('not a registration', () => work());"#,
        &file(SourceLanguage::TypeScript),
    )
    .unwrap();
    assert!(extracted.definitions.is_empty());
    let completeness = extracted
        .diagnostics
        .iter()
        .filter(|diagnostic| crate::source_adapter::is_completeness_diagnostic(diagnostic))
        .collect::<Vec<_>>();
    assert_eq!(completeness.len(), 1);
    assert!(
        completeness[0].message.contains("1 call(s)"),
        "{}",
        completeness[0].message
    );
}

/// Pins which names a re-export or a destructured `require` turns into registration aliases. Only
/// a name the framework actually exports counts: a re-exported `World`, a positional array
/// binding, and a rest element all name something the module never published as a registration, so
/// calling them must not be extracted as a step definition.
#[test]
fn re_exports_and_destructures_only_alias_names_the_framework_publishes() {
    let re_exported = extract_ts(
        r#"export { World, Given as Setup } from '@cucumber/cucumber';
Setup('a step', () => work());
World('not a step', () => work());"#,
    );
    assert_eq!(re_exported.len(), 1);
    assert_eq!(re_exported[0].matcher, "a step");
    assert_eq!(re_exported[0].registration, "Given");

    assert!(extract_ts(
        r#"const [Setup] = require('@cucumber/cucumber');
Setup('not a step', () => work());"#,
    )
    .is_empty());

    let with_rest = extract_ts(
        r#"const { Given: Setup, ...others } = require('@cucumber/cucumber');
Setup('a step', () => work());
others.Given('not a step', () => work());"#,
    );
    assert_eq!(with_rest.len(), 1);
    assert_eq!(with_rest[0].matcher, "a step");
    assert_eq!(with_rest[0].registration, "Given");
}

/// The language-specific adapters must refuse sources written in another language.
///
/// Each adapter owns one tree-sitter grammar. Parsing a `.js` file with the TypeScript grammar
/// silently changes how ambiguous syntax is read, so the mismatch has to surface as an error
/// naming the adapter and the file instead of producing definitions from the wrong grammar.
#[test]
fn language_adapters_reject_sources_from_another_language() {
    let error = TYPESCRIPT_ADAPTER
        .extract(
            "Given('a step', () => work());",
            &file(SourceLanguage::JavaScript),
        )
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("typescript adapter cannot parse")
            && error.contains("JavaScript")
            && error.contains("features/steps/example.ts"),
        "{error}"
    );

    let error = JAVASCRIPT_ADAPTER
        .extract(
            "Given('a step', () => work());",
            &file(SourceLanguage::TypeScript),
        )
        .unwrap_err()
        .to_string();
    assert!(error.contains("javascript adapter cannot parse"), "{error}");
}

/// Default parameter initializers of a decorated method are part of that method's identity.
///
/// A default runs on every invocation, so two decorated steps that differ only in what their
/// defaults evaluate are not duplicates, while two that differ only in the local name bound to an
/// identical default are. An empty body with a default is also not a stub: the initializer still
/// executes, and calling it trivial would suppress real findings.
#[test]
fn decorated_method_parameter_defaults_are_part_of_handler_identity() {
    let definitions = extract_ts(
        r#"
import { Given } from 'playwright-bdd/decorators';
class Steps {
  @Given('the first page opens')
  first({ page: tab = makePage() }) { tab.goto('/'); }

  @Given('the second page opens')
  second({ page: view = makePage() }) { view.goto('/'); }

  @Given('the third page opens')
  third({ page: tab = makeOtherPage() }) { tab.goto('/'); }

  @Given('the fourth page is defaulted but empty')
  fourth({ page: tab = makePage() }) {}

  @Given('the fifth page is empty')
  fifth({ page: tab }) {}
}
"#,
    );

    assert_eq!(definitions.len(), 5);
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_ne!(
        definitions[0].handler.alpha_normalized,
        definitions[2].handler.alpha_normalized
    );
    assert_eq!(
        definitions[0].handler.behavior_signature,
        ["method:instance sync", "call:makePage", "call:v0#goto"]
    );
    assert!(!definitions[3].handler.trivial);
    assert!(definitions[4].handler.trivial);
}

/// A bare default parameter of a decorated method is serialized with its initializer too.
///
/// The JavaScript grammar represents `value = 1` as a plain assignment pattern rather than the
/// TypeScript `required_parameter` shape, so the parameter serializer has to recognize both or
/// JavaScript decorated steps would compare as if they had no defaults at all.
#[test]
fn javascript_decorated_method_defaults_change_handler_identity() {
    let source = |initializer: &str| {
        format!(
            r#"
import {{ Given }} from 'playwright-bdd/decorators';
class Steps {{
  @Given('the page opens')
  open(page = {initializer}) {{ page.goto('/'); }}
}}
"#
        )
    };
    let first = extract(&source("makePage()"), &file(SourceLanguage::JavaScript)).unwrap();
    let renamed = extract(
        &source("makePage()").replace("page", "tab"),
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    let other = extract(
        &source("makeOtherPage()"),
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();

    assert_eq!(first.len(), 1);
    assert_eq!(
        first[0].handler.behavior_signature,
        ["method:instance sync", "call:makePage", "call:v0#goto"]
    );
    assert_eq!(
        first[0].handler.alpha_normalized,
        renamed[0].handler.alpha_normalized
    );
    assert_ne!(
        first[0].handler.alpha_normalized,
        other[0].handler.alpha_normalized
    );
}

/// A named handler resolves to the binding JavaScript scoping would actually run.
///
/// Two declarations can share a name: an inner function shadows an outer one, and a later
/// assignment in the same scope replaces an earlier one. Picking the wrong candidate would
/// fingerprint a body that never executes and report duplicates between unrelated steps.
#[test]
fn named_handlers_resolve_to_the_innermost_and_latest_binding() {
    let nested = extract(
        r#"
function run() { outerAction(); }
function register() {
  function run() { innerAction(); }
  Given('a nested registration', run);
}
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(nested.len(), 1);
    assert_eq!(nested[0].handler.behavior_signature, ["call:innerAction"]);

    let redeclared = extract(
        r#"
var run = () => firstAction();
var run = () => secondAction();
Given('a redeclared registration', run);
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(redeclared.len(), 1);
    assert_eq!(
        redeclared[0].handler.behavior_signature,
        ["call:secondAction"]
    );
}

/// A handler named through a property read is not resolved to a body.
///
/// Nothing in one file proves what `steps.run` holds at registration time, so the definition has
/// to stay visible but uncomparable. Treating it as an empty body would also mark it a stub and
/// hide a real handler behind a pending-step finding.
#[test]
fn property_handler_expressions_stay_uncomparable() {
    for source in [
        "Given('a member handler', steps.run);",
        "Given('a bound member handler', steps.run.bind(steps));",
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert!(!definitions[0].handler.comparable, "{source}");
        assert!(!definitions[0].handler.trivial, "{source}");
    }
}

/// Handlers whose only effect is a nullish value or an explicit marker are stubs.
///
/// `() => null` and `() => undefined` execute nothing, and `throw pending` names the marker
/// directly rather than through a string. Failing to recognize these shapes would let unfinished
/// steps compare as real duplicate behavior.
#[test]
fn nullish_and_marker_handlers_are_recognized_as_stubs() {
    let definitions = extract(
        r#"
Given('null stub', () => null);
Given('undefined stub', () => undefined);
Given('thrown marker stub', () => { throw pending; });
Given('real handler', () => doWork());
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 4);
    assert!(definitions[0].handler.trivial);
    assert!(definitions[1].handler.trivial);
    assert!(definitions[2].handler.trivial);
    assert!(!definitions[3].handler.trivial);
}

/// A call on a receiver with no static name keeps the structural spelling of that call.
///
/// `'text'.trim()` has no binding to normalize, so inventing a receiver name would make it
/// collide with every other `.trim()` call. The event must retain the serialized callee instead.
#[test]
fn calls_on_unnameable_receivers_keep_their_structural_callee() {
    let definitions = extract(
        r#"
Given('literal receiver', () => 'the value'.trim());
Given('other literal receiver', () => 'the value'.trimEnd());
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 2);
    assert_eq!(definitions[0].handler.behavior_signature.len(), 1);
    assert!(
        definitions[0].handler.behavior_signature[0].starts_with("call:(member_expression"),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
    assert_ne!(
        definitions[0].handler.behavior_signature,
        definitions[1].handler.behavior_signature
    );
}

/// Comments never contribute to a normalized handler fingerprint.
///
/// Tree-sitter keeps comments as named nodes, so a serializer that did not skip them would report
/// two identical handlers as different merely because one carries an explanatory note.
#[test]
fn comments_do_not_change_normalized_handler_fingerprints() {
    let definitions = extract(
        r#"
Given('with comment', () => { /* explain the wait */ work(); });
Given('without comment', () => { work(); });
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 2);
    assert_eq!(
        definitions[0].handler.normalized,
        definitions[1].handler.normalized
    );
    assert_ne!(definitions[0].handler.exact, definitions[1].handler.exact);
}

/// A loop declaration named `expect` shadows the ambient assertion only where it is in scope.
///
/// `let` in a `for` head belongs to the loop, while `var` hoists to the enclosing function. Using
/// the wrong scope either keeps trusting a name the loop replaced or silently drops assertion
/// evidence from statements the loop never covered.
#[test]
fn loop_declarations_shadow_the_ambient_assertion_within_their_scope() {
    let lexical = extract_ts(
        r#"
Then('lexical loop declaration', ({ state }) => {
  for (let expect = 0; expect < 1; expect += 1) { expect(state).toBe('ready'); }
  expect(state).toBe('done');
});
"#,
    );
    assert_eq!(lexical.len(), 1);
    assert_eq!(
        lexical[0]
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .count(),
        1,
        "{:?}",
        lexical[0].handler.behavior_signature
    );

    let hoisted = extract_ts(
        r#"
Then('hoisted loop declaration', ({ state }) => {
  for (var expect = 0; expect < 1; expect += 1) { record(expect); }
  expect(state).toBe('done');
});
"#,
    );
    assert_eq!(hoisted.len(), 1);
    assert!(
        hoisted[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        hoisted[0].handler.behavior_signature
    );
}

/// A namespace declared inside a block shadows the ambient assertion only within that block.
///
/// A nested `namespace expect` is a runtime value, unlike a module-level one it is not file-wide.
/// Treating it as file-wide would erase assertion evidence from unrelated handlers; ignoring it
/// would attribute assertion semantics to a local object that is not the assertion factory.
#[test]
fn nested_namespace_declarations_shadow_assertions_only_inside_their_block() {
    let definitions = extract_ts(
        r#"
Then('assertion inside the namespace block', ({ state }) => {
  {
    namespace expect { export const custom = true; }
    expect(state).toBe('ready');
  }
});
Then('assertion beside the namespace block', ({ state }) => {
  { namespace expect { export const custom = true; } }
  expect(state).toBe('ready');
});
"#,
    );
    assert_eq!(definitions.len(), 2);
    assert!(
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
    assert!(
        definitions[1]
            .handler
            .behavior_signature
            .iter()
            .any(|event| event.starts_with("assert:")),
        "{:?}",
        definitions[1].handler.behavior_signature
    );
}

/// `import ns = require('@playwright/test')` binds an assertion namespace, not the factory.
///
/// The TypeScript require form is the only import shape whose trust depends on the module: the
/// standalone `expect` package is itself callable, every other assertion package exposes `expect`
/// as a property. Conflating the two would either lose assertion evidence or invent it.
#[test]
fn import_require_clauses_bind_assertion_namespaces_by_module() {
    let namespaced = extract_ts(
        r#"
import testApi = require('@playwright/test');
Then('namespace property assertion', ({ state }) => testApi.expect(state).toBe('ready'));
"#,
    );
    assert_eq!(namespaced.len(), 1);
    assert!(
        namespaced[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
        "{:?}",
        namespaced[0].handler.behavior_signature
    );

    // The namespace itself is not callable, so calling it is ordinary behavior, not an assertion.
    let called = extract_ts(
        r#"
import testApi = require('@playwright/test');
Then('namespace called directly', ({ state }) => testApi(state).toBe('ready'));
"#,
    );
    assert_eq!(called.len(), 1);
    assert!(
        called[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        called[0].handler.behavior_signature
    );
}

/// An asymmetric matcher is recognized through a namespaced factory exactly as through the global.
///
/// `testApi.expect.objectContaining(...)` and `expect.objectContaining(...)` describe the same
/// expected value, so they must record the same assertion event; otherwise the same assertion
/// written with a namespace import would never match its ambient spelling.
#[test]
fn asymmetric_matchers_are_recognized_through_namespaced_factories() {
    let namespaced = extract_ts(
        r#"
import * as testApi from '@playwright/test';
Then('namespaced matcher', ({ state }) =>
  testApi.expect(state).toEqual(testApi.expect.objectContaining({ ready: true })));
"#,
    );
    let ambient = extract_ts(
        r#"
Then('ambient matcher', ({ state }) =>
  expect(state).toEqual(expect.objectContaining({ ready: true })));
"#,
    );
    assert_eq!(namespaced.len(), 1);
    assert_eq!(ambient.len(), 1);
    assert!(
        namespaced[0].handler.behavior_signature[0].starts_with("assert:expect#toEqual:"),
        "{:?}",
        namespaced[0].handler.behavior_signature
    );
    assert_eq!(
        namespaced[0].handler.behavior_signature,
        ambient[0].handler.behavior_signature
    );

    // A plain call is not a matcher, so its value cannot be compared across files.
    let opaque = extract_ts(
        r#"
Then('opaque expected value', ({ state }) => expect(state).toEqual(buildExpected()));
"#,
    );
    assert_eq!(opaque.len(), 1);
    assert_ne!(
        opaque[0].handler.behavior_signature,
        ambient[0].handler.behavior_signature
    );
}

/// A require destructured into an array pattern never establishes assertion trust.
///
/// `const [expect] = require('expect')` reads index `0` of the module, not its `expect` export, so
/// the local name is an unrelated runtime binding that must shadow the ambient factory instead of
/// inheriting its provenance.
#[test]
fn array_destructured_requires_shadow_rather_than_trust_the_assertion_factory() {
    let definitions = extract_ts(
        r#"
const [expect] = require('expect');
Then('array destructured require', ({ state }) => expect(state).toBe('ready'));
"#,
    );
    assert_eq!(definitions.len(), 1);
    assert!(
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
}

/// Type-only specifiers beside a runtime `expect` import neither shadow nor gain trust.
///
/// The erased names never exist at runtime, so folding them into the shadow set would revoke the
/// trust the runtime specifier in the same statement just established.
#[test]
fn type_only_specifiers_beside_a_runtime_expect_import_preserve_trust() {
    let definitions = extract_ts(
        r#"
import { expect, type Locator } from '@playwright/test';
Then('mixed specifier import', ({ state }) => expect(state).toBe('ready'));
"#,
    );
    assert_eq!(definitions.len(), 1);
    assert!(
        definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
}

/// A registration decorator still finds its method across other decorators on the same member.
///
/// Tree-sitter lists decorators as siblings preceding the member, so the resolver has to skip
/// consecutive decorators. Stopping at the first sibling would drop every step whose method also
/// carries a logging or fixture decorator, in either order.
#[test]
fn decorator_registrations_skip_sibling_decorators_to_reach_their_method() {
    for source in [
        r#"
import { Given } from 'playwright-bdd/decorators';
class Steps {
  @Given('a decorated step')
  @log()
  run() { work(); }
}
"#,
        r#"
import { Given } from 'playwright-bdd/decorators';
class Steps {
  @log()
  @Given('a decorated step')
  run() { work(); }
}
"#,
    ] {
        let definitions = extract_ts(source);
        assert_eq!(definitions.len(), 1, "{source}");
        assert_eq!(definitions[0].matcher, "a decorated step", "{source}");
        assert_eq!(
            definitions[0].handler.behavior_signature,
            ["method:instance sync", "call:work"],
            "{source}"
        );
    }
}

/// An assertion chain remains recognizable through an angle-bracket type assertion.
///
/// `<any>expect(state)` is erased at runtime, so the assertion it wraps must record the same
/// behavior as the unwrapped spelling; otherwise a cast added for type reasons would silently
/// make two identical assertions incomparable.
#[test]
fn assertion_chains_unwrap_angle_bracket_type_assertions() {
    let asserted =
        extract_ts("Then('cast assertion', ({ state }) => (<any>expect(state)).toBe('ready'));");
    let plain = extract_ts("Then('plain assertion', ({ state }) => expect(state).toBe('ready'));");
    assert_eq!(asserted.len(), 1);
    assert_eq!(plain.len(), 1);
    assert!(
        asserted[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
        "{:?}",
        asserted[0].handler.behavior_signature
    );
    assert_eq!(
        asserted[0].handler.behavior_signature,
        plain[0].handler.behavior_signature
    );
}

/// An awaited angle-bracket cast still resolves to the assertion it wraps.
///
/// `await` is not erased the way a cast is, so the chain walker has to step through both. A cast
/// added purely for typing must not make an otherwise identical assertion incomparable.
#[test]
fn awaited_angle_bracket_casts_still_resolve_the_assertion_chain() {
    let cast = extract_ts(
        "Then('awaited cast assertion', async ({ state }) => (await <any>expect(state)).toBe('ready'));",
    );
    let plain = extract_ts(
        "Then('awaited assertion', async ({ state }) => (await expect(state)).toBe('ready'));",
    );
    assert_eq!(cast.len(), 1);
    assert_eq!(plain.len(), 1);
    assert!(
        cast[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
        "{:?}",
        cast[0].handler.behavior_signature
    );
    assert_eq!(
        cast[0].handler.behavior_signature,
        plain[0].handler.behavior_signature
    );
}

/// A `for` head that declares nothing leaves the surrounding bindings in place.
///
/// Only a declaration keyword introduces a loop binding. Treating the head of `for (;;)` as one
/// would invent a binding that shadows the ambient assertion factory and silently drop assertion
/// evidence from every statement in the loop body.
#[test]
fn loop_heads_without_a_declaration_introduce_no_binding() {
    let definitions = extract_ts(
        r#"
Then('loop without a declaration', ({ state }) => {
  for (;;) { expect(state).toBe('ready'); break; }
});
"#,
    );
    assert_eq!(definitions.len(), 1);
    assert_eq!(
        definitions[0].handler.behavior_signature[0],
        "for_statement"
    );
    assert!(
        definitions[0].handler.behavior_signature[1].starts_with("assert:expect#toBe:"),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
}

/// A labelled module-level `var` is still a module binding and shadows the ambient factory.
///
/// A label wraps the declaration without introducing a scope, so the declaration belongs to the
/// module. Missing that would keep trusting an ambient `expect` the file has replaced.
#[test]
fn labelled_module_level_var_declarations_shadow_the_ambient_assertion() {
    let definitions = extract_ts(
        r#"
outer: var expect = makeLocalAssertion();
Then('labelled module var', ({ state }) => expect(state).toBe('ready'));
"#,
    );
    assert_eq!(definitions.len(), 1);
    assert!(
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        definitions[0].handler.behavior_signature
    );
}

/// Only a write that names a binding can revoke that binding's assertion trust.
///
/// `testApi.expect = custom` replaces the factory the namespace holds, while `makeApi().expect =
/// custom` writes to an object no binding in this file names. Treating the second as a write to
/// `testApi` would discard assertion evidence from every handler in the file.
#[test]
fn only_named_receivers_revoke_namespace_assertion_trust() {
    let assertion_events = |write: &str| {
        let definitions = extract_ts(&format!(
            r#"
import * as testApi from '@playwright/test';
{write}
Then('namespace assertion', ({{ state }}) => testApi.expect(state).toBe('ready'));
"#
        ));
        assert_eq!(definitions.len(), 1, "{write}");
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .count()
    };

    assert_eq!(assertion_events("makeApi().expect = custom;"), 1);
    assert_eq!(assertion_events("testApi.expect = custom;"), 0);
}

/// A write resolves through the chain of enclosing scopes, not only the innermost and the module.
///
/// The receiver sits one block below the block that binds `testApi`, so resolving it correctly
/// requires walking the enclosing-scope chain past a scope that binds nothing. The discriminating
/// shape is that middle binding: with it, the write names a local and module trust survives;
/// without it, the same write reaches the module and revokes trust. A scope chain that jumped
/// straight to the module would answer the shadowed case wrongly.
#[test]
fn nested_block_writes_resolve_to_the_shadowing_binding_not_the_namespace() {
    let assertion_events = |binding: &str| {
        let definitions = extract_ts(&format!(
            r#"
import * as testApi from '@playwright/test';
function helper() {{
  {binding}
  {{
    testApi.expect = custom;
  }}
}}
Then('namespace assertion', ({{ state }}) => testApi.expect(state).toBe('ready'));
"#
        ));
        assert_eq!(definitions.len(), 1, "{binding}");
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .count()
    };

    assert_eq!(assertion_events("let testApi = other;"), 1);
    assert_eq!(assertion_events("let unrelated = other;"), 0);
}

/// Assertion-alias discovery stays linear across deep scopes dense with assignment edges.
///
/// Every assignment resolves its receiver to an enclosing binding. Resolving that through the
/// parse tree's ancestors is quadratic in nesting depth, because tree-sitter restarts each parent
/// lookup from the root; deeply nested generated bundles reach that cost in practice. The
/// discriminating shape is the combination the naive walk is worst on: deep nesting, wide sibling
/// runs, and an assignment on every line. One statement per line keeps the mean line short, so the
/// content filter would analyze rather than skip a file of this shape. Pre-fix this effectively
/// hangs; the assertions only check that it terminates with the expected extraction.
#[test]
fn alias_provenance_resolves_deep_scopes_with_many_assignment_edges_without_quadratic_work() {
    let mut source = String::from("import { Given } from '@cucumber/cucumber';\n");
    for depth in 0..40 {
        source.push_str(&format!("function level{depth}() {{\n"));
        for index in 0..50 {
            source.push_str(&format!("var a{index} = b{index};\n"));
            source.push_str(&format!("a{index} = b{index};\n"));
        }
    }
    source.push_str("Given('deep', () => work());\n");
    source.push_str(&"}\n".repeat(40));

    let definitions = extract_ts(&source);
    assert_eq!(definitions.len(), 1);
}

/// Alias propagation terminates when the alias graph closes a positive-depth cycle.
///
/// An assignment through a dynamically-keyed subscript records a property-depth edge, and reused
/// names close those edges into a cycle whose depth rises on every lap. Because a write's effect on
/// trust is decided once its depth reaches the copy-cross ceiling, propagation saturates depth
/// there; without that, a graph that closes such a cycle raises the depth forever and never
/// finishes. The body below is reduced by delta-debugging from the `jquery-3.5.1.min.js` selector
/// engine — the smallest fragment of it that still hangs — because the trigger is a property of the
/// whole graph, not of any one statement: `while(a=a[l])` self-references `a` while the nested
/// cache assignments reach it through subscripts on the same name. Isolated pieces of it do not
/// reproduce, so the fragment is kept whole; the assertion only checks that extraction terminates
/// with the step still analyzed.
#[test]
fn alias_propagation_terminates_on_cyclic_subscript_reassignments() {
    let source = r#"
import { expect } from 'chai';
function child(a, c, e, f, h, k, l, m, o, p, r, s, u, x, y, S) {
  d = !1;
  if (c) {
    if (y) {
      while (l) {
        a = e;
        while (a = a[l]) if (x ? a.nodeName.toLowerCase() === f : 1 === a.nodeType) return !1;
        u = l = "only" === h && !u && "nextSibling";
      }
      return !0;
    }
    if (u = [m ? c.firstChild : c.lastChild], m && p) {
      d = (s = (r = (i = (o = (a = c)[S] || (a[S] = {}))[a.uniqueID] || (o[a.uniqueID] = {}))[h] || [])[0] === k && r[1]) && r[2];
    }
  }
}
Then('subscript cycle', ({ state }) => expect(state).toBe('ready'));
"#;

    let definitions = extract_ts(source);
    assert_eq!(definitions.len(), 1);
    assert_eq!(
        definitions[0]
            .handler
            .behavior_signature
            .iter()
            .filter(|event| event.starts_with("assert:"))
            .count(),
        1
    );
}

/// A matcher alias only carries writes back to its namespace when it really aliases a matcher.
///
/// `const { not = fallback } = testApi` binds the matcher container, so replacing a matcher
/// through it mutates what `testApi.expect` reaches. A defaulted binding for an unrelated property
/// reaches nothing the assertion factory uses, so writing through it must leave trust intact.
#[test]
fn defaulted_destructured_matcher_aliases_propagate_writes_but_unrelated_ones_do_not() {
    let matcher_event = |alias: &str| {
        let definitions = extract_ts(&format!(
            r#"
import * as testApi from '@playwright/test';
const {{ {alias} = fallback }} = testApi;
{alias}.objectContaining = custom;
Then('namespaced matcher', ({{ state }}) =>
  testApi.expect(state).toEqual(testApi.expect.objectContaining({{ ready: true }})));
"#
        ));
        assert_eq!(definitions.len(), 1, "{alias}");
        definitions[0].handler.behavior_signature[0].clone()
    };

    let unrelated = matcher_event("unrelated");
    let aliased = matcher_event("not");
    assert!(
        unrelated.starts_with("assert:expect#toEqual:"),
        "{unrelated}"
    );
    assert_ne!(unrelated, aliased);
}

/// A rest copy only aliases the namespace when the copy itself is a binding.
///
/// `({ ...copy } = testApi)` names a local that holds the same matcher objects, so a deep write
/// through it reaches `testApi`. `({ ...holder.copy } = testApi)` writes into a property instead,
/// which names no binding this file can reason about, so trust must survive.
#[test]
fn rest_copies_alias_the_namespace_only_through_a_bound_identifier() {
    let matcher_event = |target: &str| {
        let definitions = extract_ts(&format!(
            r#"
import * as testApi from '@playwright/test';
({{ ...{target} }} = testApi);
{target}.not.objectContaining = custom;
Then('namespaced matcher', ({{ state }}) =>
  testApi.expect(state).toEqual(testApi.expect.objectContaining({{ ready: true }})));
"#
        ));
        assert_eq!(definitions.len(), 1, "{target}");
        definitions[0].handler.behavior_signature[0].clone()
    };

    let property_target = matcher_event("holder.copy");
    let binding_target = matcher_event("copy");
    assert!(
        property_target.starts_with("assert:expect#toEqual:"),
        "{property_target}"
    );
    assert_ne!(property_target, binding_target);
}

/// A facade module grants assertion trust to its named `expect`, never to a namespace binding.
///
/// Only the exact assertion packages are known to expose `expect` as a property of their module
/// object. A project fixture that re-exports registrations may export anything under that name, so
/// `import facade = require('~/fixtures/test')` must not make `facade.expect(...)` an assertion,
/// even though `import { expect } from '~/fixtures/test'` is trusted.
#[test]
fn facade_require_imports_bind_namespaces_without_assertion_trust() {
    let directory = tempfile::tempdir().unwrap();
    fs::create_dir_all(directory.path().join("fixtures")).unwrap();
    fs::create_dir_all(directory.path().join("steps")).unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("tsconfig.json"),
        r#"{"compilerOptions":{"paths":{"~/*":["./*"]}}}"#,
    )
    .unwrap();
    fs::write(
        directory.path().join("fixtures/test.ts"),
        r#"
import { createBdd } from 'playwright-bdd';
export const { Then } = createBdd({});
export const expect = createAssertionFactory();
"#,
    )
    .unwrap();
    let path = directory.path().join("steps/example.steps.ts");
    let source = r#"
import { Then } from '~/fixtures/test';
import { expect } from '~/fixtures/test';
import facade = require('~/fixtures/test');
Then('a named facade import is trusted', ({ state }) => expect(state).toBe('ready'));
Then('a facade require namespace is not', ({ state }) => facade.expect(state).toBe('ready'));
"#;
    fs::write(&path, source).unwrap();
    let file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);

    let extracted = extract_detailed_impl(source, &file, &mut session).unwrap();

    assert_eq!(extracted.definitions.len(), 2);
    assert!(
        extracted.definitions[0].handler.behavior_signature[0].starts_with("assert:expect#toBe:"),
        "{:?}",
        extracted.definitions[0].handler.behavior_signature
    );
    assert!(
        extracted.definitions[1]
            .handler
            .behavior_signature
            .iter()
            .all(|event| !event.starts_with("assert:")),
        "{:?}",
        extracted.definitions[1].handler.behavior_signature
    );
}

/// Aliasing a parameter is a rename, not a resolved constant.
///
/// A parameter's value is only known at call time, so an alias of one carries no fingerprint to
/// substitute. The alias still has to alpha-normalize like any other local, so two handlers that
/// alias the same parameter under different names stay equal while aliasing a different parameter
/// does not.
#[test]
fn constant_aliases_of_parameters_normalize_without_resolving_a_value() {
    let definitions = extract(
        r#"
Given('first', (page, other) => { const alias = page; alias.goto('/'); });
Given('second', (tab, extra) => { const copy = tab; copy.goto('/'); });
Given('third', (page, other) => { const alias = other; alias.goto('/'); });
"#,
        &file(SourceLanguage::JavaScript),
    )
    .unwrap();
    assert_eq!(definitions.len(), 3);
    assert_eq!(
        definitions[0].handler.alpha_normalized,
        definitions[1].handler.alpha_normalized
    );
    assert_ne!(
        definitions[0].handler.alpha_normalized,
        definitions[2].handler.alpha_normalized
    );
}

/// A string literal cannot forge sibling AST structure into an equal fingerprint.
///
/// `serialize_ast` frames nodes with `(`, `)`, spaces and `:` and embeds string content raw, so in
/// the abstract the flat serialization is ambiguous. It is safe in practice only because the quote
/// and backslash a forgery would need to reproduce a string wrapper are tokenized as
/// `escape_sequence` nodes rather than fragment text — so a string built to look like two arguments
/// stays distinct from two real arguments. This pins that separation; a tokenizer change that
/// stopped splitting on escapes would collapse the two and this test would fail.
#[test]
fn a_string_literal_does_not_forge_sibling_structure_into_an_equal_fingerprint() {
    let two_args = extract_ts(r#"Given('two args', () => { g("m", "n"); });"#);
    let forged_single = extract_ts(
        r#"Given('forged', () => { g("m \":\") ,:, (string \":\" string_fragment:n"); });"#,
    );
    assert_eq!(two_args.len(), 1);
    assert_eq!(forged_single.len(), 1);
    assert_ne!(
        two_args[0].handler.alpha_normalized,
        forged_single[0].handler.alpha_normalized,
    );
}

/// Assertion-event components escape their delimiters, so a computed key cannot forge a chain.
///
/// A behaviour event frames the assertion chain with `#` and `:`. `encode_event_component` escapes
/// those inside each name, so a computed member whose key *contains* a delimiter cannot be read as
/// the structure that delimiter denotes. `['not.toBe']` is one method named `not.toBe`, distinct
/// from `.not.toBe` (a `not` modifier on method `toBe`); a plain computed key equal to a dotted one
/// stays identical. The escaping path had no coverage before this test.
#[test]
fn assertion_event_components_escape_delimiters_so_computed_keys_do_not_forge_chains() {
    let dotted = extract_ts("Then('h', ({ state }) => expect(state).not.toBe('x'));");
    let computed_same = extract_ts("Then('h', ({ state }) => expect(state)['not'].toBe('x'));");
    let computed_delimited =
        extract_ts("Then('h', ({ state }) => expect(state)['not.toBe']('x'));");
    assert_eq!(
        dotted[0].handler.behavior_signature,
        computed_same[0].handler.behavior_signature,
    );
    assert_ne!(
        dotted[0].handler.behavior_signature,
        computed_delimited[0].handler.behavior_signature,
    );
    assert!(computed_delimited[0].handler.behavior_signature[0].contains("not\\.toBe"));
}

/// Extracts `source` as `steps.ts` in a project holding `files`.
fn extract_in_project(files: &[(&str, &str)], source: &str) -> Extraction {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    for (name, contents) in files {
        fs::write(directory.path().join(name), contents).unwrap();
    }
    let path = directory.path().join("steps.ts");
    fs::write(&path, source).unwrap();
    let source_file = SourceFile {
        path,
        language: SourceLanguage::TypeScript,
    };
    let mut session = TypeScriptExtractionSession::for_root(directory.path(), &[], &[]);
    extract_detailed_impl(source, &source_file, &mut session).unwrap()
}

/// A default import and TypeScript's `import x = require()` across module kinds. Import-equals binds
/// `module.exports`, so it registers for a package and a project module alike. A default import never
/// does: no supported package has a default export (each sets `__esModule`), and a project module's
/// `export default` is not modeled. A member call on it must warn rather than register or vanish.
/// Each registering row has a control with the same call and module that must not register.
#[test]
fn default_and_import_equals_bindings_register_only_where_they_bind_the_module() {
    let modules = [
        ("barrel.ts", "export { Given } from '@cucumber/cucumber';\n"),
        (
            "cjs.js",
            "const { Given } = require('@cucumber/cucumber');\nmodule.exports = { Given };\n",
        ),
    ];
    let call = "c.Given('a step', () => work());\n";
    // The expected warning: none, the generic unresolved-registration one, or one naming the module.
    let generic = "look like step registrations";
    for (import, registered, warning) in [
        ("import c from '@cucumber/cucumber';\n", 0, Some(generic)),
        ("import c = require('@cucumber/cucumber');\n", 1, None),
        ("import c = require('./cjs');\n", 1, None),
        ("import c from './barrel';\n", 0, Some(generic)),
        (
            "import c from './missing';\n",
            0,
            Some("module `./missing`"),
        ),
        (
            "import c = require('./missing');\n",
            0,
            Some("module `./missing`"),
        ),
    ] {
        let extracted = extract_in_project(&modules, &format!("{import}{call}"));
        assert_eq!(extracted.definitions.len(), registered, "{import}");
        let messages: Vec<_> = extracted
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.message.as_str())
            .collect();
        match warning {
            None => assert!(messages.is_empty(), "{import}: {messages:?}"),
            Some(expected) => assert!(
                messages.iter().any(|message| message.contains(expected)),
                "{import}: {messages:?}"
            ),
        }
    }
}

/// Every runtime import form binds its local name, so an imported `Given` is never the ambient
/// global. A type-only import is erased, so the ambient global still applies: that control proves
/// the call itself would register.
#[test]
fn every_runtime_import_form_shadows_the_ambient_registration_global() {
    let modules = [(
        "cjs.js",
        "module.exports = { Given: (text, fn) => text };\n",
    )];
    let call = "Given('a step', () => work());\n";
    for import in [
        "import Given from './cjs';\n",
        "import * as Given from './cjs';\n",
        "import Given = require('./cjs');\n",
        "import { Given } from './cjs';\n",
    ] {
        let extracted = extract_in_project(&modules, &format!("{import}{call}"));
        assert!(extracted.definitions.is_empty(), "{import}");
    }
    for control in ["", "import type Given from './cjs';\n"] {
        let extracted = extract_in_project(&modules, &format!("{control}{call}"));
        assert_eq!(extracted.definitions.len(), 1, "control: {control:?}");
    }
}

/// A registration handed to another function can be called there, in a body the analyzer does not
/// follow, so the call is reported and the corpus marked incomplete. The controls use the same
/// shape without a registration: no registration argument, a local value that merely shares the
/// name (a fixture parameter or block declaration), or the registration call itself.
#[test]
fn passing_a_registration_to_a_function_is_reported() {
    let modules = [(
        "helper.js",
        "module.exports = (register, text, fn) => register(text, fn);\n",
    )];
    let passed = "pass a step registration to a function";
    for (source, reported) in [
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(Given, 'a step', () => work());\n",
            true,
        ),
        (
            "import * as cucumber from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(cucumber.Given, 'a step', () => work());\n",
            true,
        ),
        (
            "import cucumber = require('@cucumber/cucumber');\nimport helper from './helper';\nhelper((cucumber.Given), 'a step', () => work());\n",
            true,
        ),
        // The ambient global counts when nothing binds the name locally.
        (
            "import helper from './helper';\nhelper(Given, 'a step', () => work());\n",
            true,
        ),
        (
            "import helper from './helper';\nhelper('a step', () => work());\n",
            false,
        ),
        // A registration nested in an argument value is passed as surely as a direct one.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper({ register: Given }, 'a step', () => work());\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper({ Given }, 'a step', () => work());\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper([Given], 'a step', () => work());\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(() => Given, 'a step', () => work());\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(new Wrapper(Given));\n",
            true,
        ),
        // Value-preserving positions carry the registration itself.
        (
            "import { Given, When } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(flag ? Given : When);\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(Given || fallback);\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(function () { if (ready) { return Given; } });\n",
            true,
        ),
        // A return is found through any control flow, and a yield counts as a return.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(() => { try { return Given; } finally { done(); } });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(function () { switch (kind) { case 'given': return Given; default: return null; } });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(() => { for (const item of items) { if (item) { return Given; } } });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(function* () { yield Given; });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper({ register() { return Given; } });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper({ get register() { return Given; } });\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper((setup(), Given));\n",
            true,
        ),
        // Spreading a literal carries its elements; spreading a registration copies its properties.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(...[Given]);\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper({ ...Given }, [...Given]);\n",
            false,
        ),
        // A compound assignment yields the combined value, not the registration.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nlet value = '';\nhelper(value += Given);\n",
            false,
        ),
        // A comma expression is its last operand only.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper((Given, 42));\n",
            false,
        ),
        // A nested function's return is its own, not the outer function's.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(() => { function inner() { return Given; } return 1; });\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(register = Given);\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(Given.bind(null), 'a step', () => work());\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(Given.toString());\n",
            false,
        ),
        // Consuming positions yield a new value, not the registration.
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(Given.name, typeof Given, Given !== undefined);\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(new Given(), Given ? 1 : 2);\n",
            false,
        ),
        // Controls: a nested object without a registration, and a registration that is called
        // inside a callback (extracted as a definition, not passed).
        (
            "import helper from './helper';\nhelper({ register: other, list: [1] }, 'a step', () => work());\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nimport helper from './helper';\nhelper(() => Given('a step', () => work()));\n",
            false,
        ),
        // A fixture parameter or local declaration that shares the name is a local value. Each
        // imports the real registration too, so only the local binding keeps the call quiet.
        (
            "import { Given } from '@cucumber/cucumber';\nexport const fixtures = { When: [({ Given }, use) => use(Given)] };\n",
            false,
        ),
        (
            "import * as cucumber from '@cucumber/cucumber';\nexport const fixtures = { When: [(cucumber, use) => use(cucumber.Given)] };\n",
            false,
        ),
        (
            "import * as cucumber from '@cucumber/cucumber';\nexport const fixtures = { When: [(cucumber, use) => use((cucumber.Given))] };\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nexport function setup(use) {\n  const Given = make();\n  use(Given);\n}\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nexport function setup(use) {\n  function Given() {}\n  use(Given);\n}\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nexport function setup(use) {\n  class Given {}\n  use(Given);\n}\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\ntry { run(); } catch (Given) { use(Given); }\n",
            false,
        ),
        // A loop declaration binds for its body; a bare loop target assigns the outer name.
        (
            "import { Given } from '@cucumber/cucumber';\nfor (const Given of values) { use(Given); }\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nfor (let Given = first(); Given; Given = next()) { use(Given); }\n",
            false,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nfor (Given of values) { use(Given); }\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nfor (const item of values) { use({ Given }); }\n",
            true,
        ),
        (
            "import { Given } from '@cucumber/cucumber';\nGiven('a step', () => work());\n",
            false,
        ),
    ] {
        let extracted = extract_in_project(&modules, source);
        let messages: Vec<_> = extracted
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.message.as_str())
            .collect();
        assert_eq!(
            messages.iter().any(|message| message.contains(passed)),
            reported,
            "{source}: {messages:?}"
        );
    }
}