File size: 424,534 Bytes
1e2511f | 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 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 | #!/usr/bin/env node
// ======================================================================
// Universal Comment Fixer 3.0.1-beta/เครื่องมือแก้ไขคอมเมนต์สากล v3.0.1-beta
// ======================================================================
// @author(Chahua Development Co., Ltd.)
// @version v3.0.1-beta
// @description Professional comment standardization tool with AI-friendly format
// @security_features Path Traversal Protection, File Size Limits, Symlink Protection
// SECURITY FEATURES:
// ┌─────────────────────────────────────────────────────────────────┐
// │ • Path Traversal Protection: Prevents ../../../etc/passwd attacks │
// │ • File Size Limits: 10MB maximum to prevent DoS attacks │
// │ • Symbolic Link Protection: Prevents infinite loop attacks │
// │ • System Directory Blacklist: Blocks access to sensitive paths │
// │ • Backup Path Validation: Secure backup creation with sanitization │
// │ • Working Directory Enforcement: All operations within project │
// └─────────────────────────────────────────────────────────────────┘
const fs = require('fs');
const path = require('path');
// ======================================================================
// Professional Logging System/ระบบบันทึกมืออาชีพ
// ======================================================================
class ProfessionalLogger {
constructor() {
this.projectName = path.basename(process.cwd());
this.logsDir = path.join(process.cwd(), 'logs');
// สร้างโฟลเดอร์ logs หลักถ้ายังไม่มี
if (!fs.existsSync(this.logsDir)) {
fs.mkdirSync(this.logsDir, { recursive: true });
}
// สร้างโฟลเดอร์ย่อยสำหรับโปรเจกต์นี้
this.projectLogsDir = path.join(this.logsDir, this.projectName);
if (!fs.existsSync(this.projectLogsDir)) {
fs.mkdirSync(this.projectLogsDir, { recursive: true });
}
// สร้างโฟลเดอร์ session ตามวันเวลา
const now = new Date();
const dateFolder = now.toISOString().slice(0, 10); // 2025-09-24
const timeFolder = now.toTimeString().slice(0, 8).replace(/:/g, '-'); // 03-53-12
this.sessionFolder = `${dateFolder}_${timeFolder}`;
this.sessionLogsDir = path.join(this.projectLogsDir, this.sessionFolder);
if (!fs.existsSync(this.sessionLogsDir)) {
fs.mkdirSync(this.sessionLogsDir, { recursive: true });
}
this.logFiles = {
error: path.join(this.sessionLogsDir, 'error.log'),
debug: path.join(this.sessionLogsDir, 'debug.log'),
audit: path.join(this.sessionLogsDir, 'audit.log'),
performance: path.join(this.sessionLogsDir, 'performance.log'),
diagnostic: path.join(this.sessionLogsDir, 'diagnostic.log')
};
// เขียน session header
this.writeSessionHeader();
}
writeSessionHeader() {
const timestamp = new Date().toISOString();
const header = `\n${'='.repeat(80)}\nSESSION START: ${timestamp} | Project: ${this.projectName}\n${'='.repeat(80)}\n`;
Object.values(this.logFiles).forEach(logFile => {
fs.appendFileSync(logFile, header, 'utf8');
});
}
formatLogEntry(level, category, message, data = null) {
const timestamp = new Date().toISOString();
let entry = `[${timestamp}] [${level.toUpperCase()}] [${category}] ${message}`;
if (data) {
entry += `\n Data: ${JSON.stringify(data, null, 2)}`;
}
entry += '\n';
return entry;
}
error(category, message, error = null, data = null) {
const logData = { ...data };
if (error) {
logData.error = {
message: error.message,
stack: error.stack,
name: error.name
};
}
const entry = this.formatLogEntry('ERROR', category, message, logData);
fs.appendFileSync(this.logFiles.error, entry, 'utf8');
// แสดงใน console ด้วย
console.error(`[ERROR] ${category}: ${message}`);
}
debug(category, message, data = null) {
const entry = this.formatLogEntry('DEBUG', category, message, data);
fs.appendFileSync(this.logFiles.debug, entry, 'utf8');
}
audit(action, filePath, details = null) {
const entry = this.formatLogEntry('AUDIT', 'FILE_OPERATION',
`${action}: ${filePath}`, details);
fs.appendFileSync(this.logFiles.audit, entry, 'utf8');
}
performance(operation, duration, details = null) {
const entry = this.formatLogEntry('PERFORMANCE', operation,
`Duration: ${duration}ms`, details);
fs.appendFileSync(this.logFiles.performance, entry, 'utf8');
}
info(category, message, data = null) {
const entry = this.formatLogEntry('INFO', category, message, data);
fs.appendFileSync(this.logFiles.debug, entry, 'utf8');
}
// สร้าง diagnostic report แยกต่างหาก
diagnostic(category, message, data = null) {
const entry = this.formatLogEntry('DIAGNOSTIC', category, message, data);
// เขียนลงทั้ง audit และ debug ในโฟลเดอร์ session
fs.appendFileSync(this.logFiles.audit, entry, 'utf8');
fs.appendFileSync(this.logFiles.debug, `\n=== DIAGNOSTIC REPORT ===\n${entry}=== END DIAGNOSTIC ===\n`, 'utf8');
// เขียนลงไฟล์ diagnostic ใน session folder
if (!fs.existsSync(this.logFiles.diagnostic)) {
const header = `DIAGNOSTIC REPORTS LOG - ${new Date().toISOString()}\nProject: ${this.projectName} | Session: ${this.sessionFolder}\n${'='.repeat(80)}\n\n`;
fs.writeFileSync(this.logFiles.diagnostic, header, 'utf8');
}
fs.appendFileSync(this.logFiles.diagnostic, entry, 'utf8');
}
}
// สร้าง logger instance
const logger = new ProfessionalLogger();
// ======================================================================
// Organized Backup System/ระบบสำรองข้อมูลที่เป็นระบบ
// ======================================================================
class OrganizedBackupManager {
constructor() {
this.projectName = path.basename(process.cwd());
this.backupsDir = path.join(process.cwd(), '.backups');
this.projectBackupDir = path.join(this.backupsDir, this.projectName);
// สร้างโฟลเดอร์ backup ถ้ายังไม่มี
this.ensureBackupDirectories();
}
// ======================================================================
// EN: Ensure condition class
// TH: คลาสประกันเงื่อนไข
// ======================================================================
ensureBackupDirectories() {
if (!fs.existsSync(this.backupsDir)) {
fs.mkdirSync(this.backupsDir, { recursive: true });
logger.audit('CREATE_BACKUP_DIR', this.backupsDir);
}
if (!fs.existsSync(this.projectBackupDir)) {
fs.mkdirSync(this.projectBackupDir, { recursive: true });
logger.audit('CREATE_PROJECT_BACKUP_DIR', this.projectBackupDir);
}
}
createBackup(originalFilePath) {
try {
// ตรวจสอบว่าไฟล์ต้นฉบับมีอยู่จริง
if (!fs.existsSync(originalFilePath)) {
throw new Error(`Original file does not exist: ${originalFilePath}`);
}
// สร้างโฟลเดอร์ตามวันที่-เวลา
const now = new Date();
const dateFolder = now.toISOString().slice(0, 10); // 2025-09-24
const timeFolder = now.toTimeString().slice(0, 8).replace(/:/g, '-'); // 03-40-40
const sessionFolder = `${dateFolder}_${timeFolder}`;
// สร้างโฟลเดอร์ backup session
const sessionBackupDir = path.join(this.projectBackupDir, sessionFolder);
if (!fs.existsSync(sessionBackupDir)) {
fs.mkdirSync(sessionBackupDir, { recursive: true });
logger.audit('CREATE_SESSION_BACKUP_DIR', sessionBackupDir);
}
// ใช้ชื่อไฟล์ต้นฉบับธรรมดา
const originalFileName = path.basename(originalFilePath);
const backupFilePath = path.join(sessionBackupDir, originalFileName);
// คัดลอกไฟล์ต้นฉบับไป backup (เก็บไฟล์ต้นฉบับ)
const originalContent = fs.readFileSync(originalFilePath, 'utf8');
fs.writeFileSync(backupFilePath, originalContent, 'utf8');
// บันทึก audit log
logger.audit('BACKUP_CREATED', originalFilePath, {
backupPath: backupFilePath,
sessionFolder: sessionFolder,
originalSize: originalContent.length,
originalFileName: originalFileName
});
logger.info('BACKUP', `Original file backed up to: ${sessionFolder}/${originalFileName}`);
return backupFilePath;
} catch (error) {
logger.error('BACKUP', `Failed to create backup for ${originalFilePath}`, error);
throw error;
}
}
cleanupOldBackups(maxAge = 7) {
try {
const sessionFolders = fs.readdirSync(this.projectBackupDir);
const cutoffTime = Date.now() - (maxAge * 24 * 60 * 60 * 1000);
let cleanedCount = 0;
sessionFolders.forEach(sessionFolder => {
const sessionPath = path.join(this.projectBackupDir, sessionFolder);
const stats = fs.statSync(sessionPath);
// ถ้าเป็นโฟลเดอร์และเก่าเกินกำหนด
if (stats.isDirectory() && stats.mtime.getTime() < cutoffTime) {
// ลบทั้งโฟลเดอร์
fs.rmSync(sessionPath, { recursive: true, force: true });
cleanedCount++;
logger.audit('BACKUP_SESSION_CLEANED', sessionPath, {
sessionFolder: sessionFolder,
age: maxAge
});
}
});
if (cleanedCount > 0) {
logger.info('BACKUP', `Cleaned up ${cleanedCount} old backup sessions`);
}
} catch (error) {
logger.error('BACKUP', 'Failed to cleanup old backups', error);
}
}
}
// ======================================================================
// File Comparison & Analysis System - ระบบเปรียบเทียบและวิเคราะห์ไฟล์
// ======================================================================
class FileComparisonAnalyzer {
constructor() {
this.comparisonResults = [];
}
// เปรียบเทียบไฟล์ก่อนและหลัง แล้วสร้าง detailed report
// ======================================================================
// EN: compareAndAnalyze class
// TH: คลาส compareAndAnalyze
// ======================================================================
compareAndAnalyze(originalContent, modifiedContent, filePath) {
try {
const comparisonId = Date.now();
logger.debug('FILE_COMPARISON', `Starting comparison analysis for: ${filePath}`, { comparisonId });
// วิเคราะห์ไฟล์ก่อน (Original)
const originalAnalysis = this.analyzeFileStructures(originalContent, 'ORIGINAL');
logger.debug('FILE_ANALYSIS', `Original file analysis completed`, {
filePath,
structures: originalAnalysis.summary
});
// วิเคราะห์ไฟล์หลัง (Modified)
const modifiedAnalysis = this.analyzeFileStructures(modifiedContent, 'MODIFIED');
logger.debug('FILE_ANALYSIS', `Modified file analysis completed`, {
filePath,
structures: modifiedAnalysis.summary
});
// เปรียบเทียบและสร้าง report
const comparisonReport = this.generateComparisonReport(
originalAnalysis,
modifiedAnalysis,
filePath
);
// บันทึก detailed report ลง audit log
this.logDetailedReport(comparisonReport, filePath);
// บันทึก error และ skip report
this.logErrorAndSkipReport(comparisonReport, filePath);
this.comparisonResults.push(comparisonReport);
return comparisonReport;
} catch (error) {
logger.error('FILE_COMPARISON', `Failed to compare files: ${filePath}`, error);
return null;
}
}
// วิเคราะห์โครงสร้างไฟล์โดยใช้ระบบที่มีอยู่
analyzeFileStructures(content, type) {
try {
// ใช้ SmartFileAnalyzer ที่มีอยู่แล้ว
const analyzer = new SmartFileAnalyzer(content, {
maxDepth: 50,
maxTokens: 100000,
maxParsingTime: 15000
});
const analysis = analyzer.analyzeFile();
// นับจำนวน structures แต่ละประเภท
const summary = {
totalFunctions: analysis.functions ? analysis.functions.length : 0,
totalClasses: analysis.classes ? analysis.classes.length : 0,
totalMethods: analysis.methods ? analysis.methods.length : 0,
totalVariables: analysis.variables ? analysis.variables.length : 0,
totalInterfaces: 0,
totalTypeAliases: 0,
totalAbstractClasses: 0,
totalStaticMethods: 0,
totalArrowFunctions: 0
};
// นับ TypeScript structures
if (analysis.interfaces) summary.totalInterfaces = analysis.interfaces.length;
if (analysis.typeAliases) summary.totalTypeAliases = analysis.typeAliases.length;
if (analysis.abstractClasses) summary.totalAbstractClasses = analysis.abstractClasses.length;
if (analysis.staticMethods) summary.totalStaticMethods = analysis.staticMethods.length;
if (analysis.arrowFunctions) summary.totalArrowFunctions = analysis.arrowFunctions.length;
// ตรวจสอบ functions ที่ไม่มี comment
const functionsWithoutComments = this.findFunctionsWithoutComments(content, analysis.functions || []);
const classesWithoutComments = this.findClassesWithoutComments(content, analysis.classes || []);
return {
type,
analysis,
summary,
functionsWithoutComments,
classesWithoutComments,
totalStructures: Object.values(summary).reduce((a, b) => a + b, 0)
};
} catch (error) {
logger.error('STRUCTURE_ANALYSIS', `Failed to analyze ${type} content`, error);
return { type, error: error.message, summary: {}, totalStructures: 0 };
}
}
// หา functions ที่ไม่มี comment (ใช้ StateMachineStructureParser พร้อม JavaScriptTokenizer)
findFunctionsWithoutComments(content, filePath = '') {
const without = [];
const lines = normalizeLineEndings(content).split('\n');
const detectedSet = new Set();
try {
// ใช้ tokenizer เพื่อสร้าง token stream
const tokenizer = new JavaScriptTokenizer(content);
const tokens = tokenizer.tokenize();
// ใช้ state machine parser เพื่อวิเคราะห์โครงสร้าง
const parser = new StateMachineStructureParser(tokens, content);
const structures = parser.parse();
// รวมสิ่งที่ตรวจจับได้ทั้งหมด
const allItems = [
...structures.functions,
...structures.arrowFunctions,
...structures.methods,
...structures.classes,
...structures.reactComponents,
...structures.interfaces,
...structures.typeAliases,
...structures.enums
];
// ตรวจสอบคอมเมนต์ด้านบน
allItems.forEach(item => {
const key = `${item.name}@${item.line}`;
detectedSet.add(key);
if (this.hasCommentAbove(lines, item.line - 1)) return;
without.push(item);
});
} catch (e) {
// ถ้า parser ใหม่มีปัญหา ใช้ regex fallback โดยตรง
console.warn('StateMachineStructureParser error, using fallback mode:', e.message);
// ค้นหาฟังก์ชั่น (ไม่ใช้ async เพื่อจับหมด)
const funcRegex = /^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)/gm;
let match;
while ((match = funcRegex.exec(content)) !== null) {
const name = match[1];
const lineNum = content.substring(0, match.index).split('\n').length;
const key = `${name}@${lineNum}`;
if (detectedSet.has(key)) continue;
if (this.hasCommentAbove(lines, lineNum - 1)) continue;
without.push({ type: 'function', name, line: lineNum });
detectedSet.add(key);
}
// ค้นหา arrow functions
const arrowRegex = /^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>/gm;
while ((match = arrowRegex.exec(content)) !== null) {
const name = match[1];
const lineNum = content.substring(0, match.index).split('\n').length;
const key = `${name}@${lineNum}`;
if (detectedSet.has(key)) continue;
if (this.hasCommentAbove(lines, lineNum - 1)) continue;
without.push({ type: 'arrow_function', name, line: lineNum });
detectedSet.add(key);
}
}
return without;
}
// Helper: ตรวจสอบว่ามีคอมเมนต์อยู่ด้านบนของบรรทัดหรือไม่
hasCommentAbove(lines, lineIndex) {
for (let i = 1; i <= 7; i++) {
if (lineIndex - i < 0) break;
const prev = (lines[lineIndex - i] || '').trim();
if (prev.startsWith('//') || prev.startsWith('/**') || prev.startsWith('/*') || prev.startsWith('*')) {
return true;
}
if (prev && !prev.startsWith('//') && !prev.startsWith('/*')) break;
}
return false;
}
// หา classes ที่ไม่มี comment (พร้อม Smart Detection)
findClassesWithoutComments(content, classes) {
const withoutComments = [];
const lines = content.split('\n');
classes.forEach(cls => {
const classLine = cls.line - 1; // 0-based index
// Smart Class Detection - กรองตัวแปรออก
if (this.isLikelyVariable(cls.name, content, classLine)) {
return; // ข้ามตัวแปรที่ถูก misidentify
}
// กรอง React Components ที่เป็น const assignments ออก
if (this.isReactComponent(cls.name, content, classLine)) {
return; // ข้าม React Components ที่ควรเป็น functions
}
let hasComment = false; // ตรวจสอบ 3 บรรทัดก่อนหน้า
for (let i = 1; i <= 3; i++) {
const checkLine = classLine - i;
if (checkLine >= 0 && lines[checkLine]) {
const line = lines[checkLine].trim();
if (line.startsWith('//') || line.startsWith('/*') || line.startsWith('*')) {
hasComment = true;
break;
}
}
}
if (!hasComment) {
withoutComments.push({
name: cls.name,
line: cls.line,
type: cls.type || 'class'
});
}
});
return withoutComments;
}
// Smart Detection - ตรวจสอบว่าชื่อนั้นเป็นตัวแปรหรือไม่
isLikelyVariable(name, content, lineIndex) {
const lines = content.split('\n');
if (lineIndex < 0 || lineIndex >= lines.length) return false;
const currentLine = lines[lineIndex].trim();
const lowerName = name.toLowerCase();
// Escape ตัวอักษรพิเศษใน name ก่อนใช้ใน RegExp
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// ตรวจสอบ patterns ที่เป็นตัวแปร
const variablePatterns = [
// Variable declarations
new RegExp(`\\b(const|let|var)\\s+${escapedName}\\s*=`),
new RegExp(`\\b${escapedName}\\s*=\\s*`),
// Function parameters
new RegExp(`function\\s*\\([^)]*\\b${escapedName}\\b[^)]*\\)`),
new RegExp(`\\([^)]*\\b${escapedName}\\b[^)]*\\)\\s*=>`),
// Destructuring
new RegExp(`{[^}]*\\b${escapedName}\\b[^}]*}`),
new RegExp(`\\[[^\\]]*\\b${escapedName}\\b[^\\]]*\\]`),
// Loop variables
new RegExp(`for\\s*\\([^;]*\\b${escapedName}\\b`),
// React Context patterns
new RegExp(`\\b${escapedName}\\s*=\\s*createContext`),
new RegExp(`\\bconst\\s+${escapedName}\\s*=\\s*createContext`),
// React Hook patterns
new RegExp(`\\b${escapedName}\\s*=\\s*use[A-Z]`),
new RegExp(`\\bconst\\s+\\[.*${escapedName}.*\\]\\s*=\\s*useState`),
// Arrow function assignments
new RegExp(`\\bconst\\s+${escapedName}\\s*=\\s*\\(`),
new RegExp(`\\bconst\\s+${escapedName}\\s*=\\s*\\w+\\s*=>`),
];
// ตรวจสอบบรรทัดปัจจุบันและใกล้เคียง (เพิ่มช่วงการตรวจสอบ)
for (let i = Math.max(0, lineIndex - 3); i <= Math.min(lines.length - 1, lineIndex + 3); i++) {
const line = lines[i];
if (variablePatterns.some(pattern => pattern.test(line))) {
return true;
}
}
// ตรวจสอบ common variable names
const commonVariableNames = [
'result', 'data', 'item', 'value', 'temp', 'node', 'element',
'current', 'next', 'prev', 'parent', 'child', 'left', 'right',
'count', 'index', 'length', 'size', 'max', 'min', 'sum',
'start', 'end', 'pos', 'queue', 'stack', 'list', 'array',
'map', 'set', 'key', 'val', 'obj', 'target', 'source',
'input', 'output', 'buffer', 'cache', 'config', 'options',
// Algorithm-specific variables
'dp', 'memo', 'visited', 'distances', 'graph', 'matrix',
'heap', 'buckets', 'intervals', 'points', 'edges', 'vertices',
// React-specific variable names
'user', 'users', 'state', 'props', 'context', 'ref', 'refs',
'handler', 'handlers', 'callback', 'callbacks', 'event', 'events',
'timeout', 'interval', 'timer', 'loading', 'error', 'success'
];
if (commonVariableNames.includes(lowerName)) {
return true;
}
// ตรวจสอบ React Context patterns (ขึ้นต้นด้วยตัวพิมพ์ใหญ่ แต่ลงท้ายด้วย Context)
if (name.endsWith('Context') && /^[A-Z][a-zA-Z]*Context$/.test(name)) {
return true;
}
// ตรวจสอบ React Component patterns ที่เป็น const assignment
if (/^[A-Z][a-zA-Z0-9]*$/.test(name)) {
// ตรวจสอบว่าเป็น const component assignment หรือไม่
const componentPattern = new RegExp(`const\\s+${name}\\s*=`);
for (let i = Math.max(0, lineIndex - 2); i <= Math.min(lines.length - 1, lineIndex + 2); i++) {
if (componentPattern.test(lines[i])) {
return true;
}
}
}
// ตรวจสอบ short variable names (มักเป็น loop counters)
if (name.length <= 2 && /^[a-zA-Z][0-9]?$/.test(name)) {
return true;
}
// ตรวจสอบ camelCase variables (ขึ้นต้นด้วยตัวพิมพ์เล็ก)
if (/^[a-z][a-zA-Z0-9]*$/.test(name)) {
return true;
}
return false;
}
// ตรวจสอบว่าเป็น React Component หรือไม่
isReactComponent(name, content, lineIndex) {
const lines = content.split('\n');
if (lineIndex < 0 || lineIndex >= lines.length) return false;
// React Component ต้องขึ้นต้นด้วยตัวพิมพ์ใหญ่
if (!/^[A-Z][a-zA-Z0-9]*$/.test(name)) return false;
// ตรวจสอบ patterns ของ React Components
const reactComponentPatterns = [
// const Component = () => {}
new RegExp(`const\\s+${name}\\s*=\\s*\\([^)]*\\)\\s*=>`),
// const Component = function() {}
new RegExp(`const\\s+${name}\\s*=\\s*function`),
// const Component = React.memo()
new RegExp(`const\\s+${name}\\s*=\\s*React\\.memo`),
// const Component = forwardRef()
new RegExp(`const\\s+${name}\\s*=\\s*forwardRef`),
// export const Component =
new RegExp(`export\\s+const\\s+${name}\\s*=`),
];
// ตรวจสอบบรรทัดใกล้เคียง
for (let i = Math.max(0, lineIndex - 2); i <= Math.min(lines.length - 1, lineIndex + 2); i++) {
const line = lines[i];
if (reactComponentPatterns.some(pattern => pattern.test(line))) {
return true;
}
}
// ตรวจสอบ JSX return patterns
const jsxPatterns = [
/return\s*\(/,
/return\s*</,
/>\s*$/,
/<\/[a-zA-Z]/
];
// ตรวจสอบใน function body ว่ามี JSX หรือไม่
for (let i = lineIndex; i < Math.min(lines.length, lineIndex + 20); i++) {
const line = lines[i].trim();
if (jsxPatterns.some(pattern => pattern.test(line))) {
return true;
}
// หยุดตรวจสอบถ้าเจอปิด function
if (line.includes('}') && !line.includes('{')) {
break;
}
}
return false;
}
// สร้าง comparison report
generateComparisonReport(originalAnalysis, modifiedAnalysis, filePath) {
const report = {
filePath,
timestamp: new Date().toISOString(),
original: originalAnalysis,
modified: modifiedAnalysis,
changes: {
functionsAdded: modifiedAnalysis.summary.totalFunctions - originalAnalysis.summary.totalFunctions,
classesAdded: modifiedAnalysis.summary.totalClasses - originalAnalysis.summary.totalClasses,
commentsAdded: 0, // จะคำนวณจากการเปรียบเทียบ
structuresSkipped: (modifiedAnalysis.functionsWithoutComments?.length || 0) + (modifiedAnalysis.classesWithoutComments?.length || 0),
errors: []
},
skippedStructures: {
functions: modifiedAnalysis.functionsWithoutComments || [],
classes: modifiedAnalysis.classesWithoutComments || []
}
};
// คำนวณจำนวน comments ที่เพิ่ม
report.changes.commentsAdded = this.calculateCommentsAdded(originalAnalysis, modifiedAnalysis);
return report;
}
// คำนวณจำนวน comments ที่เพิ่มขึ้น
calculateCommentsAdded(original, modified) {
const originalCommentLines = this.countCommentLines(original.analysis?.content || '');
const modifiedCommentLines = this.countCommentLines(modified.analysis?.content || '');
return Math.max(0, modifiedCommentLines - originalCommentLines);
}
// นับจำนวนบรรทัดที่มี comment
countCommentLines(content) {
const lines = content.split('\n');
return lines.filter(line => {
const trimmed = line.trim();
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*');
}).length;
}
// บันทึก detailed report ลง audit log
logDetailedReport(report, filePath) {
logger.audit('FILE_COMPARISON_REPORT', filePath, {
summary: {
totalStructuresOriginal: report.original.totalStructures,
totalStructuresModified: report.modified.totalStructures,
functionsAdded: report.changes.functionsAdded,
classesAdded: report.changes.classesAdded,
commentsAdded: report.changes.commentsAdded,
structuresSkipped: report.changes.structuresSkipped
},
originalStructures: report.original.summary,
modifiedStructures: report.modified.summary
});
}
// บันทึก error และ skip report แยกต่างหาก พร้อมวิเคราะห์ละเอียดและแนะนำวิธีแก้ไข
logErrorAndSkipReport(report, filePath) {
if (report.changes.structuresSkipped > 0) {
// วิเคราะห์รูปแบบที่ skip
const analysisResult = this.analyzeSkippedPatterns(report, filePath);
logger.error('STRUCTURES_SKIPPED',
`${report.changes.structuresSkipped} structures were skipped in ${filePath}`,
null,
{
skippedFunctions: report.skippedStructures.functions.map(f => `${f.name} (line ${f.line})`),
skippedClasses: report.skippedStructures.classes.map(c => `${c.name} (line ${c.line})`),
totalSkipped: report.changes.structuresSkipped,
reasons: 'Functions/Classes without comments detected',
patternAnalysis: analysisResult.patterns,
suggestedSolutions: analysisResult.solutions,
codeExamples: analysisResult.examples
}
);
// สร้าง detailed diagnostic report
this.generateDetailedDiagnosticReport(report, filePath, analysisResult);
}
// สร้าง summary report
logger.performance('FILE_PROCESSING_SUMMARY', 0, {
filePath,
success: true,
totalStructures: report.modified.totalStructures,
commentsAdded: report.changes.commentsAdded,
functionsSkipped: report.skippedStructures.functions.length,
classesSkipped: report.skippedStructures.classes.length,
errorCount: report.changes.errors.length
});
}
// วิเคราะห์รูปแบบของ structures ที่ถูก skip
analyzeSkippedPatterns(report, filePath) {
const analysis = {
patterns: {
variableDeclarations: 0,
shortVariableNames: 0,
nestedStructures: 0,
generatedCode: 0,
utilityVariables: 0
},
solutions: [],
examples: []
};
// วิเคราะห์ functions ที่ skip
report.skippedStructures.functions.forEach(func => {
if (func.name.length <= 2) {
analysis.patterns.shortVariableNames++;
analysis.solutions.push(`Short variable name detected: "${func.name}" - Consider using descriptive names`);
}
if (['i', 'j', 'k', 'x', 'y', 'z', 'n', 'm'].includes(func.name)) {
analysis.patterns.utilityVariables++;
analysis.solutions.push(`Loop/utility variable detected: "${func.name}" - This is likely a loop counter or temporary variable`);
}
});
// วิเคราะห์ classes ที่ skip
report.skippedStructures.classes.forEach(cls => {
if (cls.name.length <= 2) {
analysis.patterns.shortVariableNames++;
analysis.solutions.push(`Short variable name detected: "${cls.name}" - This appears to be a variable, not a class`);
}
if (['temp', 'result', 'data', 'item', 'node', 'value'].includes(cls.name.toLowerCase())) {
analysis.patterns.variableDeclarations++;
analysis.solutions.push(`Variable declaration detected: "${cls.name}" - This is likely a variable assignment`);
}
if (cls.name.match(/^[a-z][a-zA-Z]*$/)) {
analysis.patterns.variableDeclarations++;
analysis.solutions.push(`Camel case variable detected: "${cls.name}" - This follows variable naming convention`);
}
});
// สร้าง code examples สำหรับการแก้ไข
if (analysis.patterns.variableDeclarations > 0) {
analysis.examples.push({
type: 'Variable Declaration Fix',
problem: 'const result = someFunction();',
solution: '// Calculate processing result\nconst result = someFunction();'
});
}
if (analysis.patterns.shortVariableNames > 0) {
analysis.examples.push({
type: 'Short Variable Name Fix',
problem: 'let i = 0;',
solution: '// Loop counter for iteration\nlet i = 0;'
});
}
return analysis;
}
// สร้าง detailed diagnostic report
generateDetailedDiagnosticReport(report, filePath, analysisResult) {
const diagnosticData = {
filePath: filePath,
timestamp: new Date().toISOString(),
issuesSummary: {
totalIssues: report.changes.structuresSkipped,
functionIssues: report.skippedStructures.functions.length,
classIssues: report.skippedStructures.classes.length,
mainCauses: this.identifyMainCauses(analysisResult.patterns, report)
},
detailedAnalysis: {
likelyVariableDeclarations: analysisResult.patterns.variableDeclarations,
shortVariableNames: analysisResult.patterns.shortVariableNames,
utilityVariables: analysisResult.patterns.utilityVariables,
suggestedFixes: analysisResult.solutions.length
},
actionableRecommendations: this.generateActionableRecommendations(report, analysisResult),
codeImprovementSuggestions: analysisResult.examples
};
logger.diagnostic('STRUCTURE_ANALYSIS',
`Detailed diagnostic for ${path.basename(filePath)}`,
diagnosticData);
}
// ระบุสาเหตุหลักของปัญหา
identifyMainCauses(patterns, report) {
const causes = [];
if (patterns.variableDeclarations > 0) {
causes.push('Variable declarations misidentified as classes');
}
if (patterns.shortVariableNames > 0) {
causes.push('Short variable names detected');
}
if (patterns.utilityVariables > 0) {
causes.push('Loop counters and utility variables present');
}
// เพิ่ม Advanced Pattern Analysis
const advancedPatterns = this.analyzeAdvancedPatterns(report.skippedStructures);
if (advancedPatterns.typeScriptPatterns > 0) {
causes.push('TypeScript advanced constructs (interfaces, types, generics)');
}
if (advancedPatterns.reactPatterns > 0) {
causes.push('React patterns (hooks, components, context)');
}
if (advancedPatterns.modernJsPatterns > 0) {
causes.push('Modern JavaScript patterns (destructuring, async/await)');
}
if (advancedPatterns.classMethodPatterns > 0) {
causes.push('Advanced class methods and decorators');
}
return causes.length > 0 ? causes : ['Unknown pattern - requires manual review'];
}
// วิเคราะห์ Advanced Patterns ที่ Parser ยังไม่รู้จัก
analyzeAdvancedPatterns(skippedStructures) {
const patterns = {
typeScriptPatterns: 0,
reactPatterns: 0,
modernJsPatterns: 0,
classMethodPatterns: 0,
algorithmPatterns: 0
};
const allStructures = [
...(skippedStructures.functions || []),
...(skippedStructures.classes || [])
];
allStructures.forEach(structure => {
const name = structure.name;
const lowerName = name.toLowerCase();
// TypeScript Patterns
if (this.isTypeScriptPattern(name)) {
patterns.typeScriptPatterns++;
}
// React Patterns
if (this.isReactPattern(name)) {
patterns.reactPatterns++;
}
// Modern JavaScript Patterns
if (this.isModernJsPattern(name)) {
patterns.modernJsPatterns++;
}
// Class Method Patterns
if (this.isClassMethodPattern(name)) {
patterns.classMethodPatterns++;
}
// Algorithm Patterns
if (this.isAlgorithmPattern(name)) {
patterns.algorithmPatterns++;
}
});
return patterns;
}
// ตรวจสอบ TypeScript Patterns
isTypeScriptPattern(name) {
const tsPatterns = [
/^[A-Z][a-zA-Z]*Options$/, // ConnectionOptions, QueryOptions
/^[A-Z][a-zA-Z]*Config$/, // DatabaseConfig, ApiConfig
/^[A-Z][a-zA-Z]*Handler$/, // EventHandler, ErrorHandler
/^[A-Z][a-zA-Z]*Listener$/, // EventListener, ChangeListener
/^[A-Z][a-zA-Z]*Result$/, // QueryResult, ValidationResult
/^[A-Z][a-zA-Z]*Error$/, // ValidationError, ConnectionError
/^[A-Z][a-zA-Z]*Stats$/, // ConnectionStats, PerformanceStats
/^[A-Z][a-zA-Z]*Schema$/, // ValidationSchema, DatabaseSchema
/^I[A-Z][a-zA-Z]*$/, // Interface naming (IUser, IDatabase)
/^T[A-Z][a-zA-Z]*$/, // Type parameter naming
];
return tsPatterns.some(pattern => pattern.test(name));
}
// ตรวจสอบ React Patterns
isReactPattern(name) {
const reactPatterns = [
/^use[A-Z][a-zA-Z]*$/, // Custom hooks (useApi, useLocalStorage)
/^[A-Z][a-zA-Z]*Context$/, // React Context (ThemeContext, UserContext)
/^[A-Z][a-zA-Z]*Provider$/, // Context Provider (NotificationProvider)
/^handle[A-Z][a-zA-Z]*$/, // Event handlers (handleClick, handleSubmit)
/^on[A-Z][a-zA-Z]*$/, // Event callbacks (onClick, onSubmit)
/^render[A-Z][a-zA-Z]*$/, // Render methods (renderItem, renderField)
/^[a-z]+Ref$/, // React refs (inputRef, containerRef)
/^[A-Z][a-zA-Z]*Table$/, // React Table components (DataTable, UserTable)
/^[A-Z][a-zA-Z]*Form$/, // React Form components (LoginForm, ContactForm)
/^[A-Z][a-zA-Z]*Modal$/, // React Modal components (ConfirmModal, EditModal)
/^[A-Z][a-zA-Z]*Button$/, // React Button components (SubmitButton, CancelButton)
/^[A-Z][a-zA-Z]*Input$/, // React Input components (TextInput, DateInput)
/^[A-Z][a-zA-Z]*List$/, // React List components (ItemList, UserList)
/^[A-Z][a-zA-Z]*Card$/, // React Card components (ProfileCard, NewsCard)
/^[A-Z][a-zA-Z]*Builder$/, // React Builder components (FormBuilder, LayoutBuilder)
/^[A-Z][a-zA-Z]*Dashboard$/, // React Dashboard components
/^[A-Z][a-zA-Z]*Panel$/, // React Panel components
/^[A-Z][a-zA-Z]*Widget$/, // React Widget components
];
return reactPatterns.some(pattern => pattern.test(name));
}
// ตรวจสอบ Modern JavaScript Patterns
isModernJsPattern(name) {
const modernPatterns = [
/^[a-z]+Async$/, // Async functions (fetchAsync, loadAsync)
/^[a-z]+Promise$/, // Promise-based functions
/^[a-z]+Generator$/, // Generator functions
/^[a-z]+Iterator$/, // Iterator functions
/^create[A-Z][a-zA-Z]*$/, // Factory functions (createConnection, createUser)
/^build[A-Z][a-zA-Z]*$/, // Builder functions
/^process[A-Z][a-zA-Z]*$/, // Processing functions
];
return modernPatterns.some(pattern => pattern.test(name));
}
// ตรวจสอบ Class Method Patterns
isClassMethodPattern(name) {
const classPatterns = [
/^[a-z]+Connection$/, // Database connections
/^[a-z]+Manager$/, // Manager classes
/^[a-z]+Builder$/, // Builder classes
/^[a-z]+Factory$/, // Factory classes
/^[a-z]+Repository$/, // Repository pattern
/^[a-z]+Service$/, // Service classes
/^[a-z]+Controller$/, // Controller classes
];
return classPatterns.some(pattern => pattern.test(name));
}
// ตรวจสอบ Algorithm Patterns
isAlgorithmPattern(name) {
const algoPatterns = [
/^[a-z]{1,3}$/, // Short algorithm variables (dp, bfs, dfs)
/^[a-z]+Tree$/, // Tree structures
/^[a-z]+Node$/, // Node structures
/^[a-z]+Graph$/, // Graph structures
/^[a-z]+Queue$/, // Queue structures
/^[a-z]+Stack$/, // Stack structures
];
return algoPatterns.some(pattern => pattern.test(name));
}
// สร้างคำแนะนำที่สามารถทำได้จริง
generateActionableRecommendations(report, analysisResult) {
const recommendations = [];
if (analysisResult.patterns.variableDeclarations > 5) {
recommendations.push({
priority: 'HIGH',
action: 'Review variable declarations',
description: 'Many variables were misidentified as classes. Consider adding comments above variable declarations.',
example: '// Store calculation result\nconst result = calculate();'
});
}
if (analysisResult.patterns.shortVariableNames > 3) {
recommendations.push({
priority: 'MEDIUM',
action: 'Use descriptive variable names',
description: 'Short variable names (i, j, x, y) are common and may not need comments.',
example: 'for (let index = 0; index < items.length; index++)'
});
}
if (report.changes.structuresSkipped > 20) {
recommendations.push({
priority: 'LOW',
action: 'Consider code refactoring',
description: 'High number of skipped structures suggests complex code that may benefit from refactoring.',
example: 'Break down large functions into smaller, well-documented functions'
});
}
// Advanced Pattern Recommendations
const advancedPatterns = this.analyzeAdvancedPatterns(report.skippedStructures);
if (advancedPatterns.typeScriptPatterns > 0) {
recommendations.push({
priority: 'HIGH',
action: 'Add TypeScript interface/type documentation',
description: 'TypeScript constructs detected. These need proper documentation for better code understanding.',
example: '// Interface defining database connection options\ninterface ConnectionOptions { ... }'
});
}
if (advancedPatterns.reactPatterns > 0) {
recommendations.push({
priority: 'HIGH',
action: 'Document React components and hooks',
description: 'React patterns detected. Components and custom hooks should have clear documentation.',
example: '// Custom hook for managing API calls with loading state\nconst useApi = () => { ... }'
});
}
if (advancedPatterns.modernJsPatterns > 0) {
recommendations.push({
priority: 'MEDIUM',
action: 'Document async/await and modern patterns',
description: 'Modern JavaScript patterns detected. Async operations need clear documentation.',
example: '// Asynchronously processes user data with error handling\nasync function processUserData() { ... }'
});
}
if (advancedPatterns.classMethodPatterns > 0) {
recommendations.push({
priority: 'MEDIUM',
action: 'Add class method documentation',
description: 'Advanced class methods detected. Repository/Service patterns need clear documentation.',
example: '// Repository class for managing user database operations\nclass UserRepository { ... }'
});
}
return recommendations;
}
}
// สร้าง file comparison analyzer instance
const fileComparisonAnalyzer = new FileComparisonAnalyzer();
// สร้าง backup manager instance
const backupManager = new OrganizedBackupManager();
// ======================================================================
// Helper Functions - ฟังก์ชันช่วยเหลือสำหรับการประมวลผล
// ======================================================================
// ฟังก์ชันคำนวณหมายเลขบรรทัดที่จัดการ line endings ได้ถูกต้อง
// @param {string} content - เนื้อหาของไฟล์
// @param {number} index - ตำแหน่งที่ต้องการหาหมายเลขบรรทัด
// @returns {number} หมายเลขบรรทัด (เริ่มต้นที่ 1)
// ======================================================================
// EN: Process calculateLineNumber
// TH: ประมวลผล calculateLineNumber
// ======================================================================
function calculateLineNumber(content, index) {
const normalizedContent = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
return normalizedContent.substring(0, index).split('\n').length;
}
// ฟังก์ชันสำหรับ normalize line endings
// @param {string} content - เนื้อหาของไฟล์
// @returns {string} เนื้อหาที่ normalize แล้ว
// ======================================================================
// EN: Process normalizeLineEndings
// TH: ประมวลผล normalizeLineEndings
// ======================================================================
function normalizeLineEndings(content) {
return content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
}
// ฟังก์ชันตรวจสอบว่าแต่ละ structure มี comment เฉพาะตัวหรือไม่
// @param {string} content - เนื้อหาของไฟล์
// @param {Array} structures - รายการ structures ที่ตรวจพบ
// @returns {Map} Map ที่เก็บข้อมูล comment status ของแต่ละ structure
// ======================================================================
// EN: Create analyzeCommentStatus
// TH: สร้าง analyzeCommentStatus
// ======================================================================
function analyzeCommentStatus(content, structures) {
const commentStatusMap = new Map();
const normalizedContent = normalizeLineEndings(content);
const lines = normalizedContent.split('\n');
structures.forEach(structure => {
const structureLine = structure.line - 1; // แปลงเป็น 0-based index
let hasComment = false;
let commentLines = [];
// ตรวจสอบ 3-5 บรรทัดก่อนหน้าเฉพาะ structure นี้
for (let i = 1; i <= 5; i++) {
const checkIndex = structureLine - i;
if (checkIndex >= 0 && checkIndex < lines.length) {
const line = lines[checkIndex];
const trimmed = line.trim();
// เจอ comment line
if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.includes('*/')) {
const commentContent = trimmed.toLowerCase();
const structureName = structure.name.toLowerCase();
// ตรวจสอบว่า comment นี้เกี่ยวข้องกับ structure นี้หรือไม่
// หลัก: ชื่อ structure ต้องตรงกัน หรือ comment ต้องเฉพาะเจาะจง
if (commentContent.includes(structureName) ||
(commentContent.includes('en:') &&
(commentContent.includes(structureName) ||
(commentContent.includes('interface') && structure.type === 'interface_declaration') ||
(commentContent.includes('type') && structure.type === 'type_alias' && commentContent.includes('alias')) ||
(commentContent.includes('static') && structure.type === 'static_method') ||
(commentContent.includes('abstract') && structure.type === 'abstract_class'))) ||
(commentContent.includes('th:') &&
(commentContent.includes(structureName) ||
(commentContent.includes('interface') && structure.type === 'interface_declaration') ||
(commentContent.includes('type') && structure.type === 'type_alias' && commentContent.includes('alias')) ||
(commentContent.includes('static') && structure.type === 'static_method') ||
(commentContent.includes('abstract') && structure.type === 'abstract_class'))) ||
commentContent.includes('======')) {
hasComment = true;
commentLines.push(checkIndex + 1); // แปลงกลับเป็น 1-based
break;
}
}
// เจอ code line อื่นที่ไม่เกี่ยวข้อง ให้หยุดค้นหา
else if (trimmed &&
!trimmed.startsWith('export') &&
!trimmed.startsWith('@') &&
!trimmed.startsWith('{') &&
!trimmed.startsWith('}')) {
break;
}
}
}
commentStatusMap.set(structure.name, {
hasComment,
commentLines,
structure: structure
});
});
return commentStatusMap;
}
// ======================================================================
// JavaScript Tokenizer Engine/เครื่องมือ Tokenizer ของ JavaScript
// ======================================================================
// Token types:ประเภทของโทเค็น
const TOKEN_TYPES = {
// คำหลัก - Keywords
KEYWORD: 'KEYWORD',
// ชื่อตัวแปร/ฟังก์ชัน - Identifiers
IDENTIFIER: 'IDENTIFIER',
// เครื่องหมาย - Operators and punctuation
EQUALS: 'EQUALS', // =
ARROW: 'ARROW', // =>
PAREN_OPEN: 'PAREN_OPEN', // (
PAREN_CLOSE: 'PAREN_CLOSE', // )
BRACE_OPEN: 'BRACE_OPEN', // {
BRACE_CLOSE: 'BRACE_CLOSE', // }
BRACKET_OPEN: 'BRACKET_OPEN', // [
BRACKET_CLOSE: 'BRACKET_CLOSE', // ]
SEMICOLON: 'SEMICOLON', // ;
COMMA: 'COMMA', // ,
// คอมเมนต์ - Comments
LINE_COMMENT: 'LINE_COMMENT', // //
BLOCK_COMMENT: 'BLOCK_COMMENT', // /* */
// สตริง - Strings
STRING: 'STRING',
// ตัวเลข - Numbers
NUMBER: 'NUMBER',
// ช่องว่าง - Whitespace
WHITESPACE: 'WHITESPACE',
NEWLINE: 'NEWLINE',
// จุดสิ้นสุด - End of file
EOF: 'EOF'
};
// คำหลักของ JavaScript, TypeScript, JSX, TSX ครบถ้วน - Complete keywords for JS/TS/JSX/TSX
const KEYWORDS = new Set([
// ═══════════════════════════════════════════════════════════════
// JavaScript Core Keywords
// ═══════════════════════════════════════════════════════════════
'function', 'const', 'let', 'var', 'async', 'await',
'class', 'constructor', 'static', 'get', 'set', 'abstract',
'if', 'else', 'for', 'while', 'do', 'switch', 'case',
'return', 'break', 'continue', 'throw', 'try', 'catch',
'import', 'export', 'default', 'from', 'as', 'finally',
'with', 'delete', 'new', 'this', 'super', 'instanceof',
'of', 'in', 'null', 'undefined', 'true', 'false',
'yield', 'debugger', 'arguments', 'eval',
// ═══════════════════════════════════════════════════════════════
// TypeScript Specific Keywords
// ═══════════════════════════════════════════════════════════════
'interface', 'type', 'enum', 'namespace', 'module',
'declare', 'readonly', 'public', 'private', 'protected',
'implements', 'extends', 'keyof', 'typeof', 'infer',
'never', 'unknown', 'any', 'void', 'string', 'number', 'boolean',
'object', 'symbol', 'bigint', 'unique', 'is', 'asserts',
'override', 'satisfies', 'out', 'in', 'const',
// ═══════════════════════════════════════════════════════════════
// Advanced TypeScript Utility Types & Keywords
// ═══════════════════════════════════════════════════════════════
'Partial', 'Required', 'Pick', 'Omit', 'Exclude', 'Extract',
'NonNullable', 'Parameters', 'ReturnType', 'InstanceType',
'ThisType', 'Record', 'Readonly', 'Array', 'Promise',
'Awaited', 'ConstructorParameters', 'ThisParameterType',
'OmitThisParameter', 'Uppercase', 'Lowercase', 'Capitalize', 'Uncapitalize',
// ═══════════════════════════════════════════════════════════════
// React Core Components & Hooks
// ═══════════════════════════════════════════════════════════════
'React', 'Component', 'PureComponent', 'memo', 'forwardRef',
'createContext', 'useContext', 'createRef', 'useRef',
'useState', 'useEffect', 'useReducer', 'useCallback', 'useMemo',
'useLayoutEffect', 'useImperativeHandle', 'useDebugValue',
'useDeferredValue', 'useTransition', 'useId', 'useSyncExternalStore',
'useInsertionEffect', 'startTransition', 'flushSync',
// ═══════════════════════════════════════════════════════════════
// React Advanced Components & APIs
// ═══════════════════════════════════════════════════════════════
'Fragment', 'StrictMode', 'Suspense', 'SuspenseList', 'Profiler',
'createElement', 'createFactory', 'cloneElement', 'isValidElement',
'Children', 'lazy', 'ErrorBoundary', 'Portal', 'createPortal',
// ═══════════════════════════════════════════════════════════════
// React Router & State Management
// ═══════════════════════════════════════════════════════════════
'Router', 'Route', 'Routes', 'Link', 'NavLink', 'Navigate',
'useNavigate', 'useLocation', 'useParams', 'useSearchParams',
'Outlet', 'BrowserRouter', 'HashRouter', 'MemoryRouter',
'Provider', 'Consumer', 'connect', 'useSelector', 'useDispatch',
// ═══════════════════════════════════════════════════════════════
// JSX Specific Elements & Attributes
// ═══════════════════════════════════════════════════════════════
'JSX', 'IntrinsicElements', 'ElementType', 'ComponentProps',
'PropsWithChildren', 'PropsWithRef', 'RefAttributes',
'ClassAttributes', 'HTMLAttributes', 'DOMAttributes',
'CSSProperties', 'MouseEvent', 'KeyboardEvent', 'FormEvent',
'ChangeEvent', 'FocusEvent', 'TouchEvent', 'WheelEvent',
// ═══════════════════════════════════════════════════════════════
// Next.js Specific Keywords
// ═══════════════════════════════════════════════════════════════
'GetServerSideProps', 'GetStaticProps', 'GetStaticPaths',
'NextPage', 'NextApiRequest', 'NextApiResponse', 'NextApiHandler',
'AppProps', 'Document', 'Head', 'Image', 'Link',
'useRouter', 'withRouter', 'getServerSideProps', 'getStaticProps',
// ═══════════════════════════════════════════════════════════════
// Node.js & Server-side Keywords
// ═══════════════════════════════════════════════════════════════
'require', 'module', 'exports', '__dirname', '__filename',
'process', 'global', 'Buffer', 'console', 'setTimeout', 'setInterval',
'clearTimeout', 'clearInterval', 'setImmediate', 'clearImmediate',
// ═══════════════════════════════════════════════════════════════
// Testing Framework Keywords
// ═══════════════════════════════════════════════════════════════
'describe', 'it', 'test', 'expect', 'beforeEach', 'afterEach',
'beforeAll', 'afterAll', 'jest', 'mock', 'spy', 'stub',
'render', 'screen', 'fireEvent', 'waitFor', 'act',
// ═══════════════════════════════════════════════════════════════
// Build Tools & Bundlers Keywords
// ═══════════════════════════════════════════════════════════════
'webpack', 'vite', 'rollup', 'parcel', 'babel', 'tsc',
'eslint', 'prettier', 'tsconfig', 'package', 'dependencies',
// ═══════════════════════════════════════════════════════════════
// CSS-in-JS & Styling Libraries
// ═══════════════════════════════════════════════════════════════
'styled', 'css', 'keyframes', 'createGlobalStyle', 'ThemeProvider',
'makeStyles', 'useStyles', 'withStyles', 'createStyles',
'Box', 'Stack', 'Grid', 'Container', 'Paper', 'Card',
// ═══════════════════════════════════════════════════════════════
// Database & API Keywords
// ═══════════════════════════════════════════════════════════════
'fetch', 'axios', 'query', 'mutation', 'subscription',
'GraphQL', 'REST', 'API', 'endpoint', 'middleware',
'mongoose', 'prisma', 'sequelize', 'typeorm', 'knex',
// ═══════════════════════════════════════════════════════════════
// Common Library & Framework Keywords
// ═══════════════════════════════════════════════════════════════
'lodash', 'moment', 'dayjs', 'date-fns', 'ramda',
'rxjs', 'observable', 'subject', 'subscription',
'express', 'koa', 'fastify', 'nest', 'apollo',
// ═══════════════════════════════════════════════════════════════
// Development & Debugging Keywords
// ═══════════════════════════════════════════════════════════════
'development', 'production', 'staging', 'test',
'debug', 'trace', 'warn', 'error', 'info', 'log',
'performance', 'profiler', 'benchmark', 'optimization'
]);
// ======================================================================
// Security Manager สำหรับ Parser/ระบบจัดการความปลอดภัยสำหรับ Parser
// ======================================================================
class TokenizerSecurityManager {
constructor(options = {}) {
// SECURITY: กำหนดขีดจำกัดการทำงานเพื่อป้องกัน DoS attacks
this.MAX_DEPTH = options.maxDepth || 100; // ความลึกสูงสุดของ nested structures
this.MAX_TOKENS = options.maxTokens || 500000; // จำนวน token สูงสุด
this.MAX_PARSING_TIME = options.maxParsingTime || 30000; // เวลาประมวลผลสูงสุด (30 วินาที)
this.MAX_LOOP_ITERATIONS = options.maxLoopIterations || 1000000; // จำนวนการวนลูปสูงสุด
this.startTime = null;
this.iterationCount = 0;
this.currentDepth = 0;
this.warnings = [];
}
// เริ่มต้นการตรวจสอบ
// ======================================================================
// EN: Start process class
// TH: คลาสเริ่มกระบวนการ
// ======================================================================
startParsing() {
this.startTime = Date.now();
this.iterationCount = 0;
this.currentDepth = 0;
this.warnings = [];
}
// ตรวจสอบการวนลูปแต่ละครั้ง
checkIteration() {
this.iterationCount++;
// ตรวจสอบ timeout
if (this.startTime && (Date.now() - this.startTime) > this.MAX_PARSING_TIME) {
throw new Error(`SECURITY: Parsing timeout after ${this.MAX_PARSING_TIME}ms. File may contain malicious patterns.`);
}
// ตรวจสอบจำนวนการวนลูป
if (this.iterationCount > this.MAX_LOOP_ITERATIONS) {
throw new Error(`SECURITY: Too many parsing iterations (${this.MAX_LOOP_ITERATIONS}). File may contain complexity attack patterns.`);
}
}
// ตรวจสอบความลึก
enterDepth() {
this.currentDepth++;
if (this.currentDepth > this.MAX_DEPTH) {
throw new Error(`SECURITY: Parsing depth exceeded ${this.MAX_DEPTH} levels. File may contain deeply nested malicious structures.`);
}
}
// ออกจากความลึก
exitDepth() {
if (this.currentDepth > 0) {
this.currentDepth--;
}
}
// ตรวจสอบจำนวน tokens
checkTokenCount(tokenCount) {
if (tokenCount > this.MAX_TOKENS) {
throw new Error(`SECURITY: Token count exceeded ${this.MAX_TOKENS}. File too complex for safe processing.`);
}
}
// เพิ่มคำเตือน
addWarning(message) {
this.warnings.push(`SECURITY WARNING: ${message}`);
}
// รับสถิติ
getStats() {
return {
processingTime: this.startTime ? Date.now() - this.startTime : 0,
iterations: this.iterationCount,
maxDepth: this.currentDepth,
warnings: this.warnings
};
}
}
// JavaScript Tokenizer:โทเค็นไนเซอร์ JavaScript
// ======================================================================
// EN: JavaScriptTokenizer tokenizer
// TH: โทเค็นไนเซอร์ JavaScriptTokenizer
// ======================================================================
class JavaScriptTokenizer {
constructor(code, securityOptions = {}) {
this.code = code;
this.cursor = 0;
this.line = 1;
this.column = 1;
this.tokens = [];
this.braceDepth = 0; // ติดตาม depth ของ {}
this.parenDepth = 0; // ติดตาม depth ของ ()
this.bracketDepth = 0; // ติดตาม depth ของ []
// SECURITY: เพิ่ม Security Manager
this.security = new TokenizerSecurityManager(securityOptions);
}
// แปลงโค้ดทั้งหมดเป็น tokens - Tokenize entire code
tokenize() {
// SECURITY: เริ่มต้นการตรวจสอบ
this.security.startParsing();
try {
while (this.cursor < this.code.length) {
// SECURITY: ตรวจสอบในแต่ละการวนลูป
this.security.checkIteration();
this.readNextToken();
}
// SECURITY: ตรวจสอบจำนวน tokens ทั้งหมด
this.security.checkTokenCount(this.tokens.length);
// เพิ่ม EOF token
this.addToken(TOKEN_TYPES.EOF, '', this.line, this.column);
// แสดงสถิติความปลอดภัยถ้ามีคำเตือน
const stats = this.security.getStats();
if (stats.warnings.length > 0) {
console.warn('Tokenizer Security Warnings:');
stats.warnings.forEach(warning => console.warn(` - ${warning}`));
}
return this.tokens;
} catch (error) {
// รายงานข้อผิดพลาดด้านความปลอดภัย
if (error.message.includes('SECURITY:')) {
console.error(`SECURITY ALERT: ${error.message}`);
console.error('File processing stopped for security reasons.');
}
throw error;
}
}
// อ่าน token ถัดไป - Read next token
readNextToken() {
const char = this.currentChar();
// ข้ามช่องว่าง - Skip whitespace
if (this.isWhitespace(char)) {
this.readWhitespace();
return;
}
// อ่านบรรทัดใหม่ - Read newline
if (char === '\n') {
this.addToken(TOKEN_TYPES.NEWLINE, char, this.line, this.column);
this.advance();
this.line++;
this.column = 1;
return;
}
// อ่านตัวอักษร (identifier หรือ keyword) - Read letters
if (this.isLetter(char) || char === '_' || char === '$') {
this.readIdentifierOrKeyword();
return;
}
// อ่านตัวเลข - Read numbers
if (this.isDigit(char)) {
this.readNumber();
return;
}
// อ่านสตริง - Read strings
if (char === '"' || char === "'" || char === '`') {
this.readString(char);
return;
}
// อ่านคอมเมนต์ - Read comments
if (char === '/' && this.peek() === '/') {
this.readLineComment();
return;
}
if (char === '/' && this.peek() === '*') {
this.readBlockComment();
return;
}
// อ่าน arrow function (=>) - Read arrow operator
if (char === '=' && this.peek() === '>') {
this.addToken(TOKEN_TYPES.ARROW, '=>', this.line, this.column);
this.advance(2);
return;
}
// อ่านเครื่องหมายต่างๆ - Read operators and punctuation
this.readOperatorOrPunctuation(char);
}
// อ่าน identifier หรือ keyword - Read identifier or keyword
readIdentifierOrKeyword() {
const startLine = this.line;
const startColumn = this.column;
let value = '';
while (this.cursor < this.code.length &&
(this.isAlphaNumeric(this.currentChar()) ||
this.currentChar() === '_' ||
this.currentChar() === '$')) {
value += this.currentChar();
this.advance();
}
const type = KEYWORDS.has(value) ? TOKEN_TYPES.KEYWORD : TOKEN_TYPES.IDENTIFIER;
this.addToken(type, value, startLine, startColumn);
}
// อ่านตัวเลข - Read number
readNumber() {
const startLine = this.line;
const startColumn = this.column;
let value = '';
while (this.cursor < this.code.length && this.isDigit(this.currentChar())) {
value += this.currentChar();
this.advance();
}
// รองรับจุดทศนิยม - Support decimal points
if (this.currentChar() === '.' && this.isDigit(this.peek())) {
value += this.currentChar();
this.advance();
while (this.cursor < this.code.length && this.isDigit(this.currentChar())) {
value += this.currentChar();
this.advance();
}
}
this.addToken(TOKEN_TYPES.NUMBER, value, startLine, startColumn);
}
// อ่านสตริง - Read string
readString(quote) {
const startLine = this.line;
const startColumn = this.column;
let value = quote;
this.advance(); // ข้าม quote แรก
while (this.cursor < this.code.length && this.currentChar() !== quote) {
if (this.currentChar() === '\\') {
value += this.currentChar();
this.advance();
if (this.cursor < this.code.length) {
value += this.currentChar();
// Handle escaped newline in template literals
if (this.currentChar() === '\n') {
this.line++;
this.column = 1;
}
this.advance();
}
} else {
// Track newlines inside strings (for template literals)
if (this.currentChar() === '\n') {
this.line++;
this.column = 1;
}
value += this.currentChar();
this.advance();
}
}
if (this.cursor < this.code.length) {
value += this.currentChar(); // เพิ่ม quote ปิด
this.advance();
}
this.addToken(TOKEN_TYPES.STRING, value, startLine, startColumn);
}
// อ่านคอมเมนต์บรรทัดเดียว - Read line comment
readLineComment() {
const startLine = this.line;
const startColumn = this.column;
let value = '';
while (this.cursor < this.code.length && this.currentChar() !== '\n') {
value += this.currentChar();
this.advance();
}
this.addToken(TOKEN_TYPES.LINE_COMMENT, value, startLine, startColumn);
// Advance past the newline character (without incrementing line here)
// The newline will be handled by readNextToken() in the main loop
if (this.cursor < this.code.length && this.currentChar() === '\n') {
this.advance();
this.line++; // Increment line when we pass the newline
this.column = 1;
}
}
// อ่านคอมเมนต์บล็อค - Read block comment
readBlockComment() {
const startLine = this.line;
const startColumn = this.column;
let value = '';
while (this.cursor < this.code.length - 1 &&
!(this.currentChar() === '*' && this.peek() === '/')) {
if (this.currentChar() === '\n') {
this.line++;
this.column = 1;
}
value += this.currentChar();
this.advance();
}
if (this.cursor < this.code.length - 1) {
value += this.currentChar(); // เพิ่ม *
this.advance();
value += this.currentChar(); // เพิ่ม /
this.advance();
}
this.addToken(TOKEN_TYPES.BLOCK_COMMENT, value, startLine, startColumn);
}
// อ่านช่องว่าง - Read whitespace
readWhitespace() {
while (this.cursor < this.code.length && this.isWhitespace(this.currentChar())) {
this.advance();
}
}
// อ่านเครื่องหมายและตัวดำเนินการ - Read operators and punctuation
readOperatorOrPunctuation(char) {
const tokenMap = {
'=': TOKEN_TYPES.EQUALS,
'(': TOKEN_TYPES.PAREN_OPEN,
')': TOKEN_TYPES.PAREN_CLOSE,
'{': TOKEN_TYPES.BRACE_OPEN,
'}': TOKEN_TYPES.BRACE_CLOSE,
'[': TOKEN_TYPES.BRACKET_OPEN,
']': TOKEN_TYPES.BRACKET_CLOSE,
';': TOKEN_TYPES.SEMICOLON,
',': TOKEN_TYPES.COMMA
};
// อัพเดท depth counters
if (char === '{') this.braceDepth++;
else if (char === '}') this.braceDepth--;
else if (char === '(') this.parenDepth++;
else if (char === ')') this.parenDepth--;
else if (char === '[') this.bracketDepth++;
else if (char === ']') this.bracketDepth--;
const type = tokenMap[char] || TOKEN_TYPES.IDENTIFIER;
this.addToken(type, char, this.line, this.column);
this.advance();
}
// Helper methods
currentChar() {
return this.cursor >= this.code.length ? '\0' : this.code[this.cursor];
}
peek(offset = 1) {
const peekPos = this.cursor + offset;
return peekPos >= this.code.length ? '\0' : this.code[peekPos];
}
advance(count = 1) {
for (let i = 0; i < count && this.cursor < this.code.length; i++) {
this.cursor++;
this.column++;
}
}
addToken(type, value, line, column) {
this.tokens.push({
type,
value,
line,
column,
position: this.cursor - value.length,
braceDepth: this.braceDepth,
parenDepth: this.parenDepth,
bracketDepth: this.bracketDepth
});
}
isWhitespace(char) {
return char === ' ' || char === '\t' || char === '\r';
}
isLetter(char) {
return /[a-zA-Z]/.test(char);
}
isDigit(char) {
return /[0-9]/.test(char);
}
isAlphaNumeric(char) {
return this.isLetter(char) || this.isDigit(char);
}
}
// Function Pattern Matcher:ตัวจับรูปแบบฟังก์ชัน
// ======================================================================
// EN: FunctionPatternMatcher pattern matcher
// TH: ตัวจับรูปแบบ FunctionPatternMatcher
// ======================================================================
class FunctionPatternMatcher {
constructor(tokens, securityOptions = {}) {
this.tokens = tokens.filter(t => t.type !== TOKEN_TYPES.WHITESPACE);
this.functions = [];
this.cursor = 0;
this.scopeStack = []; // เก็บ scope ปัจจุบัน (global, class, function)
this.braceDepth = 0; // เก็บระดับ {}
this.inClass = false; // ตรวจสอบว่าอยู่ใน class หรือไม่
this.classNames = []; // เก็บชื่อคลาสที่พบ
// SECURITY: เพิ่ม Security Manager
this.security = new TokenizerSecurityManager(securityOptions);
}
// ค้นหาฟังก์ชันทั้งหมด - Find all functions
findFunctions() {
// SECURITY: เริ่มต้นการตรวจสอบ
this.security.startParsing();
try {
this.buildScopeMap(); // สร้าง scope map ก่อน
this.cursor = 0; // reset cursor
while (this.cursor < this.tokens.length) {
// SECURITY: ตรวจสอบในแต่ละการวนลูป
this.security.checkIteration();
const func = this.matchFunctionPattern();
if (func) {
this.functions.push(func);
} else {
this.cursor++;
}
}
// แสดงสถิติความปลอดภัยถ้ามีคำเตือน
const stats = this.security.getStats();
if (stats.warnings.length > 0) {
console.warn('Parser Security Warnings:');
stats.warnings.forEach(warning => console.warn(` - ${warning}`));
}
return this.functions;
} catch (error) {
// รายงานข้อผิดพลาดด้านความปลอดภัย
if (error.message.includes('SECURITY:')) {
console.error(`SECURITY ALERT: ${error.message}`);
console.error('Function parsing stopped for security reasons.');
}
throw error;
}
}
// สร้าง scope map เพื่อเข้าใจโครงสร้างโค้ด
buildScopeMap() {
let braceDepth = 0;
let inClass = false;
let classDepth = -1;
for (let i = 0; i < this.tokens.length; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'class') {
inClass = true;
classDepth = braceDepth + 1; // คลาสจะอยู่ในระดับ brace ถัดไป
}
if (token.type === TOKEN_TYPES.BRACE_OPEN) {
braceDepth++;
// SECURITY: ตรวจสอบความลึกเกินขีดจำกัด
if (braceDepth > this.security.MAX_DEPTH) {
this.security.addWarning(`Deep nesting detected: ${braceDepth} levels (max recommended: ${this.security.MAX_DEPTH})`);
// ข้ามการประมวลผลในระดับที่ลึกเกินไป
continue;
}
this.security.enterDepth();
}
if (token.type === TOKEN_TYPES.BRACE_CLOSE) {
braceDepth--;
this.security.exitDepth();
// ถ้าออกจากระดับคลาส
if (inClass && braceDepth < classDepth) {
inClass = false;
classDepth = -1;
}
}
// เก็บข้อมูล scope ใน token
token.inClass = inClass;
token.braceDepth = braceDepth;
}
}
// ตรวจสอบรูปแบบฟังก์ชัน - Match function patterns
matchFunctionPattern() {
// ตรวจสอบว่าอยู่ในคอมเมนต์หรือสตริงหรือไม่
if (this.isInCommentOrString()) {
return null;
}
// ===================================================================
// ENHANCED PATTERN DETECTION v2.0 - The Next Frontier
// การตรวจจับรูปแบบขั้นสูง v2.0 - มิติใหม่ของการพัฒนา
// ===================================================================
// Priority 1: TypeScript Advanced Constructs
return this.matchInterfaceDeclaration() ||
this.matchTypeAlias() ||
this.matchEnumDeclaration() ||
this.matchNamespaceDeclaration() ||
this.matchModuleDeclaration() ||
this.matchDeclareStatement() ||
// Priority 2: Class and Object Patterns
this.matchClassDeclaration() ||
this.matchAbstractClass() ||
this.matchGenericClass() ||
// Priority 3: React/JSX Advanced Patterns
this.matchReactComponent() ||
this.matchExportedComponent() ||
this.matchReactHooks() ||
this.matchReactForwardRef() ||
this.matchReactMemo() ||
this.matchHigherOrderComponent() ||
// Priority 4: Function Patterns
this.matchFunctionDeclaration() ||
this.matchArrowFunction() ||
this.matchAsyncFunction() ||
this.matchGeneratorFunction() ||
this.matchIIFE() ||
this.matchCurriedFunction() ||
this.matchFactoryFunction() ||
// Priority 5: Method Patterns
this.matchAsyncClassMethod() ||
this.matchGetter() ||
this.matchSetter() ||
this.matchStaticMethod() ||
this.matchPrivateMethod() ||
this.matchProtectedMethod() ||
this.matchClassMethod() ||
// Priority 6: Modern JavaScript Patterns
this.matchDestructuringAssignment() ||
this.matchSpreadOperator() ||
this.matchAsyncIterator() ||
this.matchProxyHandler() ||
// Priority 7: Algorithm & Data Structure Patterns
this.matchAlgorithmFunction() ||
this.matchDataStructureMethod() ||
this.matchMathFunction() ||
// Priority 8: Express.js & Node.js Patterns
this.matchExpressRoute() ||
this.matchExpressMiddleware() ||
this.matchNodeJSModule();
}
// รูปแบบ: function name() {} - Function declaration pattern
matchFunctionDeclaration() {
// รูปแบบปกติ: function name() {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'function' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.PAREN_OPEN) {
const functionToken = this.currentToken();
const nameToken = this.peekToken(1);
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'function', name, '('
return {
type: 'function_declaration',
name: nameToken.value,
line: functionToken.line,
column: functionToken.column,
parameters: params,
isAsync: false
};
}
// รูปแบบ generator: function* name() {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'function' &&
this.peekToken(1)?.value === '*' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(3)?.type === TOKEN_TYPES.PAREN_OPEN) {
const functionToken = this.currentToken();
const nameToken = this.peekToken(2);
// กรองชื่อที่ไม่ถูกต้อง - ป้องกันการใช้ * เป็นชื่อ
if (!nameToken.value ||
nameToken.value.trim() === '' ||
nameToken.value === '*' ||
nameToken.value.includes('*') ||
/^[^\w]/.test(nameToken.value) ||
nameToken.value.length < 2) {
return null;
}
const params = this.extractParameters(this.cursor + 3);
this.cursor += 4; // ข้าม 'function', '*', name, '('
return {
type: 'generator_function',
name: nameToken.value,
line: functionToken.line,
column: functionToken.column,
parameters: params,
isAsync: false,
isGenerator: true
};
}
// รูปแบบ const name = function* () {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
(this.currentToken()?.value === 'const' || this.currentToken()?.value === 'let' || this.currentToken()?.value === 'var') &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS &&
this.peekToken(3)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(3)?.value === 'function' &&
this.peekToken(4)?.value === '*') {
const keywordToken = this.currentToken();
const nameToken = this.peekToken(1);
// กรองชื่อที่ไม่ถูกต้อง
if (!nameToken.value ||
nameToken.value.trim() === '' ||
nameToken.value === '*' ||
nameToken.value.includes('*') ||
/^[^\w]/.test(nameToken.value) ||
nameToken.value.length < 2) {
return null;
}
const params = this.extractParameters(this.cursor + 5);
this.cursor += 6; // ข้าม keyword, name, '=', 'function', '*', '('
return {
type: 'generator_function',
name: nameToken.value,
line: keywordToken.line,
column: keywordToken.column,
parameters: params,
isAsync: false,
isGenerator: true
};
}
return null;
}
// รูปแบบ: const name = () => {} - Arrow function pattern
matchArrowFunction() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
(this.currentToken()?.value === 'const' || this.currentToken()?.value === 'let' || this.currentToken()?.value === 'var') &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS) {
// หา arrow (=>) ในตำแหน่งที่เป็นไปได้
let arrowPos = this.findArrowInRange(this.cursor + 3, this.cursor + 10);
if (arrowPos !== -1) {
const keywordToken = this.currentToken();
const nameToken = this.peekToken(1);
const params = this.extractParametersBeforeArrow(this.cursor + 3, arrowPos);
this.cursor = arrowPos + 1;
return {
type: 'arrow_function',
name: nameToken.value,
line: keywordToken.line,
column: keywordToken.column,
parameters: params,
isAsync: this.checkAsyncBeforeArrow(this.cursor - 5, arrowPos)
};
}
}
return null;
}
// รูปแบบ: async function name() {} - Async function pattern
matchAsyncFunction() {
// รูปแบบปกติ: async function name() {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'async' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'function' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(3)?.type === TOKEN_TYPES.PAREN_OPEN) {
const asyncToken = this.currentToken();
const nameToken = this.peekToken(2);
const params = this.extractParameters(this.cursor + 3);
this.cursor += 4; // ข้าม 'async', 'function', name, '('
return {
type: 'async_function',
name: nameToken.value,
line: asyncToken.line,
column: asyncToken.column,
parameters: params,
isAsync: true
};
}
// รูปแบบ async generator: async function* name() {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'async' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'function' &&
this.peekToken(2)?.value === '*' &&
this.peekToken(3)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(4)?.type === TOKEN_TYPES.PAREN_OPEN) {
const asyncToken = this.currentToken();
const nameToken = this.peekToken(3);
// กรองชื่อที่ไม่ถูกต้อง
if (!nameToken.value ||
nameToken.value.trim() === '' ||
nameToken.value === '*' ||
nameToken.value.includes('*') ||
/^[^\w]/.test(nameToken.value) ||
nameToken.value.length < 2) {
return null;
}
const params = this.extractParameters(this.cursor + 4);
this.cursor += 5; // ข้าม 'async', 'function', '*', name, '('
return {
type: 'async_generator_function',
name: nameToken.value,
line: asyncToken.line,
column: asyncToken.column,
parameters: params,
isAsync: true,
isGenerator: true
};
}
// รูปแบบ const name = async function* () {}
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
(this.currentToken()?.value === 'const' || this.currentToken()?.value === 'let' || this.currentToken()?.value === 'var') &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS &&
this.peekToken(3)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(3)?.value === 'async' &&
this.peekToken(4)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(4)?.value === 'function' &&
this.peekToken(5)?.value === '*') {
const keywordToken = this.currentToken();
const nameToken = this.peekToken(1);
// กรองชื่อที่ไม่ถูกต้อง
if (!nameToken.value ||
nameToken.value.trim() === '' ||
nameToken.value === '*' ||
nameToken.value.includes('*') ||
/^[^\w]/.test(nameToken.value) ||
nameToken.value.length < 2) {
return null;
}
const params = this.extractParameters(this.cursor + 6);
this.cursor += 7; // ข้าม keyword, name, '=', 'async', 'function', '*', '('
return {
type: 'async_generator_function',
name: nameToken.value,
line: keywordToken.line,
column: keywordToken.column,
parameters: params,
isAsync: true,
isGenerator: true
};
}
return null;
}
// รูปแบบ: methodName() {} (ในคลาส) - Class method pattern
matchClassMethod() {
const currentToken = this.currentToken();
if (currentToken?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(1)?.type === TOKEN_TYPES.PAREN_OPEN) {
const nameToken = currentToken;
// กรองคำที่ไม่ใช่ method
const excludedNames = [
'constructor', 'super', 'this', 'new', 'Map', 'Set', 'Array', 'Object', 'Promise',
'console', 'Math', 'JSON', 'Date', 'String', 'Number', 'Boolean', 'Error',
'require', 'module', 'exports', 'process', 'Buffer', 'setTimeout', 'setInterval',
'function', 'return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue'
];
if (excludedNames.includes(nameToken.value)) {
return null;
}
// กรอง operators และ keywords
if (nameToken.value.length === 1 && /[+\-*/=<>!&|^%]/.test(nameToken.value)) {
return null;
}
// ตรวจสอบว่าไม่ใช่การเรียกใช้ฟังก์ชัน (function call)
const prevToken = this.peekToken(-1);
if (prevToken && (prevToken.value === '.' || prevToken.value === 'new' || prevToken.type === TOKEN_TYPES.PAREN_CLOSE)) {
return null;
}
// ลดความเข้มงวด - ตรวจสอบบริบทแต่ยอมรับกรณีพิเศษ
const inClass = this.isInClassContext();
const nextTokenAfterParen = this.findTokenAfterParentheses();
const hasMethodBody = nextTokenAfterParen && nextTokenAfterParen.type === TOKEN_TYPES.BRACE_OPEN;
// ต้องอยู่ในคลาสหรือมี method body ที่ชัดเจน
if (!inClass && !hasMethodBody) {
return null;
}
// ถ้าไม่มี method body ชัดเจนแต่อยู่ในคลาส ก็ยังพอจะรับได้
if (inClass && !hasMethodBody) {
// ตรวจสอบว่าเป็น method pattern ที่น่าจะใช่หรือไม่
if (!this.isLikelyMethodName(nameToken.value)) {
return null;
}
}
// ตรวจสอบว่าไม่ใช่ชื่อที่ว่างเปล่าหรือมีแค่ symbols
if (!nameToken.value || nameToken.value.trim() === '' || /^[^\w]/.test(nameToken.value)) {
return null;
}
const params = this.extractParameters(this.cursor + 1);
this.cursor += 2; // ข้าม name, '('
return {
type: 'class_method',
name: nameToken.value,
line: nameToken.line,
column: nameToken.column,
parameters: params,
isAsync: false
};
}
return null;
}
// รูปแบบ: async methodName() {} (ในคลาส) - Async class method pattern
matchAsyncClassMethod() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'async' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.PAREN_OPEN) {
const asyncToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าอยู่ในคลาสหรือไม่
if (!this.isInClassContext()) {
return null;
}
// กรองคำที่ไม่ใช่ method
const excludedNames = [
'constructor', 'super', 'this', 'new', 'Map', 'Set', 'Array', 'Object', 'Promise',
'console', 'Math', 'JSON', 'Date', 'String', 'Number', 'Boolean', 'Error',
'require', 'module', 'exports', 'process', 'Buffer', 'setTimeout', 'setInterval',
'function', 'return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue'
];
if (excludedNames.includes(nameToken.value)) {
return null;
}
// ตรวจสอบว่าต่อด้วย { (method body) หรือไม่
const nextTokenAfterParen = this.findTokenAfterParentheses();
if (!nextTokenAfterParen || nextTokenAfterParen.type !== TOKEN_TYPES.BRACE_OPEN) {
return null;
}
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'async', name, '('
return {
type: 'async_class_method',
name: nameToken.value,
line: asyncToken.line,
column: asyncToken.column,
parameters: params,
isAsync: true
};
}
return null;
}
// รูปแบบ: get propertyName() {} - Getter pattern
matchGetter() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'get' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.PAREN_OPEN) {
const getToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าอยู่ในคลาสหรือไม่
if (!this.isInClassContext()) {
return null;
}
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'get', name, '('
return {
type: 'getter',
name: nameToken.value,
line: getToken.line,
column: getToken.column,
parameters: params,
isAsync: false
};
}
return null;
}
// รูปแบบ: set propertyName(value) {} - Setter pattern
matchSetter() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'set' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.PAREN_OPEN) {
const setToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าอยู่ในคลาสหรือไม่
if (!this.isInClassContext()) {
return null;
}
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'set', name, '('
return {
type: 'setter',
name: nameToken.value,
line: setToken.line,
column: setToken.column,
parameters: params,
isAsync: false
};
}
return null;
}
// รูปแบบ: static methodName() {} - Static method pattern
matchStaticMethod() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'static' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.PAREN_OPEN) {
const staticToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าอยู่ในคลาสหรือไม่
if (!this.isInClassContext()) {
return null;
}
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'static', name, '('
return {
type: 'static_method',
name: nameToken.value,
line: staticToken.line,
column: staticToken.column,
parameters: params,
isAsync: false
};
}
return null;
}
// รูปแบบ: class ClassName {} หรือ abstract class ClassName {} - Class declaration pattern
matchClassDeclaration() {
// ตรวจสอบ abstract class pattern
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'abstract' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'class' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER) {
const abstractToken = this.currentToken();
const classToken = this.peekToken(1);
const nameToken = this.peekToken(2);
// ตรวจสอบว่าเป็นคลาสที่ top-level หรือไม่ (ไม่ใช่ nested class)
const currentDepth = abstractToken.braceDepth || 0;
// อนุญาติให้ class อยู่ในระดับที่ลึกกว่าได้บ้าง สำหรับไฟล์ที่ซับซ้อน - แต่ไม่เกิน 2 level
if (currentDepth > 2) {
return null; // ข้าม deeply nested class
}
this.cursor += 3; // ข้าม 'abstract', 'class', name
return {
type: 'class_declaration',
name: nameToken.value,
line: abstractToken.line,
column: abstractToken.column,
parameters: [],
isAsync: false,
isAbstract: true
};
}
// ตรวจสอบ regular class pattern
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'class' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER) {
const classToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าเป็นคลาสที่ top-level หรือไม่ (ไม่ใช่ nested class)
const currentDepth = classToken.braceDepth || 0;
// อนุญาติให้ class อยู่ในระดับที่ลึกกว่าได้บ้าง สำหรับไฟล์ที่ซับซ้อน - แต่ไม่เกิน 2 level
if (currentDepth > 2) {
return null; // ข้าม deeply nested class
}
this.cursor += 2; // ข้าม 'class', name
return {
type: 'class_declaration',
name: nameToken.value,
line: classToken.line,
column: classToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: interface InterfaceName {} - Interface declaration pattern
matchInterfaceDeclaration() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'interface' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER) {
const interfaceToken = this.currentToken();
const nameToken = this.peekToken(1);
this.cursor += 2; // ข้าม 'interface', name
return {
type: 'interface_declaration',
name: nameToken.value,
line: interfaceToken.line,
column: interfaceToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: type TypeName = ... - Type alias declaration pattern
matchTypeAlias() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'type' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS) {
const typeToken = this.currentToken();
const nameToken = this.peekToken(1);
this.cursor += 3; // ข้าม 'type', name, '='
return {
type: 'type_alias',
name: nameToken.value,
line: typeToken.line,
column: typeToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: enum EnumName {} - Enum declaration pattern
matchEnumDeclaration() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'enum' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER) {
const enumToken = this.currentToken();
const nameToken = this.peekToken(1);
this.cursor += 2; // ข้าม 'enum', name
return {
type: 'enum_declaration',
name: nameToken.value,
line: enumToken.line,
column: enumToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: const ComponentName = () => { - React Functional Component pattern
matchReactComponent() {
// Pattern: const ComponentName = () => JSX
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'const' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(1)?.value.match(/^[A-Z][a-zA-Z0-9]*$/) && // Component name starts with uppercase
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS &&
this.peekToken(3)?.type === TOKEN_TYPES.PAREN_OPEN) {
const constToken = this.currentToken();
const nameToken = this.peekToken(1);
const params = this.extractParameters(this.cursor + 3);
this.cursor += 4; // ข้าม 'const', name, '=', '('
return {
type: 'react_component',
name: nameToken.value,
line: constToken.line,
column: constToken.column,
parameters: params,
isAsync: false,
isReactComponent: true
};
}
// Pattern: function ComponentName() { return JSX
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'function' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(1)?.value.match(/^[A-Z][a-zA-Z0-9]*$/)) { // Component name starts with uppercase
const functionToken = this.currentToken();
const nameToken = this.peekToken(1);
const params = this.extractParameters(this.cursor + 2);
this.cursor += 3; // ข้าม 'function', name, '('
return {
type: 'react_component',
name: nameToken.value,
line: functionToken.line,
column: functionToken.column,
parameters: params,
isAsync: false,
isReactComponent: true
};
}
return null;
}
// รูปแบบ: export const/function ComponentName - Exported Component pattern
matchExportedComponent() {
// Pattern: export const ComponentName =
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'export' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'const' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.value.match(/^[A-Z][a-zA-Z0-9]*$/)) {
const exportToken = this.currentToken();
const nameToken = this.peekToken(2);
const params = this.extractParameters(this.cursor + 4); // after 'export const name ='
this.cursor += 5; // ข้าม 'export', 'const', name, '=', '('
return {
type: 'exported_component',
name: nameToken.value,
line: exportToken.line,
column: exportToken.column,
parameters: params,
isAsync: false,
isExported: true,
isReactComponent: true
};
}
// Pattern: export function ComponentName
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'export' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'function' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.value.match(/^[A-Z][a-zA-Z0-9]*$/)) {
const exportToken = this.currentToken();
const nameToken = this.peekToken(2);
const params = this.extractParameters(this.cursor + 3);
this.cursor += 4; // ข้าม 'export', 'function', name, '('
return {
type: 'exported_component',
name: nameToken.value,
line: exportToken.line,
column: exportToken.column,
parameters: params,
isAsync: false,
isExported: true,
isReactComponent: true
};
}
// Pattern: export default class ComponentName
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'export' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'default' &&
this.peekToken(2)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(2)?.value === 'class' &&
this.peekToken(3)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(3)?.value.match(/^[A-Z][a-zA-Z0-9]*$/)) {
const exportToken = this.currentToken();
const nameToken = this.peekToken(3);
this.cursor += 4; // ข้าม 'export', 'default', 'class', name
return {
type: 'exported_class_component',
name: nameToken.value,
line: exportToken.line,
column: exportToken.column,
parameters: [],
isAsync: false,
isExported: true,
isReactComponent: true
};
}
return null;
}
// ตรวจสอบว่าชื่อน่าจะเป็น method หรือไม่
isLikelyMethodName(name) {
// ตรวจสอบ pattern ต่างๆ ที่มักเป็น method name
const methodPatterns = [
/^(get|set|is|has|can|should|will|create|make|build|init|setup|config|configure)/, // action verbs
/^(process|handle|manage|calculate|compute|validate|check|verify|parse|format)/, // processing verbs
/^(render|update|delete|remove|add|insert|save|load|fetch|send|receive|execute)/, // CRUD operations
/^(start|stop|pause|resume|restart|reset|clear|clean|refresh|reload|sync)/, // lifecycle verbs
/^(connect|disconnect|login|logout|authenticate|authorize|encrypt|decrypt)/, // auth/network
/^(on[A-Z]|handle[A-Z]|process[A-Z])/, // event handlers
/^[a-z][a-zA-Z]*[A-Z]/, // camelCase with uppercase
/^[a-z]+[0-9]+/, // มีตัวเลขปน
/.*[A-Z].*[A-Z].*/ // มี uppercase หลายตัว
];
// ห้าม built-in keywords
const excludedPatterns = [
/^(if|else|for|while|switch|case|break|continue|return|try|catch|finally|throw)$/,
/^(var|let|const|function|class|import|export|default|from|as|typeof|instanceof)$/,
/^(null|undefined|true|false|this|super|new|delete|void)$/
];
// ตรวจสอบว่าไม่ใช่ keyword ที่ต้องห้าม
if (excludedPatterns.some(pattern => pattern.test(name))) {
return false;
}
// ตรวจสอบว่าตรงกับ pattern ที่เป็น method
return methodPatterns.some(pattern => pattern.test(name)) ||
(name.length > 2 && /^[a-z][a-zA-Z0-9_]*$/.test(name));
}
// Helper methods - ฟังก์ชันช่วยเหลือ
currentToken() {
return this.cursor < this.tokens.length ? this.tokens[this.cursor] : null;
}
peekToken(offset) {
const pos = this.cursor + offset;
return pos >= 0 && pos < this.tokens.length ? this.tokens[pos] : null;
}
isInCommentOrString() {
const token = this.currentToken();
return token?.type === TOKEN_TYPES.LINE_COMMENT ||
token?.type === TOKEN_TYPES.BLOCK_COMMENT ||
token?.type === TOKEN_TYPES.STRING;
}
extractParameters(startPos) {
const params = [];
let pos = startPos;
let depth = 1; // เริ่มที่ 1 เพราะเราข้าม '(' แรกแล้ว
while (pos < this.tokens.length && depth > 0) {
const token = this.tokens[pos];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
depth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
depth--;
} else if (token.type === TOKEN_TYPES.IDENTIFIER && depth === 1) {
params.push(token.value);
}
pos++;
}
return params;
}
extractParametersBeforeArrow(startPos, arrowPos) {
const params = [];
let pos = startPos;
while (pos < arrowPos) {
const token = this.tokens[pos];
if (token.type === TOKEN_TYPES.IDENTIFIER) {
params.push(token.value);
}
pos++;
}
return params;
}
// หาโทเค็นหลังจากวงเล็บปิด () - Find token after parentheses
findTokenAfterParentheses() {
let pos = this.cursor + 1; // เริ่มที่ (
let depth = 1;
while (pos < this.tokens.length && depth > 0) {
const token = this.tokens[pos];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
depth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
depth--;
}
pos++;
}
// ข้าม whitespace และหาโทเค็นถัดไป
while (pos < this.tokens.length && this.tokens[pos].type === TOKEN_TYPES.WHITESPACE) {
pos++;
}
return pos < this.tokens.length ? this.tokens[pos] : null;
}
findArrowInRange(start, end) {
// ขยายขอบเขตการค้นหาให้กว้างขึ้นสำหรับ parameter ที่ซับซ้อน
const searchEnd = Math.min(end + 15, this.tokens.length);
for (let i = start; i < searchEnd; i++) {
if (this.tokens[i]?.type === TOKEN_TYPES.ARROW) {
// ตรวจสอบว่าไม่อยู่ในบล็อกอื่น (เช่น object literal)
let braceCount = 0;
let parenCount = 0;
for (let j = start; j < i; j++) {
const checkToken = this.tokens[j];
if (checkToken) {
if (checkToken.type === TOKEN_TYPES.BRACE_OPEN) braceCount++;
else if (checkToken.type === TOKEN_TYPES.BRACE_CLOSE) braceCount--;
else if (checkToken.type === TOKEN_TYPES.PAREN_OPEN) parenCount++;
else if (checkToken.type === TOKEN_TYPES.PAREN_CLOSE) parenCount--;
}
}
// ถ้า brace และ paren สมดุล แสดงว่าเป็น arrow function ที่ถูกต้อง
if (braceCount === 0 && parenCount <= 0) {
return i;
}
}
}
return -1;
}
checkAsyncBeforeArrow(start, end) {
for (let i = start; i < end; i++) {
if (this.tokens[i]?.type === TOKEN_TYPES.KEYWORD &&
this.tokens[i]?.value === 'async') {
return true;
}
}
return false;
}
isInClassContext() {
// ตรวจสอบด้วยการนับ braces และหา class keyword
let braceDepth = 0;
let foundClass = false;
let classStart = -1;
// ตรวจสอบย้อนหลังเพื่อหา class declaration
for (let i = Math.max(0, this.cursor - 100); i < this.cursor; i++) {
const token = this.tokens[i];
if (!token) continue;
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'class') {
foundClass = true;
classStart = i;
braceDepth = 0; // รีเซ็ต
}
if (foundClass && i > classStart) {
if (token.type === TOKEN_TYPES.BRACE_OPEN) {
braceDepth++;
} else if (token.type === TOKEN_TYPES.BRACE_CLOSE) {
braceDepth--;
if (braceDepth <= 0) {
foundClass = false; // ออกจาก class แล้ว
}
}
}
}
// ตรวจสอบว่าปัจจุบันอยู่ใน class body หรือไม่
return foundClass && braceDepth > 0;
}
}
// ======================================================================
// Structure Parser Engine/เครื่องมือ Parser โครงสร้างใหม่
// ======================================================================
// Structure Parser: ตัววิเคราะห์โครงสร้างโค้ดแบบใหม่ (แทนที่ FunctionPatternMatcher)
class StructureParser {
constructor(tokens, securityOptions = {}) {
this.tokens = tokens.filter(t => t.type !== TOKEN_TYPES.WHITESPACE);
this.cursor = 0;
this.scopeStack = [];
this.structures = [];
// SECURITY: เพิ่ม Security Manager
this.security = new TokenizerSecurityManager(securityOptions);
}
// วิเคราะห์โครงสร้างทั้งหมด
// ======================================================================
// EN: Parse data class
// TH: คลาสแปลงข้อมูล
// ======================================================================
parse() {
// SECURITY: เริ่มต้นการตรวจสอบ
this.security.startParsing();
try {
while (this.cursor < this.tokens.length) {
// SECURITY: ตรวจสอบในแต่ละการวนลูป
this.security.checkIteration();
const structure = this.parseDeclaration();
if (structure) {
this.structures.push(structure);
}
}
// แสดงสถิติความปลอดภัยถ้ามีคำเตือน
const stats = this.security.getStats();
if (stats.warnings.length > 0) {
console.warn('Parser Security Warnings:');
stats.warnings.forEach(warning => console.warn(` - ${warning}`));
}
return this.structures;
} catch (error) {
// รายงานข้อผิดพลาดด้านความปลอดภัย
if (error.message.includes('SECURITY:')) {
console.error(`SECURITY ALERT: ${error.message}`);
console.error('Structure parsing stopped for security reasons.');
}
throw error;
}
}
// วิเคราะห์โครงสร้างหลักในระดับบนสุด (Global Scope)
parseDeclaration() {
const currentToken = this.currentToken();
if (!currentToken) return null;
// ตรวจสอบว่าอยู่ในคอมเมนต์หรือสตริงหรือไม่
if (this.isInCommentOrString()) {
this.advance();
return null;
}
// ตรวจจับ class declaration: class MyClass { ... }
if (currentToken.type === TOKEN_TYPES.KEYWORD && currentToken.value === 'class') {
return this.parseClassDeclaration();
}
// ตรวจจับ function declaration: function myFunc() { ... }
if (currentToken.type === TOKEN_TYPES.KEYWORD && currentToken.value === 'function') {
return this.parseFunctionDeclaration();
}
// ตรวจจับ const/let/var ที่เป็น arrow function หรือ function expression
if (currentToken.type === TOKEN_TYPES.KEYWORD && ['const', 'let', 'var'].includes(currentToken.value)) {
return this.parseVariableDeclaration();
}
// ถ้าไม่ใช่โครงสร้างที่สนใจ ให้ข้ามไป
this.advance();
return null;
}
// วิเคราะห์ Class
parseClassDeclaration() {
const classToken = this.advance(); // consume 'class'
if (this.currentToken()?.type !== TOKEN_TYPES.IDENTIFIER) return null;
const nameToken = this.advance(); // consume class name
const classStructure = {
type: 'class_declaration',
name: nameToken.value,
line: classToken.line,
column: classToken.column,
methods: []
};
// หา body ของ class
if (this.currentToken()?.type === TOKEN_TYPES.BRACE_OPEN) {
const bodyStartIndex = this.cursor;
const bodyEndIndex = this.findMatchingBrace(bodyStartIndex);
if (bodyEndIndex !== -1) {
// SECURITY: ตรวจสอบระดับความลึก
this.security.enterDepth();
// เข้าไปวิเคราะห์ภายใน body ของ class
this.parseClassBody(classStructure, bodyEndIndex);
this.cursor = bodyEndIndex + 1; // เลื่อน cursor ไปหลัง '}'
this.security.exitDepth();
}
}
return classStructure;
}
// วิเคราะห์ภายใน Class Body
parseClassBody(classStructure, bodyEndIndex) {
this.advance(); // consume '{'
while (this.cursor < bodyEndIndex) {
const token = this.currentToken();
if (!token) break;
let isAsync = false;
let isStatic = false;
let kind = 'method'; // 'method', 'get', 'set'
// ตรวจจับ async / static / get / set
if (token.type === TOKEN_TYPES.KEYWORD) {
if (token.value === 'async') {
isAsync = true;
this.advance();
} else if (token.value === 'static') {
isStatic = true;
this.advance();
} else if (token.value === 'get' || token.value === 'set') {
kind = token.value;
this.advance();
}
}
// ตรวจจับ Method: methodName(...) { ... }
const nameToken = this.currentToken();
const parenToken = this.peekToken(1);
if (nameToken?.type === TOKEN_TYPES.IDENTIFIER && parenToken?.type === TOKEN_TYPES.PAREN_OPEN) {
// ไม่จับ constructor เพราะไม่ต้องการคอมเมนต์
if (nameToken.value !== 'constructor') {
classStructure.methods.push({
type: 'class_method',
name: nameToken.value,
line: nameToken.line,
column: nameToken.column,
isAsync,
isStatic,
kind,
parameters: this.extractParameters(this.cursor + 1)
});
}
// ข้ามผ่าน method ทั้งหมดไปอย่างรวดเร็ว
const methodBodyStart = this.findToken(TOKEN_TYPES.BRACE_OPEN, this.cursor);
if (methodBodyStart !== -1) {
const methodBodyEnd = this.findMatchingBrace(methodBodyStart);
if (methodBodyEnd !== -1) {
this.cursor = methodBodyEnd + 1;
continue;
}
}
}
this.advance();
}
}
// วิเคราะห์ Function
parseFunctionDeclaration() {
const funcToken = this.advance(); // consume 'function'
// ตรวจจับ generator function: function* name()
let isGenerator = false;
if (this.currentToken()?.value === '*') {
isGenerator = true;
this.advance(); // consume '*'
}
if (this.currentToken()?.type !== TOKEN_TYPES.IDENTIFIER) {
// อาจเป็น function expression ที่ไม่มีชื่อ
return null;
}
const nameToken = this.advance();
const funcStructure = {
type: isGenerator ? 'generator_function' : 'function_declaration',
name: nameToken.value,
line: funcToken.line,
column: funcToken.column,
parameters: this.extractParameters(this.cursor),
isAsync: false
};
// ข้ามไปจนสุด body ของฟังก์ชัน
const bodyStart = this.findToken(TOKEN_TYPES.BRACE_OPEN, this.cursor);
if (bodyStart !== -1) {
const bodyEnd = this.findMatchingBrace(bodyStart);
if (bodyEnd !== -1) {
this.cursor = bodyEnd + 1;
}
}
return funcStructure;
}
// วิเคราะห์ const/let/var = ...
parseVariableDeclaration() {
this.advance(); // consume const/let/var
const nameToken = this.currentToken();
if (nameToken?.type !== TOKEN_TYPES.IDENTIFIER) return null;
this.advance(); // consume name
if (this.currentToken()?.type !== TOKEN_TYPES.EQUALS) return null;
this.advance(); // consume '='
// ตรวจจับ async keyword
let isAsync = false;
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD && this.currentToken().value === 'async') {
isAsync = true;
this.advance();
}
// ตรวจจับ arrow function: () => { ... }
const nextToken = this.currentToken();
let isArrowFunc = false;
if (nextToken?.type === TOKEN_TYPES.PAREN_OPEN) {
const closingParen = this.findMatchingParen(this.cursor);
if (closingParen !== -1 && this.tokens[closingParen + 1]?.type === TOKEN_TYPES.ARROW) {
isArrowFunc = true;
}
} else if (nextToken?.type === TOKEN_TYPES.IDENTIFIER) {
// Handle arrow functions without parens: a => ...
if (this.peekToken(1)?.type === TOKEN_TYPES.ARROW) {
isArrowFunc = true;
}
}
if (isArrowFunc) {
const funcStructure = {
type: 'arrow_function',
name: nameToken.value,
line: nameToken.line,
column: nameToken.column,
isAsync,
parameters: this.extractArrowParameters(this.cursor)
};
const bodyStart = this.findToken(TOKEN_TYPES.BRACE_OPEN, this.cursor);
if (bodyStart !== -1) {
const bodyEnd = this.findMatchingBrace(bodyStart);
if (bodyEnd !== -1) {
this.cursor = bodyEnd + 1;
}
} else {
// Arrow function แบบไม่มี {} - หา semicolon
const semicolon = this.findToken(TOKEN_TYPES.SEMICOLON, this.cursor);
if (semicolon !== -1) this.cursor = semicolon + 1;
}
return funcStructure;
}
return null;
}
// --- Helper Methods ---
// ฟังก์ชันหัวใจ: ค้นหาวงเล็บปีกกาปิดที่คู่กัน
findMatchingBrace(startIndex) {
let depth = 1;
for (let i = startIndex + 1; i < this.tokens.length; i++) {
// SECURITY: ป้องกันการวนลูปไม่สิ้นสุด
if (i - startIndex > this.security.MAX_LOOP_ITERATIONS) {
this.security.addWarning(`Potential infinite loop detected in findMatchingBrace`);
break;
}
if (this.tokens[i].type === TOKEN_TYPES.BRACE_OPEN) {
depth++;
} else if (this.tokens[i].type === TOKEN_TYPES.BRACE_CLOSE) {
depth--;
if (depth === 0) {
return i;
}
}
}
return -1; // Not found
}
// ค้นหาวงเล็บปิดที่คู่กัน
findMatchingParen(startIndex) {
let depth = 1;
for (let i = startIndex + 1; i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.PAREN_OPEN) {
depth++;
} else if (this.tokens[i].type === TOKEN_TYPES.PAREN_CLOSE) {
depth--;
if (depth === 0) {
return i;
}
}
}
return -1; // Not found
}
// ค้นหา token ประเภทที่ต้องการ
findToken(type, startIndex) {
for (let i = startIndex; i < this.tokens.length; i++) {
if (this.tokens[i].type === type) return i;
}
return -1;
}
// ดึงพารามิเตอร์ของฟังก์ชัน (ปรับปรุงจากเดิม)
extractParameters(parenIndex) {
if (this.tokens[parenIndex]?.type !== TOKEN_TYPES.PAREN_OPEN) return [];
const params = [];
const closingParen = this.findMatchingParen(parenIndex);
if (closingParen === -1) return [];
// ดึง parameter names ระหว่าง ( และ )
for (let i = parenIndex + 1; i < closingParen; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.IDENTIFIER) {
params.push(token.value);
}
}
return params;
}
// ดึงพารามิเตอร์ของ arrow function
extractArrowParameters(startIndex) {
const firstToken = this.tokens[startIndex];
if (!firstToken) return [];
if (firstToken.type === TOKEN_TYPES.PAREN_OPEN) {
return this.extractParameters(startIndex);
} else if (firstToken.type === TOKEN_TYPES.IDENTIFIER) {
return [firstToken.value];
}
return [];
}
// ตรวจสอบว่าอยู่ในคอมเมนต์หรือสตริงหรือไม่
isInCommentOrString() {
const currentToken = this.currentToken();
return currentToken && (
currentToken.type === TOKEN_TYPES.LINE_COMMENT ||
currentToken.type === TOKEN_TYPES.BLOCK_COMMENT ||
currentToken.type === TOKEN_TYPES.STRING
);
}
currentToken() { return this.tokens[this.cursor]; }
peekToken(offset = 1) { return this.tokens[this.cursor + offset]; }
advance() {
if (!this.isAtEnd()) this.cursor++;
return this.tokens[this.cursor - 1];
}
isAtEnd() { return this.cursor >= this.tokens.length; }
// Method สำหรับ backward compatibility กับ FunctionPatternMatcher
findFunctions() {
const structures = this.parse();
const allItems = [];
structures.forEach(s => {
if (s.type === 'class_declaration') {
// เพิ่มตัวคลาสเอง
allItems.push({
type: s.type,
name: s.name,
line: s.line,
column: s.column,
parameters: []
});
// เพิ่มเมธอดทั้งหมดในคลาส
if (s.methods) {
s.methods.forEach(m => allItems.push(m));
}
} else {
allItems.push(s);
}
});
return allItems;
}
}
// ======================================================================
// Smart File Analyzer Engine/เครื่องมือวิเคราะห์ไฟล์อัจฉริยะ
// ======================================================================
// Smart File Analyzer: ตัวเรียนรู้และวิเคราะห์ไฟล์ทั้งหมดก่อนสร้างคอมเมนต์
class SmartFileAnalyzer {
constructor(content, securityOptions = {}) {
this.content = content;
this.lines = content.split('\n');
this.security = new TokenizerSecurityManager(securityOptions);
// ข้อมูลที่เรียนรู้ได้จากไฟล์
this.fileBlueprint = {
classes: new Map(), // Map<className, classInfo>
functions: new Map(), // Map<functionName, functionInfo>
patterns: new Set(), // Set ของ patterns ที่พบ
keywords: new Set(), // Set ของ keywords ที่ควรเพิ่ม
relationships: new Map(), // Map ของความสัมพันธ์ระหว่าง classes/functions
context: { // บริบทของไฟล์
type: 'unknown', // 'api', 'database', 'ui', 'algorithm', etc.
domain: 'unknown', // 'web', 'crypto', 'data', etc.
complexity: 'simple' // 'simple', 'moderate', 'complex'
}
};
}
// วิเคราะห์ไฟล์ทั้งหมดและสร้าง blueprint
analyzeFile() {
try {
this.security.startParsing();
// Phase 0: TypeScript Pre-analysis/การวิเคราะห์ TypeScript เบื้องต้น
this.analyzeTypeScriptStructures();
// Phase 1: Tokenize และ Parse โครงสร้าง
const tokenizer = new JavaScriptTokenizer(this.content, this.security);
const tokens = tokenizer.tokenize();
const structureAnalyzer = new StructureAnalyzer(tokens, this.content);
const structures = structureAnalyzer.analyzeAll();
// Phase 2: วิเคราะห์โครงสร้างลึก
this.analyzeStructures(structures);
// Phase 3: ค้นหาลวดลายและความสัมพันธ์
this.findPatternsAndRelationships();
// Phase 4: สร้าง dynamic keywords
this.generateDynamicKeywords();
// Phase 5: กำหนดบริบทของไฟล์
this.determineFileContext();
// Phase 6: AI-Powered Intent Understanding (NEW!)
this.aiIntentAnalysis = this.analyzeCodeIntent();
console.log(` Smart Analysis Complete: Found ${this.fileBlueprint.classes.size} classes, ${this.fileBlueprint.functions.size} functions, ${this.fileBlueprint.keywords.size} keywords`);
// Safe access to AI analysis results
if (this.aiIntentAnalysis && typeof this.aiIntentAnalysis === 'object') {
// Count total intents found across all categories
let totalIntents = 0;
let totalRisks = 0;
if (this.aiIntentAnalysis.businessLogic) totalIntents += this.aiIntentAnalysis.businessLogic.size || 0;
if (this.aiIntentAnalysis.securityMeasures) totalRisks += this.aiIntentAnalysis.securityMeasures.size || 0;
if (this.aiIntentAnalysis.algorithmicPurpose) totalIntents += this.aiIntentAnalysis.algorithmicPurpose.size || 0;
console.log(` AI Intent Analysis: Detected ${totalIntents} logical patterns, ${totalRisks} security concerns`);
} else {
console.log(` AI Intent Analysis: Completed basic analysis`);
}
return this.fileBlueprint;
} catch (error) {
console.error(' Smart Analysis Error:', error.message);
return null;
}
}
// วิเคราะห์โครงสร้าง TypeScript เฉพาะ
analyzeTypeScriptStructures() {
// วิเคราะห์ interfaces
this.analyzeInterfaces();
// วิเคราะห์ type aliases
this.analyzeTypeAliases();
// วิเคราะห์ enums
this.analyzeEnums();
// วิเคราะห์ abstract classes
this.analyzeAbstractClasses();
// วิเคราะห์ generics
this.analyzeGenerics();
// วิเคราะห์ const declarations (JavaScript/Node.js เฉพาะ)
this.analyzeConstDeclarations();
}
// วิเคราะห์ const declarations
analyzeConstDeclarations() {
const constRegex = /const\s+(\w+)\s*=\s*([^;]+);?/g;
let match;
while ((match = constRegex.exec(this.content)) !== null) {
const constName = match[1];
const constValue = match[2].trim();
const lineNumber = calculateLineNumber(this.content, match.index);
const constType = this.inferConstType(constName, constValue);
// ข้ามถ้าเป็น require statements หรือ imports
if (constType === 'require' || constType === 'import') {
continue;
}
// ======================================================================
// EN: constInfo constants
// TH: ค่าคงที่ constInfo
// ======================================================================
const constInfo = {
name: constName,
line: lineNumber,
type: constType,
value: constValue,
purpose: this.inferConstPurpose(constName, constValue, constType),
complexity: constValue.length > 200 ? 'high' : constValue.length > 50 ? 'moderate' : 'simple'
};
// เพิ่มเข้า functions หรือ classes ตามประเภท
if (constType === 'function' || constType === 'arrow_function' || constType === 'middleware') {
this.fileBlueprint.functions.set(constName, constInfo);
this.addPattern(constName, 'const_function');
} else {
this.fileBlueprint.classes.set(constName, constInfo);
this.addPattern(constName, constType);
}
this.addDynamicKeyword(constName.toLowerCase(), `${constName} ${constType}`, this.getThaiConstType(constType, constName));
}
}
// อนุมานประเภทของ const
inferConstType(constName, constValue) {
const name = constName.toLowerCase();
const value = constValue.toLowerCase();
// ตรวจสอบ require/import
if (value.includes('require(') || value.includes('import(')) {
return 'require';
}
// ตรวจสอบ functions
if (value.includes('=>') || value.includes('function(')) {
if (name.includes('middleware') || name.includes('auth') || name.includes('limit') || value.includes('(req, res')) {
return 'middleware';
}
return 'arrow_function';
}
// ตรวจสอบ Express app
if (value.includes('express()')) {
return 'express_app';
}
// ตรวจสอบ configuration objects
if (name.includes('config') || name.includes('setting') || name.includes('option')) {
return 'configuration';
}
// ตรวจสอบ database/data objects
if (name.includes('database') || name.includes('db') || name.includes('data') || value.includes('users:') || value.includes('posts:')) {
return 'data_store';
}
// ตรวจสอบ storage/upload objects
if (name.includes('storage') || name.includes('upload') || value.includes('multer.') || value.includes('diskStorage')) {
return 'storage_config';
}
// ตรวจสอบ rate limiters
if (name.includes('limit') || value.includes('rateLimit(')) {
return 'rate_limiter';
}
// ตรวจสอบ objects ทั่วไป
if (value.startsWith('{') || value.includes('{')) {
return 'object';
}
// ตรวจสอบ arrays
if (value.startsWith('[')) {
return 'array';
}
return 'constant';
}
// อนุมานวัตถุประสงค์ของ const
inferConstPurpose(constName, constValue, constType) {
const name = constName.toLowerCase();
switch (constType) {
case 'configuration':
return 'app_config';
case 'data_store':
return 'in_memory_database';
case 'storage_config':
return 'file_upload_config';
case 'rate_limiter':
return 'api_rate_limiter';
case 'middleware':
if (name.includes('auth')) return 'auth_middleware';
if (name.includes('validate')) return 'validation_middleware';
if (name.includes('async')) return 'async_wrapper';
return 'express_middleware';
case 'arrow_function':
if (name.includes('find')) return 'finder_function';
if (name.includes('generate')) return 'generator_function';
return 'utility_function';
case 'express_app':
return 'express_application';
default:
return constType;
}
}
// แปลประเภท const เป็นภาษาไทย
getThaiConstType(constType, constName) {
const name = constName.toLowerCase();
switch (constType) {
case 'configuration':
return `การกำหนดค่า ${constName}`;
case 'data_store':
return `ที่เก็บข้อมูล ${constName}`;
case 'storage_config':
return `การกำหนดค่าการจัดเก็บไฟล์ ${constName}`;
case 'rate_limiter':
return `ตัวจำกัดอัตรา ${constName}`;
case 'middleware':
return `มิดเดิลแวร์ ${constName}`;
case 'arrow_function':
return `ฟังก์ชัน ${constName}`;
case 'express_app':
return `แอปพลิเคชัน Express ${constName}`;
case 'object':
return `ออบเจ็กต์ ${constName}`;
case 'array':
return `อาร์เรย์ ${constName}`;
default:
return `ค่าคงที่ ${constName}`;
}
} // วิเคราะห์ interfaces
analyzeInterfaces() {
// ======================================================================
// EN: Interface definition for \
// TH: การกำหนด interface สำหรับ \
// ======================================================================
const interfaceRegex = /interface\s+(\w+)(?:<[^>]*>)?\s*(?:extends\s+[^{]+)?\s*{/g;
let match;
while ((match = interfaceRegex.exec(this.content)) !== null) {
const interfaceName = match[1];
const lineNumber = calculateLineNumber(this.content, match.index);
const interfaceInfo = {
name: interfaceName,
line: lineNumber,
type: 'interface',
properties: this.extractInterfaceProperties(match.index),
purpose: this.inferInterfacePurpose(interfaceName),
complexity: 'simple'
};
this.fileBlueprint.classes.set(interfaceName, interfaceInfo);
this.addPattern(interfaceName, 'interface');
this.addDynamicKeyword(interfaceName.toLowerCase(), `${interfaceName} interface`, `อินเทอร์เฟซ ${interfaceName}`);
}
}
// วิเคราะห์ type aliases
analyzeTypeAliases() {
const typeRegex = /type\s+(\w+)(?:<[^>]*>)?\s*=\s*([^;]+);?/g;
let match;
while ((match = typeRegex.exec(this.content)) !== null) {
const typeName = match[1];
const typeDefinition = match[2].trim();
const lineNumber = this.content.substring(0, match.index).split('\n').length;
const typeInfo = {
name: typeName,
line: lineNumber,
type: 'type_alias',
definition: typeDefinition,
purpose: this.inferTypePurpose(typeName, typeDefinition),
complexity: typeDefinition.length > 100 ? 'high' : 'simple'
};
this.fileBlueprint.functions.set(typeName, typeInfo);
this.addPattern(typeName, 'type');
this.addDynamicKeyword(typeName.toLowerCase(), `${typeName} type definition`, `นิยามประเภท ${typeName}`);
}
}
// วิเคราะห์ enums
analyzeEnums() {
const enumRegex = /enum\s+(\w+)\s*{([^}]+)}/g;
let match;
while ((match = enumRegex.exec(this.content)) !== null) {
const enumName = match[1];
const enumBody = match[2];
const lineNumber = this.content.substring(0, match.index).split('\n').length;
const enumInfo = {
name: enumName,
line: lineNumber,
type: 'enum',
values: this.extractEnumValues(enumBody),
purpose: this.inferEnumPurpose(enumName),
complexity: 'simple'
};
this.fileBlueprint.classes.set(enumName, enumInfo);
this.addPattern(enumName, 'enum');
this.addDynamicKeyword(enumName.toLowerCase(), `${enumName} enumeration`, `การนับ ${enumName}`);
}
}
// วิเคราะห์ abstract classes
analyzeAbstractClasses() {
// ======================================================================
// EN: \ component
// TH: ส่วนประกอบ \
// ======================================================================
const abstractRegex = /abstract\s+class\s+(\w+)(?:<[^>]*>)?(?:\s+extends\s+\w+)?(?:\s+implements\s+[^{]+)?\s*{/g;
let match;
while ((match = abstractRegex.exec(this.content)) !== null) {
const className = match[1];
const lineNumber = this.content.substring(0, match.index).split('\n').length;
const classInfo = {
name: className,
line: lineNumber,
type: 'abstract_class',
isAbstract: true,
methods: new Map(),
properties: new Set(),
purpose: this.inferAbstractClassPurpose(className),
complexity: 'moderate'
};
this.fileBlueprint.classes.set(className, classInfo);
this.addPattern(className, 'abstract_class');
this.addDynamicKeyword(className.toLowerCase(), `${className} abstract class`, `คลาสนามธรรม ${className}`);
}
}
// วิเคราะห์ generics
analyzeGenerics() {
const genericRegex = /<([^>]+)>/g;
let match;
while ((match = genericRegex.exec(this.content)) !== null) {
const genericParams = match[1].split(',').map(param => param.trim());
genericParams.forEach(param => {
if (param.length === 1 && /[A-Z]/.test(param)) {
this.addDynamicKeyword(`generic_${param.toLowerCase()}`, `Generic type ${param}`, `ประเภททั่วไป ${param}`);
}
});
}
} // วิเคราะห์โครงสร้างที่ได้จาก parser
analyzeStructures(structures) {
structures.forEach(structure => {
if (structure.type === 'class_declaration') {
this.analyzeClass(structure);
} else {
this.analyzeFunction(structure);
}
});
}
// วิเคราะห์คลาสอย่างละเอียด
analyzeClass(classStructure) {
const className = classStructure.name;
const classInfo = {
name: className,
line: classStructure.line,
methods: new Map(),
properties: new Set(),
extends: null,
implements: [],
purpose: this.inferClassPurpose(className),
complexity: this.calculateClassComplexity(classStructure)
};
// วิเคราะห์ methods ในคลาส
if (classStructure.methods) {
classStructure.methods.forEach(method => {
const methodInfo = {
name: method.name,
type: method.type,
line: method.line,
isAsync: method.isAsync || false,
isStatic: method.isStatic || false,
kind: method.kind || 'method',
parameters: method.parameters || [],
purpose: this.inferMethodPurpose(method.name, className),
accessibility: this.inferAccessibility(method.name)
};
classInfo.methods.set(method.name, methodInfo);
});
}
this.fileBlueprint.classes.set(className, classInfo);
this.addPattern(className, 'class');
}
// วิเคราะห์ฟังก์ชันอย่างละเอียด
analyzeFunction(funcStructure) {
const functionName = funcStructure.name;
const functionInfo = {
name: functionName,
type: funcStructure.type,
line: funcStructure.line,
parameters: funcStructure.parameters || [],
isAsync: funcStructure.isAsync || false,
isGenerator: funcStructure.isGenerator || false,
purpose: this.inferFunctionPurpose(functionName),
scope: 'global',
complexity: this.calculateFunctionComplexity(funcStructure)
};
this.fileBlueprint.functions.set(functionName, functionInfo);
this.addPattern(functionName, 'function');
}
// ค้นหาลวดลายและความสัมพันธ์
findPatternsAndRelationships() {
// หาความสัมพันธ์ระหว่าง classes
for (const [className, classInfo] of this.fileBlueprint.classes) {
// ค้นหา inheritance และ composition patterns
this.findClassRelationships(className, classInfo);
// ค้นหา design patterns
this.detectDesignPatterns(className, classInfo);
}
// หาความสัมพันธ์ระหว่าง functions
for (const [funcName, funcInfo] of this.fileBlueprint.functions) {
this.findFunctionRelationships(funcName, funcInfo);
}
}
// สร้าง dynamic keywords จากสิ่งที่พบในไฟล์
generateDynamicKeywords() {
// ตรวจสอบว่า fileBlueprint มีข้อมูลหรือไม่
if (!this.fileBlueprint || !this.fileBlueprint.classes || !this.fileBlueprint.functions) {
console.log(' Warning: fileBlueprint not properly initialized, skipping keyword generation');
return;
}
try {
// สร้าง keywords จากชื่อ classes
for (const className of this.fileBlueprint.classes.keys()) {
this.addDynamicKeyword(className.toLowerCase(), `${className} class`, `คลาส ${className}`);
// เพิ่ม variations
if (className.endsWith('Manager')) {
this.addDynamicKeyword(className.toLowerCase(), `${className} manager`, `ตัวจัดการ ${className.replace('Manager', '')}`);
}
if (className.endsWith('Controller')) {
this.addDynamicKeyword(className.toLowerCase(), `${className} controller`, `ตัวควบคุม ${className.replace('Controller', '')}`);
}
if (className.endsWith('Service')) {
this.addDynamicKeyword(className.toLowerCase(), `${className} service`, `บริการ ${className.replace('Service', '')}`);
}
}
// สร้าง keywords จากชื่อ methods และ functions
const allMethods = new Set();
for (const classInfo of this.fileBlueprint.classes.values()) {
if (classInfo.methods) {
for (const methodName of classInfo.methods.keys()) {
allMethods.add(methodName);
}
}
}
for (const funcName of this.fileBlueprint.functions.keys()) {
allMethods.add(funcName);
}
// เพิ่ม method-specific keywords
for (const methodName of allMethods) {
this.addMethodSpecificKeywords(methodName);
}
} catch (error) {
console.log(' Warning: Error generating dynamic keywords:', error.message);
}
}
// เพิ่ม keywords เฉพาะสำหรับ methods
addMethodSpecificKeywords(methodName) {
const name = methodName.toLowerCase();
// CRUD operations
if (name.includes('create') || name.includes('add') || name.includes('insert')) {
this.addDynamicKeyword(name, `Create ${methodName}`, `สร้าง ${methodName}`);
}
if (name.includes('get') || name.includes('fetch') || name.includes('find') || name.includes('retrieve')) {
this.addDynamicKeyword(name, `Get ${methodName}`, `ดึง ${methodName}`);
}
if (name.includes('update') || name.includes('modify') || name.includes('edit') || name.includes('change')) {
this.addDynamicKeyword(name, `Update ${methodName}`, `อัปเดต ${methodName}`);
}
if (name.includes('delete') || name.includes('remove') || name.includes('destroy')) {
this.addDynamicKeyword(name, `Delete ${methodName}`, `ลบ ${methodName}`);
}
// Validation and processing
if (name.includes('validate') || name.includes('check') || name.includes('verify')) {
this.addDynamicKeyword(name, `Validate ${methodName}`, `ตรวจสอบ ${methodName}`);
}
if (name.includes('process') || name.includes('handle') || name.includes('execute')) {
this.addDynamicKeyword(name, `Process ${methodName}`, `ประมวลผล ${methodName}`);
}
// Specific method patterns
if (name.includes('generate') && name.includes('key')) {
this.addDynamicKeyword(name, 'Generate encryption key', 'สร้างคีย์การเข้ารหัส');
}
if (name.includes('encrypt')) {
this.addDynamicKeyword(name, 'Encrypt data', 'เข้ารหัสข้อมูล');
}
if (name.includes('decrypt')) {
this.addDynamicKeyword(name, 'Decrypt data', 'ถอดรหัสข้อมูล');
}
if (name.includes('cache') && name.includes('size')) {
this.addDynamicKeyword(name, 'Get cache size', 'ดึงขนาดแคช');
}
if (name.includes('max') && name.includes('cache')) {
this.addDynamicKeyword(name, 'Set maximum cache size', 'กำหนดขนาดแคชสูงสุด');
}
}
// กำหนดบริบทของไฟล์
determineFileContext() {
// ตรวจสอบว่า fileBlueprint มีข้อมูลหรือไม่
if (!this.fileBlueprint || !this.fileBlueprint.classes || !this.fileBlueprint.functions) {
this.fileBlueprint.context = {
type: 'unknown',
domain: 'unknown',
complexity: 'simple'
};
return;
}
const classNames = Array.from(this.fileBlueprint.classes.keys()).map(name => name.toLowerCase());
const functionNames = Array.from(this.fileBlueprint.functions.keys()).map(name => name.toLowerCase());
const allNames = [...classNames, ...functionNames];
// ตรวจสอบเนื้อหาไฟล์เพื่อจับบริบทได้แม่นยำขึ้น
const content = this.content.toLowerCase();
// ตรวจจับประเภทของไฟล์
if (content.includes('express') || content.includes('app.get') || content.includes('app.post') ||
content.includes('req, res') || allNames.some(name => name.includes('app') || name.includes('server') || name.includes('router'))) {
this.fileBlueprint.context.type = 'api';
this.fileBlueprint.context.domain = 'web';
} else if (allNames.some(name => name.includes('crypto') || name.includes('encrypt') || name.includes('hash')) ||
content.includes('bcrypt') || content.includes('jwt') || content.includes('crypto')) {
this.fileBlueprint.context.type = 'security';
this.fileBlueprint.context.domain = 'crypto';
} else if (allNames.some(name => name.includes('database') || name.includes('db') || name.includes('sql')) ||
content.includes('database') || content.includes('mongodb') || content.includes('mysql')) {
this.fileBlueprint.context.type = 'database';
this.fileBlueprint.context.domain = 'data';
} else if (allNames.some(name => name.includes('api') || name.includes('client') || name.includes('request'))) {
this.fileBlueprint.context.type = 'api';
this.fileBlueprint.context.domain = 'web';
} else if (allNames.some(name => name.includes('algorithm') || name.includes('sort') || name.includes('search'))) {
this.fileBlueprint.context.type = 'algorithm';
this.fileBlueprint.context.domain = 'computation';
} else if (allNames.some(name => name.includes('component') || name.includes('render') || name.includes('ui'))) {
this.fileBlueprint.context.type = 'ui';
this.fileBlueprint.context.domain = 'frontend';
} // ตรวจจับความซับซ้อน
const totalStructures = this.fileBlueprint.classes.size + this.fileBlueprint.functions.size;
if (totalStructures > 20) {
this.fileBlueprint.context.complexity = 'complex';
} else if (totalStructures > 10) {
this.fileBlueprint.context.complexity = 'moderate';
}
}
// Helper methods
addPattern(name, type) {
this.fileBlueprint.patterns.add(`${type}:${name.toLowerCase()}`);
}
addDynamicKeyword(key, english, thai) {
this.fileBlueprint.keywords.add(JSON.stringify({ key, english, thai }));
}
inferClassPurpose(className) {
const name = className.toLowerCase();
if (name.includes('manager')) return 'manager';
if (name.includes('controller')) return 'controller';
if (name.includes('service')) return 'service';
if (name.includes('model')) return 'model';
if (name.includes('view')) return 'view';
if (name.includes('component')) return 'component';
if (name.includes('error')) return 'error';
if (name.includes('validator')) return 'validator';
if (name.includes('parser')) return 'parser';
if (name.includes('tokenizer')) return 'tokenizer';
return 'class';
}
inferMethodPurpose(methodName, className) {
const method = methodName.toLowerCase();
const cls = className.toLowerCase();
// Context-aware purpose inference
if (cls.includes('crypto') || cls.includes('security')) {
if (method.includes('generate')) return 'generate_crypto';
if (method.includes('encrypt')) return 'encrypt_data';
if (method.includes('decrypt')) return 'decrypt_data';
}
if (cls.includes('cache') || cls.includes('memory')) {
if (method.includes('size')) return 'get_size';
if (method.includes('clear')) return 'clear_cache';
if (method.includes('max')) return 'set_limit';
}
// General purpose inference
if (method.includes('get') || method.includes('fetch')) return 'getter';
if (method.includes('set') || method.includes('assign')) return 'setter';
if (method.includes('create') || method.includes('add')) return 'creator';
if (method.includes('delete') || method.includes('remove')) return 'destroyer';
if (method.includes('update') || method.includes('modify')) return 'updater';
if (method.includes('validate') || method.includes('check')) return 'validator';
if (method.includes('process') || method.includes('handle')) return 'processor';
return 'method';
}
inferFunctionPurpose(functionName) {
const name = functionName.toLowerCase();
if (name.includes('demo') || name.includes('test') || name.includes('example')) return 'demo';
if (name.includes('init') || name.includes('setup')) return 'initializer';
if (name.includes('main') || name.includes('run')) return 'main';
if (name.includes('helper') || name.includes('util')) return 'utility';
return 'function';
}
inferAccessibility(methodName) {
if (methodName.startsWith('_')) return 'private';
if (methodName.startsWith('#')) return 'private';
return 'public';
}
calculateClassComplexity(classStructure) {
const methodCount = classStructure.methods ? classStructure.methods.length : 0;
if (methodCount > 15) return 'high';
if (methodCount > 8) return 'medium';
return 'low';
}
calculateFunctionComplexity(funcStructure) {
const paramCount = funcStructure.parameters ? funcStructure.parameters.length : 0;
if (paramCount > 5) return 'high';
if (paramCount > 2) return 'medium';
return 'low';
}
findClassRelationships(className, classInfo) {
// Implementation for finding class relationships
// This would analyze inheritance, composition, etc.
}
detectDesignPatterns(className, classInfo) {
// Implementation for detecting design patterns
// Singleton, Factory, Observer, etc.
}
findFunctionRelationships(funcName, funcInfo) {
// Implementation for finding function relationships
// Helper functions, utility functions, etc.
}
// ===================================================================
// TypeScript Helper Methods/เมธอดช่วยเหลือสำหรับ TypeScript
// ===================================================================
// แยกคุณสมบัติของ interface
extractInterfaceProperties(startIndex) {
const properties = [];
const startPos = this.content.indexOf('{', startIndex);
const endPos = this.findMatchingBrace(startPos);
if (startPos === -1 || endPos === -1) return properties;
const interfaceBody = this.content.substring(startPos + 1, endPos);
const lines = interfaceBody.split('\n');
lines.forEach(line => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*')) {
const propertyMatch = trimmed.match(/(\w+)(\?)?:\s*([^;]+);?/);
if (propertyMatch) {
properties.push({
name: propertyMatch[1],
optional: !!propertyMatch[2],
type: propertyMatch[3].trim()
});
}
}
});
return properties;
}
// แยกค่าของ enum
extractEnumValues(enumBody) {
const values = [];
const lines = enumBody.split('\n');
lines.forEach(line => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('//')) {
const valueMatch = trimmed.match(/(\w+)(?:\s*=\s*([^,]+))?/);
if (valueMatch) {
values.push({
name: valueMatch[1],
value: valueMatch[2] ? valueMatch[2].trim() : null
});
}
}
});
return values;
}
// หา matching brace
findMatchingBrace(startPos) {
let depth = 1;
let pos = startPos + 1;
while (pos < this.content.length && depth > 0) {
const char = this.content[pos];
if (char === '{') depth++;
else if (char === '}') depth--;
pos++;
}
return depth === 0 ? pos - 1 : -1;
}
// อนุมานวัตถุประสงค์ของ interface
inferInterfacePurpose(interfaceName) {
const name = interfaceName.toLowerCase();
if (name.includes('config') || name.includes('options')) return 'configuration';
if (name.includes('result') || name.includes('response')) return 'result_type';
if (name.includes('request') || name.includes('params')) return 'input_type';
if (name.includes('error') || name.includes('exception')) return 'error_type';
if (name.includes('event') || name.includes('listener')) return 'event_type';
if (name.includes('data') || name.includes('model')) return 'data_type';
if (name.includes('service') || name.includes('client')) return 'service_interface';
if (name.includes('repository') || name.includes('dao')) return 'repository_interface';
return 'interface';
}
// อนุมานวัตถุประสงค์ของ type alias
inferTypePurpose(typeName, typeDefinition) {
const name = typeName.toLowerCase();
const definition = typeDefinition.toLowerCase();
if (name.includes('listener') || name.includes('callback') || name.includes('handler')) return 'callback_type';
if (name.includes('rule') || name.includes('schema') || name.includes('validation')) return 'validation_type';
if (name.includes('strategy') || name.includes('policy')) return 'strategy_type';
if (definition.includes('string') && definition.includes('|')) return 'string_union';
if (definition.includes('number') && definition.includes('|')) return 'number_union';
if (definition.includes('=>')) return 'function_type';
if (definition.includes('{') && definition.includes('}')) return 'object_type';
return 'type_alias';
}
// อนุมานวัตถุประสงค์ของ enum
inferEnumPurpose(enumName) {
const name = enumName.toLowerCase();
if (name.includes('status') || name.includes('state')) return 'status_enum';
if (name.includes('type') || name.includes('kind')) return 'type_enum';
if (name.includes('level') || name.includes('priority')) return 'level_enum';
if (name.includes('direction') || name.includes('order')) return 'direction_enum';
if (name.includes('mode') || name.includes('strategy')) return 'mode_enum';
return 'enumeration';
}
// อนุมานวัตถุประสงค์ของ abstract class
inferAbstractClassPurpose(className) {
const name = className.toLowerCase();
if (name.includes('base') || name.includes('abstract')) return 'base_class';
if (name.includes('repository') || name.includes('dao')) return 'repository_base';
if (name.includes('service') || name.includes('provider')) return 'service_base';
if (name.includes('controller') || name.includes('handler')) return 'controller_base';
if (name.includes('component') || name.includes('widget')) return 'component_base';
return 'abstract_class';
}
// ===================================================================
// AI Intent Understanding Engine - เครื่องมืออัจฉริยะเข้าใจความตั้งใจของโค้ด
// ===================================================================
// วิเคราะห์ความตั้งใจและความหมายของโค้ด
// Analyze intent and semantic meaning of code
// Evolution: From "Grammar Expert" to "Literary Critic"
analyzeCodeIntent() {
try {
console.log('\n AI Intent Understanding Engine: เริ่มการวิเคราะห์ความตั้งใจของโค้ด...');
// สร้าง Intent Map
const intentMap = {
businessLogic: new Map(),
dataFlow: new Map(),
errorHandling: new Map(),
performanceOptimization: new Map(),
securityMeasures: new Map(),
userInteraction: new Map(),
systemIntegration: new Map(),
algorithmicPurpose: new Map()
};
// วิเคราะห์แต่ละ class และ function
this.analyzeClassesIntent(intentMap);
this.analyzeFunctionsIntent(intentMap);
this.analyzeDataFlowIntent(intentMap);
this.analyzeLogicalPatterns(intentMap);
// สร้าง Smart Comments จาก Intent Analysis
this.generateIntentBasedComments(intentMap);
console.log(' AI Intent Analysis เสร็จสมบูรณ์');
return intentMap;
} catch (error) {
console.error(' AI Intent Analysis ล้มเหลว:', error.message);
return null;
}
}
// วิเคราะห์ความตั้งใจของ Classes
analyzeClassesIntent(intentMap) {
this.fileBlueprint.classes.forEach((classInfo, className) => {
// Pattern Analysis: Business Logic Intent
const businessIntent = this.inferBusinessIntent(className, classInfo);
if (businessIntent) {
intentMap.businessLogic.set(className, businessIntent);
}
// Pattern Analysis: Architecture Intent
const architectureRole = this.inferArchitectureRole(className, classInfo);
if (architectureRole) {
intentMap.systemIntegration.set(className, architectureRole);
}
// Pattern Analysis: Security Intent
const securityRole = this.inferSecurityRole(className, classInfo);
if (securityRole) {
intentMap.securityMeasures.set(className, securityRole);
}
});
}
// วิเคราะห์ความตั้งใจของ Functions
analyzeFunctionsIntent(intentMap) {
this.fileBlueprint.functions.forEach((funcInfo, funcName) => {
// Algorithmic Purpose Analysis
const algorithmIntent = this.inferAlgorithmicIntent(funcName, funcInfo);
if (algorithmIntent) {
intentMap.algorithmicPurpose.set(funcName, algorithmIntent);
}
// Performance Intent Analysis
const performanceIntent = this.inferPerformanceIntent(funcName, funcInfo);
if (performanceIntent) {
intentMap.performanceOptimization.set(funcName, performanceIntent);
}
// Error Handling Intent
const errorHandlingIntent = this.inferErrorHandlingIntent(funcName, funcInfo);
if (errorHandlingIntent) {
intentMap.errorHandling.set(funcName, errorHandlingIntent);
}
});
}
// วิเคราะห์การไหลของข้อมูล และความสัมพันธ์
analyzeDataFlowIntent(intentMap) {
// Analyze variable assignments and data transformations
const dataFlowPatterns = this.extractDataFlowPatterns();
dataFlowPatterns.forEach((pattern, operation) => {
const intent = this.inferDataFlowIntent(operation, pattern);
if (intent) {
intentMap.dataFlow.set(operation, intent);
}
});
}
// วิเคราะห์รูปแบบทางตรรกะและการตัดสินใจ
analyzeLogicalPatterns(intentMap) {
// Look for conditional logic patterns
const conditionalPatterns = this.extractConditionalPatterns();
conditionalPatterns.forEach((pattern, condition) => {
const logicalIntent = this.inferLogicalIntent(condition, pattern);
if (logicalIntent) {
intentMap.businessLogic.set(`logic_${condition}`, logicalIntent);
}
});
}
// อนุมานความตั้งใจทางธุรกิจของ Class
inferBusinessIntent(className, classInfo) {
const name = className.toLowerCase();
const methods = Array.isArray(classInfo.methods) ? classInfo.methods : [];
// E-commerce Patterns
if (name.includes('order') || name.includes('cart') || name.includes('payment')) {
return {
domain: 'e-commerce',
purpose: 'การจัดการการซื้อขายและการชำระเงิน',
businessValue: 'สร้างรายได้และจัดการธุรกรรม',
userImpact: 'ช่วยให้ผู้ใช้สามารถซื้อสินค้าได้อย่างปลอดภัย'
};
}
// User Management Patterns
if (name.includes('user') || name.includes('auth') || name.includes('account')) {
return {
domain: 'user-management',
purpose: 'การจัดการผู้ใช้และการรับรองตัวตน',
businessValue: 'สร้างและรักษาฐานผู้ใช้',
userImpact: 'ให้ผู้ใช้เข้าถึงระบบได้อย่างปลอดภัย'
};
}
// Data Processing Patterns
if (name.includes('processor') || name.includes('analyzer') || name.includes('parser')) {
return {
domain: 'data-processing',
purpose: 'การประมวลผลและวิเคราะห์ข้อมูล',
businessValue: 'เปลี่ยนข้อมูลดิบให้เป็นข้อมูลที่มีค่า',
userImpact: 'ได้รับข้อมูลที่ถูกต้องและมีประโยชน์'
};
}
return null;
} // อนุมานบทบาททางสถาปัตยกรรม
inferArchitectureRole(className, classInfo) {
const name = className.toLowerCase();
// MVC Pattern Detection
if (name.includes('controller')) {
return {
pattern: 'MVC',
role: 'Controller',
responsibility: 'จัดการ Request และ Response',
coupling: 'กลาง - เชื่อมต่อ Model และ View'
};
}
if (name.includes('model') || name.includes('entity')) {
return {
pattern: 'MVC',
role: 'Model',
responsibility: 'จัดการข้อมูลและ Business Logic',
coupling: 'ต่ำ - ไม่ขึ้นกับ UI'
};
}
// Repository Pattern Detection
if (name.includes('repository') || name.includes('dao')) {
return {
pattern: 'Repository',
role: 'Data Access',
responsibility: 'แยก Business Logic จาก Data Access',
coupling: 'ต่ำ - เฉพาะ Data Layer'
};
}
return null;
}
// อนุมานบทบาทด้านความปลอดภัย
inferSecurityRole(className, classInfo) {
const name = className.toLowerCase();
const methods = Array.isArray(classInfo.methods) ? classInfo.methods : [];
if (name.includes('security') || name.includes('crypto') || name.includes('auth')) {
const hasEncryption = methods.some(m => (typeof m === 'string' ? m : '').includes('encrypt') || (typeof m === 'string' ? m : '').includes('decrypt'));
const hasValidation = methods.some(m => (typeof m === 'string' ? m : '').includes('validate') || (typeof m === 'string' ? m : '').includes('verify'));
return {
level: hasEncryption ? 'high' : 'medium',
measures: {
encryption: hasEncryption,
validation: hasValidation,
authentication: name.includes('auth')
},
threat_protection: 'ป้องกันการเข้าถึงที่ไม่ได้รับอนุญาต'
};
}
return null;
} // อนุมานความตั้งใจของ Algorithm
inferAlgorithmicIntent(funcName, funcInfo) {
const name = funcName.toLowerCase();
const params = funcInfo.parameters || [];
// Sorting Algorithm Detection
if (name.includes('sort')) {
return {
type: 'sorting',
purpose: 'จัดเรียงข้อมูลตามเกณฑ์ที่กำหนด',
complexity: params.length > 2 ? 'complex' : 'simple',
optimization: 'เพื่อการค้นหาและประมวลผลที่รวดเร็ว'
};
}
// Search Algorithm Detection
if (name.includes('search') || name.includes('find')) {
return {
type: 'searching',
purpose: 'ค้นหาข้อมูลตามเงื่อนไขที่กำหนด',
strategy: name.includes('binary') ? 'binary_search' : 'linear_search',
optimization: 'ลดเวลาในการค้นหาข้อมูล'
};
}
// Validation Algorithm Detection
if (name.includes('validate') || name.includes('check')) {
return {
type: 'validation',
purpose: 'ตรวจสอบความถูกต้องของข้อมูล',
scope: 'data_integrity',
importance: 'critical'
};
}
return null;
}
// อนุมานความตั้งใจด้าน Performance
inferPerformanceIntent(funcName, funcInfo) {
const name = funcName.toLowerCase();
if (name.includes('cache') || name.includes('memoize')) {
return {
strategy: 'caching',
goal: 'ลดการคำนวณซ้ำ',
impact: 'เพิ่มความเร็วในการตอบสนอง'
};
}
if (name.includes('async') || name.includes('promise')) {
return {
strategy: 'asynchronous',
goal: 'ป้องกันการบล็อกการทำงาน',
impact: 'ทำงานหลายอย่างพร้อมกันได้'
};
}
if (name.includes('optimize') || name.includes('efficient')) {
return {
strategy: 'optimization',
goal: 'ลดการใช้ทรัพยากร',
impact: 'ประหยัดหน่วยความจำและพลังงาน'
};
}
return null;
}
// อนุมานความตั้งใจด้าน Error Handling
inferErrorHandlingIntent(funcName, funcInfo) {
const name = funcName.toLowerCase();
if (name.includes('try') || name.includes('catch') || name.includes('handle')) {
return {
approach: 'defensive_programming',
goal: 'ป้องกันการ crash ของระบบ',
user_experience: 'ให้ข้อความ error ที่เข้าใจง่าย'
};
}
if (name.includes('retry') || name.includes('fallback')) {
return {
approach: 'resilience',
goal: 'ทำให้ระบบทำงานต่อได้แม้เกิดปัญหา',
reliability: 'สูง'
};
}
return null;
}
// สกัดรูปแบบการไหลของข้อมูล
extractDataFlowPatterns() {
const patterns = new Map();
const lines = this.content.split('\n');
lines.forEach((line, index) => {
const trimmed = line.trim();
// Assignment patterns
if (trimmed.includes('=') && !trimmed.includes('==') && !trimmed.includes('!=')) {
const assignment = trimmed.match(/(\w+)\s*=\s*(.+)/);
if (assignment) {
patterns.set(`assignment_${index}`, {
variable: assignment[1],
value: assignment[2],
line: index + 1,
intent: 'data_transformation'
});
}
}
// Function calls that transform data
if (trimmed.includes('.map(') || trimmed.includes('.filter(') ||
trimmed.includes('.reduce(') || trimmed.includes('.transform(')) {
patterns.set(`transformation_${index}`, {
type: 'data_transformation',
line: index + 1,
intent: 'data_processing'
});
}
});
return patterns;
}
// สกัดรูปแบบเงื่อนไข
extractConditionalPatterns() {
const patterns = new Map();
const lines = this.content.split('\n');
lines.forEach((line, index) => {
const trimmed = line.trim();
// If statements
if (trimmed.startsWith('if ') || trimmed.includes('if(')) {
patterns.set(`condition_${index}`, {
type: 'conditional_logic',
line: index + 1,
condition: trimmed,
intent: 'decision_making'
});
}
// Switch statements
if (trimmed.startsWith('switch ') || trimmed.includes('switch(')) {
patterns.set(`switch_${index}`, {
type: 'multiple_choice',
line: index + 1,
intent: 'route_selection'
});
}
});
return patterns;
}
// อนุมานความตั้งใจของการไหลข้อมูล
inferDataFlowIntent(operation, pattern) {
if (pattern.intent === 'data_transformation') {
return {
purpose: 'เปลี่ยนรูปแบบข้อมูลให้เหมาะกับการใช้งาน',
impact: 'ทำให้ข้อมูลใช้งานได้ง่ายขึ้น',
type: 'transformation'
};
}
if (pattern.intent === 'data_processing') {
return {
purpose: 'ประมวลผลข้อมูลเพื่อหาผลลัพธ์ที่ต้องการ',
impact: 'ได้ข้อมูลใหม่ที่มีค่ามากขึ้น',
type: 'processing'
};
}
return null;
}
// อนุมานความตั้งใจทางตรรกะ
inferLogicalIntent(condition, pattern) {
if (pattern.intent === 'decision_making') {
return {
purpose: 'ตัดสินใจเลือกเส้นทางการทำงาน',
impact: 'ควบคุมการไหลของโปรแกรม',
complexity: 'medium'
};
}
if (pattern.intent === 'route_selection') {
return {
purpose: 'เลือกการดำเนินการตามสถานการณ์',
impact: 'จัดการกรณีต่างๆ ได้อย่างเป็นระบบ',
complexity: 'high'
};
}
return null;
}
// สร้าง Smart Comments จาก Intent Analysis
generateIntentBasedComments(intentMap) {
console.log('\n กำลังสร้าง Smart Comments จาก AI Intent Analysis...');
// สร้าง comment สำหรับ business logic
intentMap.businessLogic.forEach((intent, item) => {
if (intent.purpose && intent.businessValue) {
const smartComment = this.createSmartComment(item, intent, 'business');
this.addSmartCommentToBlueprint(item, smartComment);
}
});
// สร้าง comment สำหรับ algorithmic purpose
intentMap.algorithmicPurpose.forEach((intent, item) => {
if (intent.purpose && intent.optimization) {
const smartComment = this.createSmartComment(item, intent, 'algorithm');
this.addSmartCommentToBlueprint(item, smartComment);
}
});
// สร้าง comment สำหรับ security measures
intentMap.securityMeasures.forEach((intent, item) => {
if (intent.threat_protection) {
const smartComment = this.createSmartComment(item, intent, 'security');
this.addSmartCommentToBlueprint(item, smartComment);
}
});
console.log(' Smart Comments สร้างเสร็จแล้ว');
}
// สร้าง Smart Comment จาก Intent
createSmartComment(item, intent, category) {
switch (category) {
case 'business':
return {
thai: `// ${intent.purpose} - ${intent.businessValue}`,
english: `// ${intent.purpose} - Creates business value through ${intent.businessValue}`,
impact: intent.userImpact
};
case 'algorithm':
return {
thai: `// ${intent.purpose} - เพื่อ${intent.optimization}`,
english: `// ${intent.purpose} - Optimized for ${intent.optimization}`,
complexity: intent.complexity
};
case 'security':
return {
thai: `// ${intent.threat_protection} - ระดับความปลอดภัย: ${intent.level}`,
english: `// ${intent.threat_protection} - Security level: ${intent.level}`,
measures: intent.measures
};
default:
return {
thai: `// วัตถุประสงค์: ${intent.purpose || 'ไม่ระบุ'}`,
english: `// Purpose: ${intent.purpose || 'Not specified'}`
};
}
}
// เพิ่ม Smart Comment ไปยัง Blueprint
addSmartCommentToBlueprint(item, smartComment) {
if (!this.fileBlueprint.smartComments) {
this.fileBlueprint.smartComments = new Map();
}
this.fileBlueprint.smartComments.set(item, smartComment);
}
// ดึงข้อมูล Intent Analysis ทั้งหมด
getIntentAnalysisReport() {
const intentAnalysis = this.analyzeCodeIntent();
if (!intentAnalysis) {
return null;
}
return {
summary: {
totalBusinessLogic: intentAnalysis.businessLogic ? intentAnalysis.businessLogic.size : 0,
totalAlgorithms: intentAnalysis.algorithmicPurpose ? intentAnalysis.algorithmicPurpose.size : 0,
totalSecurityMeasures: intentAnalysis.securityMeasures ? intentAnalysis.securityMeasures.size : 0,
totalDataFlows: intentAnalysis.dataFlow ? intentAnalysis.dataFlow.size : 0
},
details: {
businessLogic: intentAnalysis.businessLogic ? Array.from(intentAnalysis.businessLogic.entries()) : [],
algorithms: intentAnalysis.algorithmicPurpose ? Array.from(intentAnalysis.algorithmicPurpose.entries()) : [],
security: intentAnalysis.securityMeasures ? Array.from(intentAnalysis.securityMeasures.entries()) : [],
dataFlow: intentAnalysis.dataFlow ? Array.from(intentAnalysis.dataFlow.entries()) : []
},
smartComments: this.fileBlueprint && this.fileBlueprint.smartComments ?
Array.from(this.fileBlueprint.smartComments.entries()) : []
};
}
}
// Structure Analyzer:ตัววิเคราะห์โครงสร้างโค้ด
// ======================================================================
// EN: StructureAnalyzer analyzer
// TH: ตัววิเคราะห์ StructureAnalyzer
// ======================================================================
class StructureAnalyzer {
constructor(tokens, content) {
this.tokens = tokens.filter(t => t.type !== TOKEN_TYPES.WHITESPACE);
this.content = content;
this.lines = content.split('\n');
this.structures = [];
}
// วิเคราะห์โครงสร้างทั้งหมด - Analyze all structures
// ======================================================================
// EN: analyzeAll class
// TH: คลาส analyzeAll
// ======================================================================
analyzeAll() {
let cursor = 0;
while (cursor < this.tokens.length) {
const structure = this.analyzeStructureAt(cursor);
if (structure) {
this.structures.push(structure);
cursor = structure.endTokenIndex || cursor + 1;
} else {
cursor++;
}
}
return this.structures;
}
// วิเคราะห์โครงสร้างที่ตำแหน่งเฉพาะ - Analyze structure at specific position
analyzeStructureAt(startCursor) {
const token = this.tokens[startCursor];
if (!token) return null;
// วิเคราะห์ interface (TypeScript)
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'interface') {
return this.analyzeInterface(startCursor);
}
// วิเคราะห์ type alias (TypeScript)
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'type') {
return this.analyzeTypeAlias(startCursor);
}
// วิเคราะห์ class
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'class') {
return this.analyzeClass(startCursor);
}
// วิเคราะห์ abstract class
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'abstract') {
const nextToken = this.tokens[startCursor + 1];
if (nextToken && nextToken.value === 'class') {
return this.analyzeAbstractClass(startCursor);
}
}
// วิเคราะห์ const/let/var (objects และ arrow functions)
if (token.type === TOKEN_TYPES.KEYWORD &&
['const', 'let', 'var'].includes(token.value)) {
const result = this.analyzeVariableDeclaration(startCursor);
if (result) return result;
}
// วิเคราะห์ function
if (token.type === TOKEN_TYPES.KEYWORD && token.value === 'function') {
return this.analyzeFunction(startCursor);
}
return null;
}
// วิเคราะห์คลาส - Analyze class structure
analyzeClass(startCursor) {
const classToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER) {
return null;
}
// หาขอบเขตของคลาส
const classBounds = this.findBlockBounds(startCursor + 2, TOKEN_TYPES.BRACE_OPEN);
if (!classBounds) return null;
// วิเคราะห์สมาชิกของคลาส
const members = this.analyzeClassMembers(classBounds.startIndex, classBounds.endIndex);
// อ่านเนื้อหาคลาสเพื่อเข้าใจความหมาย
const classContent = this.extractContentBetweenLines(classToken.line, classBounds.endLine);
const purpose = this.inferClassPurpose(nameToken.value, classContent, members);
return {
type: 'class',
name: nameToken.value,
line: classToken.line,
column: classToken.column,
startTokenIndex: startCursor,
endTokenIndex: classBounds.endTokenIndex,
endLine: classBounds.endLine,
members: members,
purpose: purpose,
content: classContent
};
}
// วิเคราะห์การประกาศตัวแปร (object และ arrow function) - Analyze variable declaration
analyzeVariableDeclaration(startCursor) {
const keywordToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
const equalsToken = this.tokens[startCursor + 2];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER ||
!equalsToken || equalsToken.type !== TOKEN_TYPES.EQUALS) {
return null;
}
// ตรวจสอบว่าเป็น arrow function หรือไม่
const arrowFuncResult = this.analyzeArrowFunction(startCursor);
if (arrowFuncResult) return arrowFuncResult;
// ตรวจสอบว่าเป็น object หรือไม่
const braceToken = this.tokens[startCursor + 3];
if (braceToken && braceToken.type === TOKEN_TYPES.BRACE_OPEN) {
return this.analyzeObjectDeclaration(startCursor);
}
return null;
}
// วิเคราะห์ arrow function - Analyze arrow function
analyzeArrowFunction(startCursor) {
const keywordToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
const equalsToken = this.tokens[startCursor + 2];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER ||
!equalsToken || equalsToken.type !== TOKEN_TYPES.EQUALS) {
return null;
}
// หา arrow operator (=>)
let arrowIndex = -1;
for (let i = startCursor + 3; i < startCursor + 15 && i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.ARROW) {
arrowIndex = i;
break;
}
}
if (arrowIndex === -1) return null;
// หาพารามิเตอร์
const params = this.extractArrowFunctionParameters(startCursor + 3, arrowIndex);
// หาขอบเขตของฟังก์ชัน
const functionBounds = this.findArrowFunctionBounds(arrowIndex);
if (!functionBounds) return null;
const functionContent = this.extractContentBetweenLines(keywordToken.line, functionBounds.endLine);
const purpose = {
english: `Arrow function: ${nameToken.value}`,
thai: `ฟังก์ชันแบบ arrow: ${nameToken.value}`
};
return {
type: 'arrow_function',
name: nameToken.value,
line: keywordToken.line,
column: keywordToken.column,
startTokenIndex: startCursor,
endTokenIndex: functionBounds.endTokenIndex,
endLine: functionBounds.endLine,
parameters: params,
purpose: purpose,
content: functionContent
};
}
// วิเคราะห์การประกาศ object - Analyze object declaration
analyzeObjectDeclaration(startCursor) {
const keywordToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
const equalsToken = this.tokens[startCursor + 2];
const braceToken = this.tokens[startCursor + 3];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER ||
!equalsToken || equalsToken.type !== TOKEN_TYPES.EQUALS ||
!braceToken || braceToken.type !== TOKEN_TYPES.BRACE_OPEN) {
return null;
}
// หาขอบเขตของ object
const objectBounds = this.findBlockBounds(startCursor + 3, TOKEN_TYPES.BRACE_OPEN);
if (!objectBounds) return null;
// วิเคราะห์คุณสมบัติของ object
const properties = this.analyzeObjectProperties(objectBounds.startIndex, objectBounds.endIndex);
// อ่านเนื้อหา object เพื่อเข้าใจความหมาย
const objectContent = this.extractContentBetweenLines(keywordToken.line, objectBounds.endLine);
const purpose = this.inferObjectPurpose(nameToken.value, objectContent, properties);
return {
type: 'object',
name: nameToken.value,
line: keywordToken.line,
column: keywordToken.column,
startTokenIndex: startCursor,
endTokenIndex: objectBounds.endTokenIndex,
endLine: objectBounds.endLine,
properties: properties,
purpose: purpose,
content: objectContent
};
}
// วิเคราะห์ interface (TypeScript) - Analyze interface structure
analyzeInterface(startCursor) {
const interfaceToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER) {
return null;
}
// หาขอบเขตของ interface
const interfaceBounds = this.findBlockBounds(startCursor, TOKEN_TYPES.BRACE_OPEN);
if (!interfaceBounds) return null;
const interfaceContent = this.extractContentBetweenLines(interfaceToken.line, interfaceBounds.endLine);
const purpose = {
english: `Interface definition for ${nameToken.value}`,
thai: `การกำหนด interface สำหรับ ${nameToken.value}`
};
return {
type: 'interface_declaration',
name: nameToken.value,
line: interfaceToken.line,
column: interfaceToken.column,
startTokenIndex: startCursor,
endTokenIndex: interfaceBounds.endTokenIndex,
endLine: interfaceBounds.endLine,
purpose: purpose,
content: interfaceContent
};
}
// วิเคราะห์ type alias (TypeScript) - Analyze type alias structure
analyzeTypeAlias(startCursor) {
const typeToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
const equalsToken = this.tokens[startCursor + 2];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER ||
!equalsToken || equalsToken.type !== TOKEN_TYPES.EQUALS) {
return null;
}
// หาจุดสิ้นสุดของ type alias (อาจเป็น ; หรือ \n)
let endTokenIndex = startCursor + 3;
while (endTokenIndex < this.tokens.length) {
const token = this.tokens[endTokenIndex];
if (token.type === TOKEN_TYPES.SEMICOLON ||
token.type === TOKEN_TYPES.NEWLINE ||
token.type === TOKEN_TYPES.EOF) {
break;
}
endTokenIndex++;
}
const endLine = this.tokens[endTokenIndex]?.line || typeToken.line;
const typeContent = this.extractContentBetweenLines(typeToken.line, endLine);
const purpose = {
english: `Type alias definition for ${nameToken.value}`,
thai: `การกำหนด type alias สำหรับ ${nameToken.value}`
};
return {
type: 'type_alias',
name: nameToken.value,
line: typeToken.line,
column: typeToken.column,
startTokenIndex: startCursor,
endTokenIndex: endTokenIndex,
endLine: endLine,
purpose: purpose,
content: typeContent
};
}
// วิเคราะห์ abstract class - Analyze abstract class structure
analyzeAbstractClass(startCursor) {
const abstractToken = this.tokens[startCursor];
const classToken = this.tokens[startCursor + 1];
const nameToken = this.tokens[startCursor + 2];
if (!classToken || classToken.value !== 'class' ||
!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER) {
return null;
}
// หาขอบเขตของคลาส
const classBounds = this.findBlockBounds(startCursor, TOKEN_TYPES.BRACE_OPEN);
if (!classBounds) return null;
const classContent = this.extractContentBetweenLines(abstractToken.line, classBounds.endLine);
const purpose = {
english: `Abstract class: ${nameToken.value}`,
thai: `คลาสนามธรรม: ${nameToken.value}`
};
return {
type: 'abstract_class',
name: nameToken.value,
line: abstractToken.line,
column: abstractToken.column,
startTokenIndex: startCursor,
endTokenIndex: classBounds.endTokenIndex,
endLine: classBounds.endLine,
purpose: purpose,
content: classContent
};
}
// วิเคราะห์ฟังก์ชัน - Analyze function structure
analyzeFunction(startCursor) {
const functionToken = this.tokens[startCursor];
const nameToken = this.tokens[startCursor + 1];
if (!nameToken || nameToken.type !== TOKEN_TYPES.IDENTIFIER) {
return null;
}
// หาพารามิเตอร์
const params = this.extractFunctionParameters(startCursor + 2);
// หาขอบเขตของฟังก์ชัน
const functionBounds = this.findFunctionBounds(startCursor);
if (!functionBounds) return null;
// อ่านเนื้อหาฟังก์ชันเพื่อเข้าใจความหมาย
const functionContent = this.extractContentBetweenLines(functionToken.line, functionBounds.endLine);
const purpose = this.inferFunctionPurpose(nameToken.value, functionContent, params);
return {
type: 'function',
name: nameToken.value,
line: functionToken.line,
column: functionToken.column,
startTokenIndex: startCursor,
endTokenIndex: functionBounds.endTokenIndex,
endLine: functionBounds.endLine,
parameters: params,
purpose: purpose,
content: functionContent
};
}
// หาขอบเขตของบล็อค - Find block bounds
findBlockBounds(startCursor, openType) {
let depth = 0;
let startIndex = -1;
let endIndex = -1;
let endTokenIndex = -1;
for (let i = startCursor; i < this.tokens.length; i++) {
const token = this.tokens[i];
if (token.type === openType) {
if (depth === 0) {
startIndex = i;
}
depth++;
} else if (token.type === TOKEN_TYPES.BRACE_CLOSE) {
depth--;
if (depth === 0) {
endIndex = i;
endTokenIndex = i;
break;
}
}
}
if (startIndex === -1 || endIndex === -1) {
return null;
}
return {
startIndex,
endIndex,
endTokenIndex,
endLine: this.tokens[endIndex]?.line || 0
};
}
// หาขอบเขตของฟังก์ชัน - Find function bounds
findFunctionBounds(startCursor) {
// หา { แรกหลังจาก )
let braceStart = -1;
let parenDepth = 0;
for (let i = startCursor; i < this.tokens.length; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
parenDepth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
parenDepth--;
} else if (token.type === TOKEN_TYPES.BRACE_OPEN && parenDepth === 0) {
braceStart = i;
break;
}
}
if (braceStart === -1) return null;
return this.findBlockBounds(braceStart, TOKEN_TYPES.BRACE_OPEN);
}
// หาขอบเขตของ arrow function - Find arrow function bounds
findArrowFunctionBounds(arrowIndex) {
// หาเนื้อหาหลัง =>
// อาจเป็น { ... } หรือ expression
let startIndex = arrowIndex + 1;
if (startIndex < this.tokens.length) {
const nextToken = this.tokens[startIndex];
if (nextToken.type === TOKEN_TYPES.BRACE_OPEN) {
// Block arrow function: () => { ... }
return this.findBlockBounds(startIndex, TOKEN_TYPES.BRACE_OPEN);
} else {
// Expression arrow function: () => expression
// หาจุดสิ้นสุด (;, ,, ), } หรือ \n)
let endIndex = startIndex;
let parenDepth = 0;
let braceDepth = 0;
while (endIndex < this.tokens.length) {
const token = this.tokens[endIndex];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
parenDepth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
parenDepth--;
if (parenDepth < 0) break;
} else if (token.type === TOKEN_TYPES.BRACE_OPEN) {
braceDepth++;
} else if (token.type === TOKEN_TYPES.BRACE_CLOSE) {
braceDepth--;
if (braceDepth < 0) break;
} else if ((token.type === TOKEN_TYPES.SEMICOLON ||
token.type === TOKEN_TYPES.COMMA ||
token.type === TOKEN_TYPES.NEWLINE) &&
parenDepth === 0 && braceDepth === 0) {
break;
}
endIndex++;
}
return {
startIndex: arrowIndex + 1,
endIndex: endIndex - 1,
endTokenIndex: endIndex - 1,
endLine: this.tokens[endIndex - 1]?.line || this.tokens[arrowIndex]?.line
};
}
}
return null;
}
// แยกพารามิเตอร์ของ arrow function - Extract arrow function parameters
extractArrowFunctionParameters(startIndex, arrowIndex) {
const params = [];
// หาพารามิเตอร์ระหว่าง startIndex และ arrowIndex
let currentParam = '';
let parenDepth = 0;
for (let i = startIndex; i < arrowIndex; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
if (parenDepth === 0) {
// เริ่ม parameter list
parenDepth++;
continue;
}
parenDepth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
parenDepth--;
if (parenDepth === 0) {
// จบ parameter list
if (currentParam.trim()) {
params.push(currentParam.trim());
currentParam = '';
}
break;
}
} else if (token.type === TOKEN_TYPES.COMMA && parenDepth === 1) {
if (currentParam.trim()) {
params.push(currentParam.trim());
currentParam = '';
}
continue;
}
if (parenDepth > 0 || (parenDepth === 0 && token.type === TOKEN_TYPES.IDENTIFIER)) {
currentParam += token.value;
}
}
// กรณี single parameter without parentheses: param => ...
if (params.length === 0 && currentParam.trim()) {
params.push(currentParam.trim());
}
return params;
}
// วิเคราะห์สมาชิกของคลาส - Analyze class members
analyzeClassMembers(startIndex, endIndex) {
const members = [];
// Implementation for analyzing class methods and properties
// This would parse constructor, methods, properties, etc.
return members;
}
// วิเคราะห์คุณสมบัติของ object - Analyze object properties
// ======================================================================
// EN: analyzeObjectProperties class
// TH: คลาส analyzeObjectProperties
// ======================================================================
analyzeObjectProperties(startIndex, endIndex) {
const properties = [];
for (let i = startIndex + 1; i < endIndex; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.IDENTIFIER) {
const nextToken = this.tokens[i + 1];
if (nextToken && nextToken.value === ':') {
// พบคุณสมบัติ
const valueToken = this.tokens[i + 2];
properties.push({
name: token.value,
line: token.line,
value: valueToken?.value || '',
type: this.inferPropertyType(valueToken)
});
}
}
}
return properties;
}
// แยกพารามิเตอร์ของฟังก์ชัน - Extract function parameters
extractFunctionParameters(startCursor) {
const params = [];
let depth = 0;
for (let i = startCursor; i < this.tokens.length; i++) {
const token = this.tokens[i];
if (token.type === TOKEN_TYPES.PAREN_OPEN) {
depth++;
} else if (token.type === TOKEN_TYPES.PAREN_CLOSE) {
depth--;
if (depth === 0) break;
} else if (token.type === TOKEN_TYPES.IDENTIFIER && depth === 1) {
params.push(token.value);
}
}
return params;
}
// แยกเนื้อหาระหว่างบรรทัด - Extract content between lines
extractContentBetweenLines(startLine, endLine) {
const lines = [];
for (let i = startLine - 1; i < endLine && i < this.lines.length; i++) {
lines.push(this.lines[i]);
}
return lines.join('\n');
}
// อนุมานจุดประสงค์ของคลาส - Infer class purpose
inferClassPurpose(className, content, members) {
const name = className.toLowerCase();
// วิเคราะห์จากชื่อคลาส
if (name.includes('tokenizer')) {
return {
english: `${className} tokenizer`,
thai: `โทเค็นไนเซอร์ ${className}`,
category: 'parser'
};
}
if (name.includes('matcher') || name.includes('pattern')) {
return {
english: `${className} pattern matcher`,
thai: `ตัวจับรูปแบบ ${className}`,
category: 'matcher'
};
}
if (name.includes('generator') || name.includes('creator')) {
return {
english: `${className} generator`,
thai: `ตัวสร้าง ${className}`,
category: 'generator'
};
}
if (name.includes('analyzer') || name.includes('scanner')) {
return {
english: `${className} analyzer`,
thai: `ตัววิเคราะห์ ${className}`,
category: 'analyzer'
};
}
// วิเคราะห์จากเนื้อหา
if (content.includes('constructor') && content.includes('this.')) {
return {
english: `${className} class`,
thai: `คลาส ${className}`,
category: 'class'
};
}
return {
english: `${className} component`,
thai: `ส่วนประกอบ ${className}`,
category: 'component'
};
}
// อนุมานจุดประสงค์ของ object - Infer object purpose
inferObjectPurpose(objectName, content, properties) {
const name = objectName.toLowerCase();
// วิเคราะห์จากชื่อ
if (name.includes('types') || name.includes('type')) {
return {
english: `${objectName} type definitions`,
thai: `คำจำกัดความประเภท ${objectName}`,
category: 'types'
};
}
if (name.includes('config') || name.includes('settings')) {
return {
english: `${objectName} configuration`,
thai: `การกำหนดค่า ${objectName}`,
category: 'config'
};
}
if (name.includes('constants') || name.includes('const')) {
return {
english: `${objectName} constants`,
thai: `ค่าคงที่ ${objectName}`,
category: 'constants'
};
}
// วิเคราะห์จากคุณสมบัติ
if (properties.length > 5 && properties.every(p => p.type === 'string')) {
return {
english: `${objectName} enumeration`,
thai: `การแจงนับ ${objectName}`,
category: 'enum'
};
}
return {
english: `${objectName} object`,
thai: `วัตถุ ${objectName}`,
category: 'object'
};
}
// อนุมานจุดประสงค์ของฟังก์ชัน - Infer function purpose
inferFunctionPurpose(functionName, content, parameters) {
const name = functionName.toLowerCase();
// วิเคราะห์จากชื่อและเนื้อหา
if (content.includes('return') && content.includes('new ')) {
return {
english: `Create ${functionName}`,
thai: `สร้าง ${functionName}`,
category: 'factory'
};
}
if (content.includes('this.') && content.includes('=')) {
return {
english: `Initialize ${functionName}`,
thai: `เริ่มต้น ${functionName}`,
category: 'constructor'
};
}
// ใช้ระบบเดิมแต่ปรับปรุง
return {
english: `Process ${functionName}`,
thai: `ประมวลผล ${functionName}`,
category: 'process'
};
}
// อนุมานประเภทของคุณสมบัติ - Infer property type
inferPropertyType(token) {
if (!token) return 'unknown';
if (token.type === TOKEN_TYPES.STRING) return 'string';
if (token.type === TOKEN_TYPES.NUMBER) return 'number';
if (token.value === 'true' || token.value === 'false') return 'boolean';
if (token.type === TOKEN_TYPES.BRACE_OPEN) return 'object';
return 'identifier';
}
}
// ======================================================================
// ENHANCED PATTERN DETECTION METHODS v2.0 - The Next Frontier
// เมธอดตรวจจับรูปแบบขั้นสูง v2.0 - มิติใหม่ของการพัฒนา
// ======================================================================
// เป็นส่วนขยายของ StructureAnalyzer สำหรับแก้ปัญหา "Missed Structures"
// Integration กับ StructureAnalyzer หลักผ่าน mixin pattern
class EnhancedPatternDetector extends StructureAnalyzer {
// ===================================================================
// TypeScript Advanced Constructs - โครงสร้าง TypeScript ขั้นสูง
// ===================================================================
// รูปแบบ: namespace Name {} - Namespace declaration pattern
// ======================================================================
// EN: matchNamespaceDeclaration class
// TH: คลาส matchNamespaceDeclaration
// ======================================================================
matchNamespaceDeclaration() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'namespace' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.BRACE_OPEN) {
const namespaceToken = this.currentToken();
const nameToken = this.peekToken(1);
this.cursor += 3; // ข้าม 'namespace', name, '{'
return {
type: 'namespace_declaration',
name: nameToken.value,
line: namespaceToken.line,
column: namespaceToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: module Name {} - Module declaration pattern
matchModuleDeclaration() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'module' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.BRACE_OPEN) {
const moduleToken = this.currentToken();
const nameToken = this.peekToken(1);
this.cursor += 3; // ข้าม 'module', name, '{'
return {
type: 'module_declaration',
name: nameToken.value,
line: moduleToken.line,
column: moduleToken.column,
parameters: [],
isAsync: false
};
}
return null;
}
// รูปแบบ: declare global/module/namespace/etc - Declare statement pattern
matchDeclareStatement() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'declare' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD) {
const declareToken = this.currentToken();
const typeToken = this.peekToken(1);
const nameToken = this.peekToken(2);
if (nameToken?.type === TOKEN_TYPES.IDENTIFIER) {
this.cursor += 3; // ข้าม 'declare', type, name
return {
type: 'declare_statement',
name: nameToken.value,
line: declareToken.line,
column: declareToken.column,
parameters: [],
isAsync: false,
declareType: typeToken.value
};
}
}
return null;
}
// รูปแบบ: abstract class Name {} - Abstract class pattern
matchAbstractClass() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'abstract' &&
this.peekToken(1)?.type === TOKEN_TYPES.KEYWORD &&
this.peekToken(1)?.value === 'class' &&
this.peekToken(2)?.type === TOKEN_TYPES.IDENTIFIER) {
const abstractToken = this.currentToken();
const classToken = this.peekToken(1);
const nameToken = this.peekToken(2);
this.cursor += 3; // ข้าม 'abstract', 'class', name
return {
type: 'abstract_class',
name: nameToken.value,
line: abstractToken.line,
column: abstractToken.column,
parameters: [],
isAsync: false,
isAbstract: true
};
}
return null;
}
// รูปแบบ: class Name<T> {} - Generic class pattern
matchGenericClass() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'class' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(2)?.type === TOKEN_TYPES.LESS_THAN) {
const classToken = this.currentToken();
const nameToken = this.peekToken(1);
// หาตำแหน่งปิด generic parameter
let genericEnd = -1;
let depth = 0;
for (let i = this.cursor + 2; i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.LESS_THAN) {
depth++;
} else if (this.tokens[i].type === TOKEN_TYPES.GREATER_THAN) {
depth--;
if (depth === 0) {
genericEnd = i;
break;
}
}
}
if (genericEnd !== -1) {
this.cursor = genericEnd + 1; // ข้ามไปหลัง >
return {
type: 'generic_class',
name: nameToken.value,
line: classToken.line,
column: classToken.column,
parameters: [],
isAsync: false,
isGeneric: true
};
}
}
return null;
}
// ===================================================================
// React/JSX Advanced Patterns - รูปแบบ React/JSX ขั้นสูง
// ===================================================================
// รูปแบบ: const useHook = () => {} - React hooks pattern
matchReactHooks() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'const' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(1)?.value?.startsWith('use') &&
this.peekToken(2)?.type === TOKEN_TYPES.EQUALS) {
const constToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบว่าเป็น arrow function
let arrowPos = -1;
for (let i = this.cursor + 3; i < this.cursor + 10 && i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.ARROW) {
arrowPos = i;
break;
}
}
if (arrowPos !== -1) {
this.cursor = arrowPos + 1; // ข้ามไปหลัง =>
return {
type: 'react_hook',
name: nameToken.value,
line: constToken.line,
column: constToken.column,
parameters: [],
isAsync: false
};
}
}
return null;
}
// รูปแบบ: React.forwardRef() - React forwardRef pattern
matchReactForwardRef() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'const' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER) {
// หา React.forwardRef pattern
let hasReactForwardRef = false;
for (let i = this.cursor + 2; i < this.cursor + 15 && i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.IDENTIFIER &&
this.tokens[i].value === 'React' &&
this.tokens[i + 1]?.value === '.' &&
this.tokens[i + 2]?.value === 'forwardRef') {
hasReactForwardRef = true;
this.cursor = i + 3;
break;
}
}
if (hasReactForwardRef) {
const constToken = this.currentToken();
const nameToken = this.peekToken(1);
return {
type: 'react_forwardref',
name: nameToken.value,
line: constToken.line,
column: constToken.column,
parameters: [],
isAsync: false
};
}
}
return null;
}
// รูปแบบ: React.memo() - React memo pattern
matchReactMemo() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'const' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER) {
// หา React.memo pattern
let hasReactMemo = false;
for (let i = this.cursor + 2; i < this.cursor + 15 && i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.IDENTIFIER &&
this.tokens[i].value === 'React' &&
this.tokens[i + 1]?.value === '.' &&
this.tokens[i + 2]?.value === 'memo') {
hasReactMemo = true;
this.cursor = i + 3;
break;
}
}
if (hasReactMemo) {
const constToken = this.currentToken();
const nameToken = this.peekToken(1);
return {
type: 'react_memo',
name: nameToken.value,
line: constToken.line,
column: constToken.column,
parameters: [],
isAsync: false
};
}
}
return null;
}
// รูปแบบ: const withHOC = (Component) => {} - Higher Order Component pattern
matchHigherOrderComponent() {
if (this.currentToken()?.type === TOKEN_TYPES.KEYWORD &&
this.currentToken()?.value === 'const' &&
this.peekToken(1)?.type === TOKEN_TYPES.IDENTIFIER &&
this.peekToken(1)?.value?.startsWith('with')) {
const constToken = this.currentToken();
const nameToken = this.peekToken(1);
// ตรวจสอบรูปแบบ HOC
let arrowPos = -1;
for (let i = this.cursor + 3; i < this.cursor + 15 && i < this.tokens.length; i++) {
if (this.tokens[i].type === TOKEN_TYPES.ARROW) {
arrowPos = i;
break;
}
}
if (arrowPos !== -1) {
this.cursor = arrowPos + 1;
return {
type: 'higher_order_component',
name: nameToken.value,
line: constToken.line,
column: constToken.column,
parameters: [],
isAsync: false
};
}
}
return null;
}
}
// ======================================================================
// Comment Generation Engine/เครื่องมือสร้างคอมเมนต์
// ======================================================================
// Comment Generator:ตัวสร้างคอมเมนต์
class CommentGenerator {
constructor() {
this.functionDescriptions = {
// ═══════════════════════════════════════════════════════════════
// DATABASE & CRUD OPERATIONS - การดำเนินการฐานข้อมูล
// ═══════════════════════════════════════════════════════════════
'get': ['Get data', 'ดึงข้อมูล'],
'fetch': ['Fetch data', 'ดึงข้อมูล'],
'retrieve': ['Retrieve data', 'ดึงข้อมูล'],
'load': ['Load data', 'โหลดข้อมูล'],
'read': ['Read data', 'อ่านข้อมูล'],
'find': ['Find data', 'ค้นหาข้อมูล'],
'search': ['Search data', 'ค้นหาข้อมูล'],
'query': ['Query data', 'สอบถามข้อมูล'],
'select': ['Select data', 'เลือกข้อมูล'],
'filter': ['Filter data', 'กรองข้อมูล'],
'sort': ['Sort data', 'เรียงข้อมูล'],
'order': ['Order data', 'จัดเรียงข้อมูล'],
'create': ['Create data', 'สร้างข้อมูล'],
'insert': ['Insert data', 'เพิ่มข้อมูล'],
'addinterceptor': ['Add interceptor', 'เพิ่มตัวสกัดกั้น'],
'addrequestinterceptor': ['Add request interceptor', 'เพิ่มตัวสกัดกั้นคำขอ'],
'addresponseinterceptor': ['Add response interceptor', 'เพิ่มตัวสกัดกั้นการตอบกลับ'],
'tojson': ['Convert to JSON', 'แปลงเป็น JSON'],
'fromjson': ['Create from JSON', 'สร้างจาก JSON'],
'isretryable': ['Check if retryable', 'ตรวจสอบว่าลองใหม่ได้หรือไม่'],
'performrequest': ['Perform request', 'ดำเนินการขอ'],
'retryrequest': ['Retry request', 'ลองคำขอใหม่'],
'withretry': ['With retry logic', 'พร้อมตรรกะลองใหม่'],
'post': ['Post data', 'โพสต์ข้อมูล'],
'put': ['Put data', 'ใส่ข้อมูล'],
'update': ['Update data', 'อัพเดทข้อมูล'],
'modify': ['Modify data', 'แก้ไขข้อมูล'],
'edit': ['Edit data', 'แก้ไขข้อมูล'],
'patch': ['Patch data', 'แพทช์ข้อมูล'],
'change': ['Change data', 'เปลี่ยนข้อมูล'],
'delete': ['Delete data', 'ลบข้อมูล'],
'remove': ['Remove item', 'ลบรายการ'],
'destroy': ['Destroy data', 'ทำลายข้อมูล'],
'drop': ['Drop data', 'ทิ้งข้อมูล'],
'save': ['Save data', 'บันทึกข้อมูล'],
'store': ['Store data', 'เก็บข้อมูล'],
'persist': ['Persist data', 'บันทึกถาวร'],
'commit': ['Commit changes', 'ยืนยันการเปลี่ยนแปลง'],
'rollback': ['Rollback changes', 'ย้อนกลับการเปลี่ยนแปลง'],
// ═══════════════════════════════════════════════════════════════
// VALIDATION & VERIFICATION - การตรวจสอบและยืนยัน
// ═══════════════════════════════════════════════════════════════
'validate': ['Validate input', 'ตรวจสอบความถูกต้อง'],
'check': ['Check data', 'ตรวจสอบข้อมูล'],
'verify': ['Verify data', 'ยืนยันข้อมูล'],
'test': ['Test function', 'ทดสอบฟังก์ชัน'],
'ensure': ['Ensure condition', 'ประกันเงื่อนไข'],
'assert': ['Assert condition', 'ยืนยันเงื่อนไข'],
'confirm': ['Confirm action', 'ยืนยันการกระทำ'],
'authorize': ['Authorize user', 'อนุญาตผู้ใช้'],
'authenticate': ['Authenticate user', 'รับรองผู้ใช้'],
'permit': ['Permit access', 'อนุญาตการเข้าถึง'],
'allow': ['Allow action', 'อนุญาตการกระทำ'],
'deny': ['Deny access', 'ปฏิเสธการเข้าถึง'],
'reject': ['Reject request', 'ปฏิเสธคำขอ'],
'approve': ['Approve request', 'อนุมัติคำขอ'],
// ═══════════════════════════════════════════════════════════════
// PROCESSING & COMPUTATION - การประมวลผลและคำนวณ
// ═══════════════════════════════════════════════════════════════
'process': ['Process data', 'ประมวลผลข้อมูล'],
'handle': ['Handle event', 'จัดการเหตุการณ์'],
'execute': ['Execute command', 'ดำเนินการคำสั่ง'],
'run': ['Run process', 'รันกระบวนการ'],
'perform': ['Perform action', 'ปฏิบัติการ'],
'operate': ['Operate system', 'ดำเนินการระบบ'],
'start': ['Start process', 'เริ่มกระบวนการ'],
'begin': ['Begin operation', 'เริ่มการดำเนินการ'],
'launch': ['Launch application', 'เปิดแอปพลิเคชัน'],
'init': ['Initialize system', 'เริ่มต้นระบบ'],
'initialize': ['Initialize data', 'เริ่มต้นข้อมูล'],
'setup': ['Setup configuration', 'ตั้งค่าระบบ'],
'configure': ['Configure settings', 'กำหนดค่าการตั้งค่า'],
'stop': ['Stop process', 'หยุดกระบวนการ'],
'end': ['End operation', 'สิ้นสุดการดำเนินการ'],
'finish': ['Finish task', 'เสร็จสิ้นงาน'],
'complete': ['Complete operation', 'ดำเนินการเสร็จสิ้น'],
'terminate': ['Terminate process', 'ยุติกระบวนการ'],
'kill': ['Kill process', 'ฆ่ากระบวนการ'],
'abort': ['Abort operation', 'ยกเลิกการดำเนินการ'],
'cancel': ['Cancel request', 'ยกเลิกคำขอ'],
'pause': ['Pause execution', 'หยุดชั่วคราว'],
'resume': ['Resume execution', 'ดำเนินการต่อ'],
'restart': ['Restart system', 'เริ่มต้นใหม่'],
'reload': ['Reload data', 'โหลดข้อมูลใหม่'],
'refresh': ['Refresh content', 'รีเฟรชเนื้อหา'],
'reset': ['Reset state', 'รีเซ็ตสถานะ'],
'clear': ['Clear data', 'เคลียร์ข้อมูล'],
'clean': ['Clean up', 'ทำความสะอาด'],
'flush': ['Flush cache', 'ล้างแคช'],
'purge': ['Purge data', 'ลบข้อมูลออก'],
// ═══════════════════════════════════════════════════════════════
// DATA TRANSFORMATION - การแปลงข้อมูล
// ═══════════════════════════════════════════════════════════════
'parse': ['Parse data', 'แปลงข้อมูล'],
'format': ['Format data', 'จัดรูปแบบข้อมูล'],
'convert': ['Convert data', 'แปลงข้อมูล'],
'transform': ['Transform data', 'เปลี่ยนแปลงข้อมูล'],
'map': ['Map data', 'แมปข้อมูล'],
'reduce': ['Reduce data', 'ลดข้อมูล'],
'filter': ['Filter data', 'กรองข้อมูล'],
'compress': ['Compress data', 'บีบอัดข้อมูล'],
'decompress': ['Decompress data', 'คลายการบีบอัด'],
'encode': ['Encode data', 'เข้ารหัสข้อมูล'],
'decode': ['Decode data', 'ถอดรหัสข้อมูล'],
'encrypt': ['Encrypt data', 'เข้ารหัสข้อมูล'],
'decrypt': ['Decrypt data', 'ถอดรหัสข้อมูล'],
'hash': ['Hash data', 'แฮชข้อมูล'],
'serialize': ['Serialize data', 'ซีเรียลไลซ์ข้อมูล'],
'deserialize': ['Deserialize data', 'ดีซีเรียลไลซ์ข้อมูล'],
'stringify': ['Stringify data', 'แปลงเป็นสตริง'],
'normalize': ['Normalize data', 'ทำให้ข้อมูลเป็นมาตรฐาน'],
'sanitize': ['Sanitize input', 'ทำความสะอาดข้อมูลนำเข้า'],
'escape': ['Escape characters', 'หลีกเลี่ยงอักขระ'],
// ═══════════════════════════════════════════════════════════════
// MATHEMATICAL & COMPUTATIONAL - คณิตศาสตร์และการคำนวณ
// ═══════════════════════════════════════════════════════════════
'calculate': ['Calculate value', 'คำนวณค่า'],
'compute': ['Compute result', 'คำนวณผลลัพธ์'],
'evaluate': ['Evaluate expression', 'ประเมินนิพจน์'],
'measure': ['Measure value', 'วัดค่า'],
'count': ['Count items', 'นับจำนวน'],
'sum': ['Sum values', 'รวมค่า'],
'total': ['Total amount', 'จำนวนรวม'],
'average': ['Average value', 'ค่าเฉลี่ย'],
'mean': ['Mean value', 'ค่าเฉลี่ย'],
'median': ['Median value', 'ค่ามัธยฐาน'],
'mode': ['Mode value', 'ค่าฐานนิยม'],
'min': ['Minimum value', 'ค่าต่ำสุด'],
'max': ['Maximum value', 'ค่าสูงสุด'],
'range': ['Range of values', 'ช่วงค่า'],
'variance': ['Variance calculation', 'การคำนวณความแปรปรวน'],
'deviation': ['Deviation calculation', 'การคำนวณส่วนเบียงเบน'],
'round': ['Round number', 'ปัดเศษจำนวน'],
'ceil': ['Ceiling number', 'ปัดขึ้น'],
'floor': ['Floor number', 'ปัดลง'],
'abs': ['Absolute value', 'ค่าสัมบูรณ์'],
'sqrt': ['Square root', 'รากที่สอง'],
'pow': ['Power calculation', 'การยกกำลัง'],
'log': ['Logarithm calculation', 'การคำนวณลอการิทึม'],
'sin': ['Sine function', 'ฟังก์ชันไซน์'],
'cos': ['Cosine function', 'ฟังก์ชันโคไซน์'],
'tan': ['Tangent function', 'ฟังก์ชันแทนเจนต์'],
// ═══════════════════════════════════════════════════════════════
// UI & PRESENTATION - อินเทอร์เฟซและการแสดงผล
// ═══════════════════════════════════════════════════════════════
'render': ['Render content', 'แสดงผลเนื้อหา'],
'display': ['Display info', 'แสดงข้อมูล'],
'show': ['Show element', 'แสดงองค์ประกอบ'],
'hide': ['Hide element', 'ซ่อนองค์ประกอบ'],
'toggle': ['Toggle state', 'สลับสถานะ'],
'open': ['Open dialog', 'เปิดไดอะล็อก'],
'close': ['Close window', 'ปิดหน้าต่าง'],
'modal': ['Modal dialog', 'ไดอะล็อกโมดัล'],
'popup': ['Popup window', 'หน้าต่างป๊อปอัป'],
'tooltip': ['Tooltip display', 'แสดงคำแนะนำ'],
'menu': ['Menu system', 'ระบบเมนู'],
'dropdown': ['Dropdown menu', 'เมนูดรอปดาวน์'],
'sidebar': ['Sidebar component', 'ส่วนประกอบแถบข้าง'],
'navbar': ['Navigation bar', 'แถบนำทาง'],
'header': ['Header component', 'ส่วนหัว'],
'footer': ['Footer component', 'ส่วนท้าย'],
'panel': ['Panel component', 'ส่วนประกอบแผง'],
'tab': ['Tab component', 'ส่วนประกอบแท็บ'],
'card': ['Card component', 'ส่วนประกอบการ์ด'],
'button': ['Button component', 'ส่วนประกอบปุ่ม'],
'input': ['Input field', 'ช่องข้อมูลนำเข้า'],
'form': ['Form component', 'ส่วนประกอบฟอร์ม'],
'table': ['Table component', 'ส่วนประกอบตาราง'],
'list': ['List component', 'ส่วนประกอบรายการ'],
'grid': ['Grid layout', 'เลย์เอาต์กริด'],
'chart': ['Chart visualization', 'การแสดงผลแผนภูมิ'],
'graph': ['Graph display', 'การแสดงผลกราฟ'],
// ═══════════════════════════════════════════════════════════════
// NETWORKING & COMMUNICATION - เครือข่ายและการสื่อสาร
// ═══════════════════════════════════════════════════════════════
'send': ['Send data', 'ส่งข้อมูล'],
'receive': ['Receive data', 'รับข้อมูล'],
'request': ['Request data', 'ขอข้อมูล'],
'response': ['Response data', 'ตอบกลับข้อมูล'],
'connect': ['Connect server', 'เชื่อมต่อเซิร์ฟเวอร์'],
'disconnect': ['Disconnect server', 'ตัดการเชื่อมต่อ'],
'socket': ['Socket connection', 'การเชื่อมต่อซ็อกเก็ต'],
'websocket': ['WebSocket connection', 'การเชื่อมต่อเว็บซ็อกเก็ต'],
'http': ['HTTP request', 'คำขอ HTTP'],
'https': ['HTTPS request', 'คำขอ HTTPS'],
'api': ['API endpoint', 'จุดสิ้นสุด API'],
'rest': ['REST API', 'REST API'],
'graphql': ['GraphQL query', 'คิวรี GraphQL'],
'ajax': ['AJAX request', 'คำขอ AJAX'],
'xhr': ['XMLHttpRequest', 'XMLHttpRequest'],
'download': ['Download file', 'ดาวน์โหลดไฟล์'],
'upload': ['Upload file', 'อัปโหลดไฟล์'],
'stream': ['Stream data', 'สตรีมข้อมูล'],
'broadcast': ['Broadcast message', 'ออกอากาศข้อความ'],
'publish': ['Publish event', 'เผยแพร่เหตุการณ์'],
'subscribe': ['Subscribe event', 'สมัครสมาชิกเหตุการณ์'],
'emit': ['Emit signal', 'ส่งสัญญาณ'],
'listen': ['Listen event', 'ฟังเหตุการณ์'],
'poll': ['Poll data', 'โพลข้อมูล'],
// ═══════════════════════════════════════════════════════════════
// FILE & STORAGE OPERATIONS - การดำเนินการไฟล์และที่เก็บข้อมูล
// ═══════════════════════════════════════════════════════════════
'file': ['File operation', 'การดำเนินการไฟล์'],
'folder': ['Folder operation', 'การดำเนินการโฟลเดอร์'],
'directory': ['Directory operation', 'การดำเนินการไดเรกทอรี'],
'path': ['Path handling', 'การจัดการพาธ'],
'write': ['Write file', 'เขียนไฟล์'],
'read': ['Read file', 'อ่านไฟล์'],
'copy': ['Copy file', 'คัดลอกไฟล์'],
'move': ['Move file', 'ย้ายไฟล์'],
'rename': ['Rename file', 'เปลี่ยนชื่อไฟล์'],
'create': ['Create file', 'สร้างไฟล์'],
'mkdir': ['Make directory', 'สร้างไดเรกทอรี'],
'exists': ['Check existence', 'ตรวจสอบการมีอยู่'],
'stat': ['File statistics', 'สถิติไฟล์'],
'watch': ['Watch changes', 'เฝ้าดูการเปลี่ยนแปลง'],
'backup': ['Backup data', 'สำรองข้อมูล'],
'restore': ['Restore data', 'กู้คืนข้อมูล'],
'archive': ['Archive files', 'เก็บถาวรไฟล์'],
'extract': ['Extract archive', 'แยกไฟล์เก็บถาวร'],
'zip': ['Zip files', 'บีบอัดไฟล์'],
'unzip': ['Unzip files', 'แตกไฟล์บีบอัด'],
// ═══════════════════════════════════════════════════════════════
// CACHE & MEMORY MANAGEMENT - การจัดการแคชและหน่วยความจำ
// ═══════════════════════════════════════════════════════════════
'cache': ['Cache data', 'แคชข้อมูล'],
'memoize': ['Memoize function', 'จดจำฟังก์ชัน'],
'buffer': ['Buffer data', 'บัฟเฟอร์ข้อมูล'],
'pool': ['Connection pool', 'พูลการเชื่อมต่อ'],
'queue': ['Queue system', 'ระบบคิว'],
'stack': ['Stack operations', 'การดำเนินการสแต็ก'],
'heap': ['Heap management', 'การจัดการฮีป'],
'memory': ['Memory management', 'การจัดการหน่วยความจำ'],
'garbage': ['Garbage collection', 'การเก็บขยะ'],
'leak': ['Memory leak', 'การรั่วไหลของหน่วยความจำ'],
'allocate': ['Allocate memory', 'จัดสรรหน่วยความจำ'],
'deallocate': ['Deallocate memory', 'ยกเลิกการจัดสรร'],
'optimize': ['Optimize performance', 'เพิ่มประสิทธิภาพ'],
'throttle': ['Throttle execution', 'จำกัดการดำเนินการ'],
'debounce': ['Debounce function', 'ดีเบาส์ฟังก์ชัน'],
// ═══════════════════════════════════════════════════════════════
// ERROR HANDLING & LOGGING - การจัดการข้อผิดพลาดและการบันทึก
// ═══════════════════════════════════════════════════════════════
'error': ['Error handling', 'การจัดการข้อผิดพลาด'],
'exception': ['Exception handling', 'การจัดการข้อยกเว้น'],
'throw': ['Throw error', 'โยนข้อผิดพลาด'],
'catch': ['Catch error', 'จับข้อผิดดพลาด'],
'try': ['Try operation', 'ลองการดำเนินการ'],
'finally': ['Finally block', 'บล็อกสุดท้าย'],
'log': ['Log message', 'บันทึกข้อความ'],
'warn': ['Warning message', 'ข้อความเตือน'],
'info': ['Information message', 'ข้อความข้อมูล'],
'debug': ['Debug message', 'ข้อความดีบัก'],
'trace': ['Trace execution', 'ติดตามการดำเนินการ'],
'monitor': ['Monitor system', 'ตรวจสอบระบบ'],
'alert': ['Alert notification', 'การแจ้งเตือน'],
'notify': ['Notify user', 'แจ้งผู้ใช้'],
// ═══════════════════════════════════════════════════════════════
// SECURITY & AUTHENTICATION - ความปลอดภัยและการรับรอง
// ═══════════════════════════════════════════════════════════════
'login': ['Login user', 'เข้าสู่ระบบผู้ใช้'],
'logout': ['Logout user', 'ออกจากระบบผู้ใช้'],
'signin': ['Sign in user', 'ลงชื่อเข้าใช้'],
'signout': ['Sign out user', 'ลงชื่อออก'],
'signup': ['Sign up user', 'สมัครสมาชิก'],
'register': ['Register user', 'ลงทะเบียนผู้ใช้'],
'auth': ['Authentication', 'การรับรองตัวตน'],
'token': ['Token management', 'การจัดการโทเคน'],
'jwt': ['JWT token', 'โทเคน JWT'],
'session': ['Session management', 'การจัดการเซสชัน'],
'cookie': ['Cookie handling', 'การจัดการคุกกี้'],
'csrf': ['CSRF protection', 'การป้องกัน CSRF'],
'xss': ['XSS protection', 'การป้องกัน XSS'],
'cors': ['CORS handling', 'การจัดการ CORS'],
'secure': ['Security function', 'ฟังก์ชันความปลอดภัย'],
'permission': ['Permission check', 'ตรวจสอบสิทธิ์'],
'role': ['Role management', 'การจัดการบทบาท'],
'acl': ['Access control', 'การควบคุมการเข้าถึง'],
// ═══════════════════════════════════════════════════════════════
// TESTING & QUALITY ASSURANCE - การทดสอบและการประกันคุณภาพ
// ═══════════════════════════════════════════════════════════════
'test': ['Test function', 'ทดสอบฟังก์ชัน'],
'spec': ['Specification test', 'ทดสอบข้อกำหนด'],
'suite': ['Test suite', 'ชุดทดสอบ'],
'case': ['Test case', 'กรณีทดสอบ'],
'mock': ['Mock function', 'ฟังก์ชันจำลอง'],
'stub': ['Stub function', 'ฟังก์ชันดัมมี่'],
'spy': ['Spy function', 'ฟังก์ชันสายลับ'],
'expect': ['Expect assertion', 'การยืนยันคาดหวัง'],
'should': ['Should assertion', 'การยืนยันควร'],
'describe': ['Describe test', 'อธิบายการทดสอบ'],
'it': ['Test case description', 'คำอธิบายกรณีทดสอบ'],
'before': ['Before hook', 'ฮุคก่อนหน้า'],
'after': ['After hook', 'ฮุคหลังจาก'],
'setup': ['Setup test', 'ตั้งค่าการทดสอบ'],
'teardown': ['Teardown test', 'ทำลายการทดสอบ'],
'benchmark': ['Benchmark test', 'ทดสอบประสิทธิภาพ'],
'performance': ['Performance test', 'ทดสอบประสิทธิภาพ'],
// ═══════════════════════════════════════════════════════════════
// UTILITY & HELPER FUNCTIONS - ฟังก์ชันช่วยเหลือและเครื่องมือ
// ═══════════════════════════════════════════════════════════════
'util': ['Utility function', 'ฟังก์ชันเครื่องมือ'],
'helper': ['Helper function', 'ฟังก์ชันช่วยเหลือ'],
'tool': ['Tool function', 'ฟังก์ชันเครื่องมือ'],
'generator': ['Generator function', 'ฟังก์ชันตัวสร้าง'],
'factory': ['Factory function', 'ฟังก์ชันโรงงาน'],
'builder': ['Builder function', 'ฟังก์ชันผู้สร้าง'],
'creator': ['Creator function', 'ฟังก์ชันผู้สร้าง'],
'constructor': ['Constructor function', 'ฟังก์ชันคอนสตรัคเตอร์'],
'destructor': ['Destructor function', 'ฟังก์ชันดีสตรัคเตอร์'],
'adapter': ['Adapter pattern', 'รูปแบบอะแดปเตอร์'],
'wrapper': ['Wrapper function', 'ฟังก์ชันห่อหุ้ม'],
'decorator': ['Decorator pattern', 'รูปแบบเดคคอเรเตอร์'],
'observer': ['Observer pattern', 'รูปแบบผู้สังเกตการณ์'],
'strategy': ['Strategy pattern', 'รูปแบบกลยุทธ์'],
'singleton': ['Singleton pattern', 'รูปแบบซิงเกิลตัน'],
// ═══════════════════════════════════════════════════════════════
// CLASSES & COMPLEX TYPES - คลาสและประเภทที่ซับซ้อน
// ═══════════════════════════════════════════════════════════════
'class': ['Class definition', 'คำจำกัดความคลาส'],
'interface': ['Interface definition', 'คำจำกัดความอินเทอร์เฟซ'],
'type': ['Type definition', 'คำจำกัดความประเภท'],
'enum': ['Enumeration', 'การนับเลข'],
'struct': ['Structure definition', 'คำจำกัดความโครงสร้าง'],
'module': ['Module definition', 'คำจำกัดความโมดูล'],
'component': ['Component class', 'คลาสส่วนประกอบ'],
'service': ['Service class', 'คลาสบริการ'],
'controller': ['Controller class', 'คลาสควบคุม'],
'model': ['Model class', 'คลาสแบบจำลอง'],
'view': ['View class', 'คลาสมุมมอง'],
'repository': ['Repository class', 'คลาสที่เก็บ'],
'dao': ['Data Access Object', 'วัตถุการเข้าถึงข้อมูล'],
'dto': ['Data Transfer Object', 'วัตถุการถ่ายโอนข้อมูล'],
'entity': ['Entity class', 'คลาสเอนทิตี'],
'manager': ['Manager class', 'คลาสผู้จัดการ'],
'handler': ['Handler class', 'คลาสผู้จัดการ'],
'processor': ['Processor class', 'คลาสผู้ประมวลผล'],
'validator': ['Validator class', 'คลาสตัวตรวจสอบ'],
'parser': ['Parser class', 'คลาสตัวแยกวิเคราะห์'],
'formatter': ['Formatter class', 'คลาสตัวจัดรูปแบบ'],
'converter': ['Converter class', 'คลาสตัวแปลง'],
'transformer': ['Transformer class', 'คลาสตัวเปลี่ยนแปลง'],
'builder': ['Builder class', 'คลาสตัวสร้าง'],
'factory': ['Factory class', 'คลาสโรงงาน'],
'strategy': ['Strategy class', 'คลาสกลยุทธ์'],
'command': ['Command class', 'คลาสคำสั่ง'],
'event': ['Event class', 'คลาสเหตุการณ์'],
'listener': ['Listener class', 'คลาสตัวฟัง'],
'observer': ['Observer class', 'คลาสผู้สังเกตการณ์'],
'subject': ['Subject class', 'คลาสหัวข้อ'],
'proxy': ['Proxy class', 'คลาสพร็อกซี่'],
'adapter': ['Adapter class', 'คลาสอะแดปเตอร์'],
'facade': ['Facade class', 'คลาสหน้าต่าง'],
'bridge': ['Bridge class', 'คลาสสะพาน'],
'composite': ['Composite class', 'คลาสคอมโพสิต'],
'decorator': ['Decorator class', 'คลาสเดคคอเรเตอร์'],
'flyweight': ['Flyweight class', 'คลาสน้ำหนักเบา'],
'iterator': ['Iterator class', 'คลาสตัววนซ้ำ'],
'mediator': ['Mediator class', 'คลาสผู้ไกล่เกลี่ย'],
'memento': ['Memento class', 'คลาสที่ระลึก'],
'prototype': ['Prototype class', 'คลาสต้นแบบ'],
'state': ['State class', 'คลาสสถานะ'],
'template': ['Template class', 'คลาสแม่แบบ'],
'visitor': ['Visitor class', 'คลาสผู้เยือน'],
'calculator': ['Calculator class', 'คลาสเครื่องคิดเลข'],
'advanced': ['Advanced system', 'ระบบขั้นสูง'],
'complex': ['Complex system', 'ระบบที่ซับซ้อน'],
'simple': ['Simple function', 'ฟังก์ชันง่าย'],
'basic': ['Basic function', 'ฟังก์ชันพื้นฐาน'],
'core': ['Core function', 'ฟังก์ชันหลัก'],
'main': ['Main function', 'ฟังก์ชันหลัก'],
'primary': ['Primary function', 'ฟังก์ชันหลัก'],
'secondary': ['Secondary function', 'ฟังก์ชันรอง'],
'custom': ['Custom function', 'ฟังก์ชันกำหนดเอง'],
'dynamic': ['Dynamic function', 'ฟังก์ชันไดนามิก'],
'static': ['Static function', 'ฟังก์ชันสแตติก'],
'async': ['Async function', 'ฟังก์ชันแบบอะซิงค์'],
'sync': ['Sync function', 'ฟังก์ชันแบบซิงค์'],
'generic': ['Generic function', 'ฟังก์ชันทั่วไป'],
'specific': ['Specific function', 'ฟังก์ชันเฉพาะ'],
'abstract': ['Abstract function', 'ฟังก์ชันนามธรรม'],
'concrete': ['Concrete function', 'ฟังก์ชันที่เป็นรูปธรรม'],
'virtual': ['Virtual function', 'ฟังก์ชันเสมือน'],
'override': ['Override function', 'ฟังก์ชันเขียนทับ'],
'implement': ['Implementation', 'การนำไปใช้'],
'extend': ['Extension function', 'ฟังก์ชันส่วนขยาย'],
'inherit': ['Inheritance function', 'ฟังก์ชันการสืบทอด'],
'compose': ['Composition function', 'ฟังก์ชันการผสมผสาน'],
'aggregate': ['Aggregation function', 'ฟังก์ชันการรวบรวม'],
'associate': ['Association function', 'ฟังก์ชันการเชื่อมโยง'],
'delegate': ['Delegation function', 'ฟังก์ชันการมอบหมาย'],
'encapsulate': ['Encapsulation function', 'ฟังก์ชันการห่อหุ้ม'],
'polymorphic': ['Polymorphic function', 'ฟังก์ชันแบบพหุรูป'],
// ═══════════════════════════════════════════════════════════════
// FRAMEWORK & LIBRARY SPECIFIC - เฉพาะเฟรมเวิร์กและไลบรารี
// ═══════════════════════════════════════════════════════════════
'react': ['React component', 'คอมโพเนนต์ React'],
'vue': ['Vue component', 'คอมโพเนนต์ Vue'],
'angular': ['Angular component', 'คอมโพเนนต์ Angular'],
'nodejs': ['Node.js function', 'ฟังก์ชัน Node.js'],
'express': ['Express middleware', 'มิดเดิลแวร์ Express'],
'redux': ['Redux action', 'การกระทำ Redux'],
'mongoose': ['Mongoose model', 'แบบจำลอง Mongoose'],
'sequelize': ['Sequelize model', 'แบบจำลอง Sequelize'],
'typeorm': ['TypeORM entity', 'เอนทิตี TypeORM'],
'prisma': ['Prisma model', 'แบบจำลอง Prisma'],
'graphql': ['GraphQL resolver', 'ตัวแยกวิเคราะห์ GraphQL'],
'apollo': ['Apollo client', 'ลูกค้า Apollo'],
'next': ['Next.js page', 'หน้า Next.js'],
'nuxt': ['Nuxt.js page', 'หน้า Nuxt.js'],
'gatsby': ['Gatsby component', 'คอมโพเนนต์ Gatsby'],
'svelte': ['Svelte component', 'คอมโพเนนต์ Svelte'],
'webpack': ['Webpack configuration', 'การกำหนดค่า Webpack'],
'vite': ['Vite configuration', 'การกำหนดค่า Vite'],
'rollup': ['Rollup configuration', 'การกำหนดค่า Rollup'],
'babel': ['Babel transformation', 'การเปลี่ยนแปลง Babel'],
'eslint': ['ESLint rule', 'กฎ ESLint'],
'prettier': ['Prettier formatter', 'ตัวจัดรูปแบบ Prettier'],
'jest': ['Jest test', 'การทดสอบ Jest'],
'mocha': ['Mocha test', 'การทดสอบ Mocha'],
'cypress': ['Cypress test', 'การทดสอบ Cypress'],
'playwright': ['Playwright test', 'การทดสอบ Playwright'],
'socket': ['Socket.io handler', 'ตัวจัดการ Socket.io'],
'passport': ['Passport strategy', 'กลยุทธ์ Passport'],
'multer': ['Multer middleware', 'มิดเดิลแวร์ Multer'],
'cors': ['CORS middleware', 'มิดเดิลแวร์ CORS'],
'helmet': ['Helmet security', 'ความปลอดภัย Helmet'],
'bcrypt': ['Bcrypt hashing', 'การแฮช Bcrypt'],
'jwt': ['JWT authentication', 'การรับรองตัวตน JWT'],
'axios': ['Axios request', 'คำขอ Axios'],
'lodash': ['Lodash utility', 'เครื่องมือ Lodash'],
'moment': ['Moment.js date', 'วันที่ Moment.js'],
'dayjs': ['Day.js date', 'วันที่ Day.js'],
'luxon': ['Luxon date', 'วันที่ Luxon'],
// ═══════════════════════════════════════════════════════════════
// DATA STRUCTURES & ALGORITHMS - โครงสร้างข้อมูลและอัลกอริทึม
// ═══════════════════════════════════════════════════════════════
'node': ['Node structure', 'โครงสร้างโหนด'],
'tree': ['Tree structure', 'โครงสร้างต้นไม้'],
'graph': ['Graph structure', 'โครงสร้างกราฟ'],
'linkedlist': ['LinkedList structure', 'โครงสร้างลิงค์ลิสต์'],
'algorithm': ['Algorithm implementation', 'การใช้งานอัลกอริทึม'],
'sort': ['Sort algorithm', 'อัลกอริทึมการเรียง'],
'search': ['Search algorithm', 'อัลกอริทึมการค้นหา'],
// ═══════════════════════════════════════════════════════════════
// DEFAULT & FALLBACK - ค่าเริ่มต้นและทางเลือก
// ═══════════════════════════════════════════════════════════════
'default': ['Function', 'ฟังก์ชัน']
};
}
// สร้างคอมเมนต์สำหรับฟังก์ชันโดยวิเคราะห์โครงสร้าง - Generate comments with structure analysis
generateFunctionComment(func, options = {}) {
const { aiMode = false, addMissing = false, structure = null } = options;
let description;
// ถ้ามี structure analysis ให้ใช้ข้อมูลจากการวิเคราะห์
if (structure && structure.purpose) {
description = {
english: structure.purpose.english,
thai: structure.purpose.thai
};
} else {
// จัดการ interface, type alias, static method ที่พิเศษ
if (func.type === 'interface_declaration') {
description = {
english: `Interface definition for ${func.name}`,
thai: `การกำหนด interface สำหรับ ${func.name}`
};
} else if (func.type === 'type_alias') {
description = {
english: `Type alias definition for ${func.name}`,
thai: `การกำหนด type alias สำหรับ ${func.name}`
};
} else if (func.type === 'static_method') {
description = {
english: `Static method: ${func.name}`,
thai: `เมธอดแบบ static: ${func.name}`
};
} else if (func.type === 'arrow_function') {
description = {
english: `Arrow function: ${func.name}`,
thai: `ฟังก์ชันแบบ arrow: ${func.name}`
};
} else {
// ใช้วิธีเดิม
description = this.getFunctionDescription(func.name, func.type);
}
}
// สร้าง comment ในรูปแบบที่ปลอดภัยและเสถียร (zone headers)
let comment = '';
comment += '// ======================================================================\n';
comment += `// EN: ${description.english}\n`;
comment += `// TH: ${description.thai}\n`;
comment += '// ======================================================================\n';
// สำหรับ object ที่มี properties เยอะ ให้เพิ่มคอมเมนต์แยกหมวดหมู่
if (structure && structure.type === 'object' && structure.properties && structure.properties.length > 0) {
const categorizedProps = this.categorizeObjectProperties(structure.properties, structure.name);
return this.generateObjectComments(comment, categorizedProps, structure);
}
return comment;
}
// สร้างคอมเมนต์สำหรับ object แบบครบถ้วน - Generate comprehensive object comments
generateObjectComments(headerComment, categorizedProps, structure) {
// สำหรับ object ที่มี properties เยอะ เราไม่ต้องแทรกคอมเมนต์ลงในโครงสร้าง
// แค่ส่งคืน header comment เท่านั้น เพราะ properties จะถูกแทรกโดย addMissingComments
return headerComment.trim();
}
// จัดหมวดหมู่ properties ของ object - Categorize object properties
categorizeObjectProperties(properties, objectName) {
const categories = {
keywords: [],
identifiers: [],
operators: [],
comments: [],
strings: [],
numbers: [],
whitespace: [],
other: []
};
properties.forEach(prop => {
const name = prop.name.toLowerCase();
if (name.includes('keyword')) {
categories.keywords.push(prop);
} else if (name.includes('identifier')) {
categories.identifiers.push(prop);
} else if (name.includes('equals') || name.includes('arrow') ||
name.includes('paren') || name.includes('brace') ||
name.includes('semicolon') || name.includes('comma')) {
categories.operators.push(prop);
} else if (name.includes('comment') || name.includes('line') || name.includes('block')) {
categories.comments.push(prop);
} else if (name.includes('string')) {
categories.strings.push(prop);
} else if (name.includes('number')) {
categories.numbers.push(prop);
} else if (name.includes('whitespace') || name.includes('newline') || name.includes('eof')) {
categories.whitespace.push(prop);
} else {
categories.other.push(prop);
}
});
return categories;
}
// สร้างคอมเมนต์สำหรับ property - Generate property comment
generatePropertyComment(prop, objectName) {
const name = prop.name.toLowerCase();
// คอมเมนต์เฉพาะสำหรับ TOKEN_TYPES
if (objectName.includes('TOKEN')) {
if (name.includes('keyword')) return ' // คำหลัก';
if (name.includes('identifier')) return ' // ชื่อตัวแปร/ฟังก์ชัน';
if (name.includes('equals')) return ' // =';
if (name.includes('arrow')) return ' // =>';
if (name.includes('paren_open')) return ' // (';
if (name.includes('paren_close')) return ' // )';
if (name.includes('brace_open')) return ' // {';
if (name.includes('brace_close')) return ' // }';
if (name.includes('semicolon')) return ' // ;';
if (name.includes('comma')) return ' // ,';
if (name.includes('line_comment')) return ' // //';
if (name.includes('block_comment')) return ' // /* */';
if (name.includes('string')) return ' // สตริง';
if (name.includes('number')) return ' // ตัวเลข';
if (name.includes('whitespace')) return ' // ช่องว่าง';
if (name.includes('newline')) return ' // บรรทัดใหม่';
if (name.includes('eof')) return ' // จุดสิ้นสุดไฟล์';
}
return '';
}
// รับคอมเมนต์หมวดหมู่ - Get category comment
getCategoryComment(category) {
const categoryComments = {
keywords: 'คำหลัก - Keywords',
identifiers: 'ชื่อตัวแปร/ฟังก์ชัน - Identifiers',
operators: 'เครื่องหมาย - Operators and punctuation',
comments: 'คอมเมนต์ - Comments',
strings: 'สตริง - Strings',
numbers: 'ตัวเลข - Numbers',
whitespace: 'ช่องว่าง - Whitespace',
other: 'อื่นๆ - Others'
};
return categoryComments[category] || 'อื่นๆ - Others';
}
// หาคำอธิบายฟังก์ชันจากชื่อ - Get function description from name
getFunctionDescription(functionName, funcType = '') {
const name = functionName.toLowerCase();
const type = funcType.toLowerCase();
// ค้นหาคำที่ตรงกัน โดยพิจารณาประเภทด้วย
for (const [keyword, descriptions] of Object.entries(this.functionDescriptions)) {
if (keyword !== 'default' && name.includes(keyword)) {
// กรณีพิเศษ: ถ้าเป็นคลาสที่มีชื่อ node ให้เป็น "Node class" แทน "Node.js function"
if (keyword === 'node' && (type.includes('class') || type === 'class_declaration')) {
return {
english: 'Node class',
thai: 'คลาสโหนด'
};
}
// กรณีพิเศษ: tree + node = TreeNode class
if (name.includes('tree') && name.includes('node') && (type.includes('class') || type === 'class_declaration')) {
return {
english: 'TreeNode class',
thai: 'คลาสโหนดต้นไม้'
};
}
// กรณีพิเศษ: graph + node = GraphNode class
if (name.includes('graph') && name.includes('node') && (type.includes('class') || type === 'class_declaration')) {
return {
english: 'GraphNode class',
thai: 'คลาสโหนดกราฟ'
};
}
// สำหรับคลาส ให้เติม "class" เข้าไปใน description
if (type.includes('class') || type === 'class_declaration') {
const baseDesc = descriptions[0].toLowerCase();
if (!baseDesc.includes('class')) {
return {
english: `${descriptions[0]} class`,
thai: `คลาส${descriptions[1]}`
};
}
}
return {
english: descriptions[0],
thai: descriptions[1]
};
}
}
// ถ้าไม่พบ ใช้ default โดยพิจารณาประเภท
if (type.includes('class') || type === 'class_declaration') {
return {
english: `${functionName} class`,
thai: `คลาส ${functionName}`
};
}
const defaultDesc = this.functionDescriptions.default;
return {
english: `${defaultDesc[0]} ${functionName}`,
thai: `${defaultDesc[1]} ${functionName}`
};
}
// หาจุดเริ่มต้นที่แท้จริงของฟังก์ชัน (รวม decorators, exports, etc.)
findRealStartLine(lines, functionLine) {
let startLine = functionLine;
const originalLine = lines[functionLine];
if (!originalLine) {
// ถ้า functionLine ไม่ถูกต้อง ลองหาคลาส/ฟังก์ชันจากชื่อ
return functionLine; // คืนค่าเดิมแทนที่จะ return -1
}
// ตรวจสอบว่าบรรทัดปัจจุบันเป็นจุดเริ่มต้นที่เหมาะสมหรือไม่
const currentTrimmed = originalLine.trim();
// ถ้าเป็นส่วนท้ายของบล็อค หรือในกลางโค้ด ไม่ควรใส่คอมเมนต์
if (currentTrimmed === '}' ||
currentTrimmed === '});' ||
currentTrimmed === ');' ||
currentTrimmed.match(/^}\s*[,;]?\s*$/)) {
// แต่ถ้าเป็น function declaration ที่ถูกต้อง ให้ผ่าน
if (this.isValidStartLine(currentTrimmed)) {
return startLine;
}
// สำหรับกรณี line numbers ผิด ลองหาบรรทัดจริงจากเนื้อหา
return this.findAlternativeStartLine(lines, functionLine);
} // ตรวจสอบย้อนหลังเพื่อหา decorators, exports, หรือ annotations
for (let i = functionLine - 1; i >= Math.max(0, functionLine - 10); i--) {
const line = lines[i];
if (!line) continue;
const trimmed = line.trim();
// บรรทัดว่าง - ข้าม
if (trimmed === '') continue;
// Comment - ถ้าเป็นคอมเมนต์ของเราแล้ว หยุด
if (trimmed.startsWith('//') || trimmed.startsWith('/*')) {
if (trimmed.includes('======') || trimmed.includes('EN:') || trimmed.includes(':ชื่อ') || trimmed.includes(':คลาส') || trimmed.includes('class:')) {
break; // เจอคอมเมนต์ของเราแล้ว
}
continue;
}
// Decorators (@), exports, imports, type annotations
if (trimmed.startsWith('@') ||
trimmed.startsWith('export') ||
trimmed.startsWith('import') ||
trimmed.includes('interface ') ||
trimmed.includes('type ') ||
(trimmed.endsWith(',') && !trimmed.includes('{')) ||
(trimmed.endsWith(';') && !trimmed.includes('{'))) {
startLine = i;
continue;
}
// ถ้าเจอบรรทัดที่ไม่เกี่ยวข้อง หยุด
break;
}
return startLine;
}
// ตรวจสอบว่าบรรทัดนี้เหมาะสมที่จะเป็นจุดเริ่มต้นหรือไม่
isValidStartLine(trimmedLine) {
// รูปแบบที่เหมาะสมสำหรับการเริ่มต้น
const validPatterns = [
// JavaScript/TypeScript basic patterns
// ======================================================================
// EN: \ component
// TH: ส่วนประกอบ \
// ======================================================================
/^class\s+\w+/, // class declarations
/^abstract\s+class\s+\w+/, // abstract class declarations
/^interface\s+\w+/, // interface declarations
/^type\s+\w+\s*=/, // type alias declarations
/^enum\s+\w+/, // enum declarations
/^function\s+\w+/, // function declarations
/^async\s+function/, // async functions
/^function\*/, // generator functions
/^async\s+function\*/, // async generator functions
/^const\s+\w+\s*=/, // const declarations
/^let\s+\w+\s*=/, // let declarations
/^var\s+\w+\s*=/, // var declarations
/^\w+\s*:/, // object methods
/^\w+\s*\(/, // function calls (methods)
// Export patterns
/^export/, // exports
/^module\.exports/, // module exports
// Method patterns
/^static\s+\w+\s*\(/, // static methods
/^abstract\s+\w+\s*\(/, // abstract methods
/^public\s+\w+\s*\(/, // public methods
/^private\s+\w+\s*\(/, // private methods
/^protected\s+\w+\s*\(/, // protected methods
/^readonly\s+\w+\s*:/, // readonly properties
/^get\s+\w+\s*\(/, // getters
/^set\s+\w+\s*\(/, // setters
/^async\s+\w+\s*\(/, // async methods
// Generic patterns
/^class\s+\w+<[^>]+>/, // generic classes
/^interface\s+\w+<[^>]+>/, // generic interfaces
/^function\s+\w+<[^>]+>/, // generic functions
// Decorator patterns
/^@\w+/ // decorators
];
// ตรวจสอบว่าตรงกับรูปแบบใดรูปแบบหนึ่งหรือไม่
return validPatterns.some(pattern => pattern.test(trimmedLine));
}
// ตรวจสอบว่าตำแหน่งนี้เหมาะสมสำหรับการใส่คอมเมนต์หรือไม่
isAppropriateCommentLocation(lines, lineIndex) {
const currentLine = lines[lineIndex];
if (!currentLine) return false;
const trimmed = currentLine.trim();
// ข้าม zone header
if (lines[lineIndex].includes('=====') || lines[lineIndex].startsWith('// EN:') || lines[lineIndex].startsWith('// TH:')) {
return false;
}
// ===================================================================
// ENHANCED CONTEXT DETECTION SYSTEM v2.0
// ระบบตรวจจับบริบทที่เหมาะสมแบบขั้นสูง v2.0
// ===================================================================
// ไม่ควรใส่คอมเมนต์ที่ตำแหน่งเหล่านี้ (Only true inappropriate contexts)
const inappropriatePatterns = [
/^}\s*$/, // closing braces only
/^}\);?\s*$/, // closing function calls
/^};?\s*$/, // closing object/interface definitions - BUT CHECK CONTEXT
/^\);\s*$/, // closing parentheses
/^,\s*$/, // comma only
/^;\s*$/, // semicolon only
/^break;?\s*$/, // break statements
/^continue;?\s*$/, // continue statements
/^case\s/, // case statements
/^default:\s*$/, // default case
/^else\s*{?\s*$/, // else statements
/^catch\s*\(/, // catch blocks
/^finally\s*{?\s*$/, // finally blocks
/^\s*$|^$/, // empty lines
/^<\/\w+>/, // closing JSX tags
/^\/\*/, // already commented lines
/^\/\//, // already single-line commented
/^\s*\*+/, // continuation of block comments
/return\s/, // return statements
/app\.\w+/, // Express app calls
/\.map\(/, // array method calls
/\.find\(/, // array method calls
/\.filter\(/, // array method calls
/\.includes\(/, // string method calls
];
// ===================================================================
// SMART CONTEXT DETECTION: Check if this is actually a valid declaration
// การตรวจจับบริบทอัจฉริยะ: ตรวจสอบว่าเป็น declaration ที่ถูกต้องหรือไม่
// ===================================================================
// First Priority: Valid Declaration Patterns (allow these even if they match inappropriate patterns)
const validDeclarationPatterns = [
// TypeScript/JavaScript Declarations
/^(class|interface|enum|type)\s+\w+/, // TypeScript declarations
/^abstract\s+class\s+\w+/, // Abstract classes
/^(export\s+)?(default\s+)?(class|interface|type|enum|function|const|let|var)/, // Exports
/^(async\s+)?function\s+\w+/, // Function declarations
/^(const|let|var)\s+\w+\s*=\s*(\w+\s*=>\s*|async\s*\w*\s*=>\s*|\([^)]*\)\s*=>\s*)/, // Arrow functions
/^(const|let|var)\s+\w+\s*=/, // Variable declarations
/^(public|private|protected|static|async)\s+\w+/, // Class methods with modifiers
/^\w+\s*\([^)]*\)\s*\{/, // Method definitions
/^(get|set)\s+\w+/, // Getters/setters
/^@\w+/, // Decorators
// React/JSX Components
/^(const|let|var)\s+\w+\s*=\s*React\.forwardRef/, // React.forwardRef
/^(const|let|var)\s+\w+\s*=\s*React\.memo/, // React.memo
/^(const|let|var)\s+\w+\s*=\s*\([^)]*\)\s*=>\s*\{/, // React functional components
// TypeScript Advanced Patterns
/^namespace\s+\w+/, // Namespace declarations
/^module\s+\w+/, // Module declarations
/^declare\s+(global|module|namespace|class|interface|type|enum|function|var|let|const)/, // Declare statements
];
// Check if current line is a valid declaration - if yes, always allow
if (validDeclarationPatterns.some(pattern => pattern.test(trimmed))) {
return true;
}
// Now check inappropriate patterns (excluding method definitions)
const strictInappropriatePatterns = [
/^}\s*$/, // closing braces only
/^}\);?\s*$/, // closing function calls
/^\);\s*$/, // closing parentheses
/^,\s*$/, // comma only
/^;\s*$/, // semicolon only
/^break;?\s*$/, // break statements
/^continue;?\s*$/, // continue statements
/^case\s/, // case statements
/^default:\s*$/, // default case
/^else\s*{?\s*$/, // else statements
/^catch\s*\(/, // catch blocks
/^finally\s*{?\s*$/, // finally blocks
/^\s*$|^$/, // empty lines
/^<\/\w+>/, // closing JSX tags
/^\/\*/, // already commented lines
/^\/\//, // already single-line commented
/^\s*\*+/, // continuation of block comments
/return\s/, // return statements (in function body)
/app\.\w+/, // Express app calls
/\.map\(/, // array method calls
/\.find\(/, // array method calls
/\.filter\(/, // array method calls
/\.includes\(/, // string method calls
];
// ตรวจสอบบรรทัดปัจจุบันกับ strict patterns
if (strictInappropriatePatterns.some(pattern => pattern.test(trimmed))) {
return false;
}
// ===================================================================
// ENHANCED CONTEXT ANALYSIS: Advanced Pattern Matching
// การวิเคราะห์บริบทขั้นสูง: การจับคู่รูปแบบขั้นสูง
// ===================================================================
// Special handling for method definitions with parameters
const methodWithParametersPattern = /^(async\s+)?(\w+)\s*\([^)]*\)\s*\{/;
if (methodWithParametersPattern.test(trimmed)) {
// This is a method definition - check context to determine if appropriate
const contextAnalysis = this.analyzeMethodContext(lines, lineIndex);
return contextAnalysis.isAppropriateForComment;
}
// Special handling for closing braces that might be end of declarations
if (/^};?\s*$/.test(trimmed)) {
// Check if this is end of interface/type/class declaration
const declarationEndAnalysis = this.analyzeDeclarationEnd(lines, lineIndex);
return declarationEndAnalysis.isDeclarationEnd;
}
// ตรวจสอบบริบทรอบข้าง - นับ braces อย่างแม่นยำ
let braceBalance = 0;
let contextLevel = 0;
let lastDeclarationType = null;
// วิเคราะห์บริบทจากบรรทัดก่อนหน้า
for (let i = Math.max(0, lineIndex - 30); i < lineIndex; i++) {
const line = lines[i];
if (!line) continue;
const lineTrimmed = line.trim();
if (!lineTrimmed) continue;
// นับ braces
const openCount = (lineTrimmed.match(/\{/g) || []).length;
// ======================================================================
// EN: | component
// TH: ส่วนประกอบ |
// ======================================================================
const closeCount = (lineTrimmed.match(/\}/g) || []).length;
braceBalance += openCount - closeCount;
// ตรวจสอบ declaration level
if (lineTrimmed.match(/^(class|interface|function|const|let|var|export)/)) {
if (braceBalance === 0) {
contextLevel = 0; // top-level
} else if (braceBalance === 1) {
contextLevel = 1; // inside class/function
}
lastDeclarationType = lineTrimmed.match(/^(\w+)/)?.[1];
}
}
// กำหนดกฎการอนุญาต
// Level 0 (top-level): อนุญาตทุกอย่าง
if (contextLevel === 0) return true;
// Level 1 (inside class/function): อนุญาตเฉพาะ methods และ properties
if (contextLevel === 1 && lastDeclarationType === 'class') {
return this.isValidStartLine(trimmed);
}
// Level 2+ (deeply nested): ห้าม
if (braceBalance > 1) return false;
return false;
}
// ===================================================================
// ENHANCED CONTEXT ANALYSIS HELPERS
// ฟังก์ชันช่วยวิเคราะห์บริบทขั้นสูง
// ===================================================================
// วิเคราะห์บริบทของ method definition เพื่อตัดสินใจว่าควรใส่คอมเมนต์หรือไม่
// @param {Array} lines - บรรทัดทั้งหมดในไฟล์
// @param {number} lineIndex - index ของบรรทัดปัจจุบัน
// @returns {Object} ผลการวิเคราะห์บริบท
analyzeMethodContext(lines, lineIndex) {
const currentLine = lines[lineIndex].trim();
// Check for class context
let inClass = false;
let classLevel = 0;
let braceLevel = 0;
// Look backwards to find class context
for (let i = lineIndex - 1; i >= Math.max(0, lineIndex - 50); i--) {
const line = lines[i];
if (!line) continue;
const trimmed = line.trim();
// Count braces
const openCount = (trimmed.match(/\{/g) || []).length;
const closeCount = (trimmed.match(/\}/g) || []).length;
braceLevel += closeCount - openCount; // counting backwards
// Check for class declaration
if (/^(class|interface|abstract\s+class)\s+\w+/.test(trimmed) && braceLevel === 0) {
inClass = true;
classLevel = 0;
break;
}
// If we hit another function at same level, stop
if (/^(function|const\s+\w+\s*=|let\s+\w+\s*=|var\s+\w+\s*=)/.test(trimmed) && braceLevel === 0) {
break;
}
}
// Method in class context
if (inClass && braceLevel <= 1) {
return {
isAppropriateForComment: true,
context: 'class_method',
reason: 'Method definition within class context'
};
}
// Top-level function
if (braceLevel === 0) {
return {
isAppropriateForComment: true,
context: 'top_level_function',
reason: 'Top-level function definition'
};
}
// Nested function or implementation details
return {
isAppropriateForComment: false,
context: 'nested_implementation',
reason: 'Nested function in implementation details'
};
}
// วิเคราะห์ว่าวงเล็บปิด }; เป็นการจบ declaration หรือไม่
// @param {Array} lines - บรรทัดทั้งหมดในไฟล์
// @param {number} lineIndex - index ของบรรทัดปัจจุบัน
// @returns {Object} ผลการวิเคราะห์
analyzeDeclarationEnd(lines, lineIndex) {
// Look backwards to find what declaration this closing brace belongs to
let braceLevel = 1; // Start with 1 since we're at a closing brace
for (let i = lineIndex - 1; i >= Math.max(0, lineIndex - 100); i--) {
const line = lines[i];
if (!line) continue;
const trimmed = line.trim();
// Count braces
const openCount = (trimmed.match(/\{/g) || []).length;
const closeCount = (trimmed.match(/\}/g) || []).length;
braceLevel += closeCount - openCount; // counting backwards
// If we reach brace level 0, we found the opening declaration
if (braceLevel === 0) {
// Check if this line contains a declaration pattern
const declarationPatterns = [
/^(interface|type|enum|namespace|module)\s+\w+/,
/^(const|let|var)\s+\w+\s*=\s*\{/, // Object literal declarations
/^(export\s+)?(interface|type|enum)\s+\w+/,
];
const isDeclaration = declarationPatterns.some(pattern => pattern.test(trimmed));
return {
isDeclarationEnd: isDeclaration,
declarationType: isDeclaration ? trimmed.match(/^(\w+)/)?.[1] : null,
reason: isDeclaration ? 'End of type/interface/enum declaration' : 'End of implementation block'
};
}
}
return {
isDeclarationEnd: false,
declarationType: null,
reason: 'Cannot determine declaration context'
};
}
// หาบรรทัดเริ่มต้นทางเลือกเมื่อ line number ผิด
findAlternativeStartLine(lines, originalLine) {
// ถ้า line number ผิด ให้หาจากการค้นหาจริง
// คืนบรรทัดเดิมแล้วปล่อยให้ระบบจัดการ
console.log(` Warning: Line number might be incorrect for line ${originalLine}, using fallback`);
return Math.max(0, originalLine);
}
// สร้าง zone header - Generate zone header
generateZoneHeader(title, description) {
return '// ======================================================================\n' +
`// ${title}/${description}\n` +
'// ======================================================================\n';
}
// สร้างคอมเมนต์ที่จัดรูปแบบแล้วจาก smart comment
generateFormattedComment(smartComment, type) {
if (!smartComment || !smartComment.english || !smartComment.thai) {
return this.generateFunctionComment({ name: 'Unknown', type: type });
}
// ใช้ zone header format สำหรับทุกประเภทคอมเมนต์
return `// ======================================================================\n` +
`// EN: ${smartComment.english}\n` +
`// TH: ${smartComment.thai}\n` +
`// ======================================================================`;
}
}
// ======================================================================
// Smart Learning Functions/ฟังก์ชันเรียนรู้อัจฉริยะ
// ======================================================================
// วิเคราะห์ไฟล์ด้วยระบบ Smart Learning
// Analyze file with Smart Learning system
// @param {string} content - เนื้อหาไฟล์
// @param {Object} options - ตัวเลือกการวิเคราะห์
// @returns {Object} ผลการวิเคราะห์และ blueprint ของไฟล์
// ======================================================================
// EN: Create analyzeFileWithSmartLearning
// TH: สร้าง analyzeFileWithSmartLearning
// ======================================================================
function analyzeFileWithSmartLearning(content, options = {}) {
try {
console.log(' Starting Smart Learning Analysis...');
// สร้าง SmartFileAnalyzer instance
const analyzer = new SmartFileAnalyzer(content, options.security || {});
// วิเคราะห์ไฟล์และสร้าง blueprint
const blueprint = analyzer.analyzeFile();
if (!blueprint) {
console.log(' Smart Learning Analysis failed, falling back to traditional method');
return null;
}
// เรียกใช้ AI Intent Understanding Engine
console.log('\n เริ่มต้น AI Intent Understanding Engine...');
const intentReport = analyzer.getIntentAnalysisReport();
if (intentReport) {
console.log(` Business Logic: ${intentReport.summary.totalBusinessLogic} items`);
console.log(` Algorithms: ${intentReport.summary.totalAlgorithms} items`);
console.log(` Security Measures: ${intentReport.summary.totalSecurityMeasures} items`);
console.log(` Data Flows: ${intentReport.summary.totalDataFlows} items`);
console.log(` Smart Comments: ${intentReport.smartComments.length} generated`);
// เพิ่ม intent analysis ไปยัง blueprint
blueprint.intentAnalysis = intentReport;
}
// แสดงผลสรุปการวิเคราะห์
console.log('\n Smart Learning Results:');
console.log(` - Classes: ${blueprint.classes.size}`);
console.log(` - Functions: ${blueprint.functions.size}`);
console.log(` - Patterns: ${blueprint.patterns.size}`);
console.log(` - Keywords: ${blueprint.keywords.size}`);
console.log(` - File Type: ${blueprint.context.type}`);
console.log(` - Domain: ${blueprint.context.domain}`);
console.log(` - Complexity: ${blueprint.context.complexity}`);
return {
success: true,
blueprint: blueprint,
analyzer: analyzer
};
} catch (error) {
console.error(' Smart Learning Analysis Error:', error.message);
return null;
}
}
// สร้างคอมเมนต์อัจฉริยะจากข้อมูล blueprint
// Generate smart comment from blueprint data
// @param {string} functionName - ชื่อฟังก์ชันหรือคลาส
// @param {string} type - ประเภท (function, class, method)
// @param {Object} blueprint - ข้อมูล blueprint จาก SmartFileAnalyzer
// @param {Object} structureInfo - ข้อมูลโครงสร้างเพิ่มเติม
// @returns {Object} คอมเมนต์ที่สร้างขึ้น
// ======================================================================
// EN: Create generateSmartComment
// TH: สร้าง generateSmartComment
// ======================================================================
function generateSmartComment(functionName, type, blueprint, structureInfo = {}) {
try {
// ถ้าไม่มี blueprint ใช้วิธีเดิม
if (!blueprint) {
const generator = new CommentGenerator();
return generator.getFunctionDescription(functionName, type);
}
let comment = null;
// ===================================================================
// TypeScript Structures Support/รองรับโครงสร้าง TypeScript
// ===================================================================
// ตรวจสอบประเภท TypeScript เฉพาะ
if (type === 'interface') {
comment = generateInterfaceComment(functionName, blueprint, structureInfo);
} else if (type === 'type_alias') {
comment = generateTypeAliasComment(functionName, blueprint, structureInfo);
} else if (type === 'enum') {
comment = generateEnumComment(functionName, blueprint, structureInfo);
} else if (type === 'abstract_class') {
comment = generateAbstractClassComment(functionName, blueprint, structureInfo);
}
// ===================================================================
// Const Declarations Support/รองรับ const declarations
// ===================================================================
else if (['configuration', 'data_store', 'storage_config', 'rate_limiter', 'middleware', 'arrow_function', 'express_app', 'object', 'array', 'constant'].includes(type)) {
comment = generateConstComment(functionName, blueprint, structureInfo, type);
}
else if (type.includes('class') || type === 'class_declaration') {
comment = generateSmartClassComment(functionName, blueprint, structureInfo);
} else {
comment = generateSmartFunctionComment(functionName, blueprint, structureInfo);
} // ถ้าไม่สามารถสร้างคอมเมนต์อัจฉริยะได้ ใช้วิธีเดิม
if (!comment) {
console.log(` Falling back to traditional method for: ${functionName}`);
const generator = new CommentGenerator();
return generator.getFunctionDescription(functionName, type);
}
return comment;
} catch (error) {
console.error(` Smart Comment Generation Error for ${functionName}:`, error.message);
// ใช้วิธีเดิมเป็น fallback
const generator = new CommentGenerator();
return generator.getFunctionDescription(functionName, type);
}
}// สร้างคอมเมนต์อัจฉริยะสำหรับคลาส
// Generate smart comment for class
// ======================================================================
// EN: Process generateSmartClassComment
// TH: ประมวลผล generateSmartClassComment
// ======================================================================
function generateSmartClassComment(className, blueprint, structureInfo) {
const classInfo = blueprint.classes.get(className);
if (!classInfo) {
return null;
}
const context = blueprint.context;
let englishComment = '';
let thaiComment = '';
// สร้างคอมเมนต์ตามบริบทและวัตถุประสงค์ของคลาส
switch (classInfo.purpose) {
case 'manager':
if (context.domain === 'crypto') {
englishComment = `${className} - Security and cryptographic operations manager`;
thaiComment = `${className} - ตัวจัดการงานด้านความปลอดภัยและการเข้ารหัส`;
} else if (context.domain === 'data') {
englishComment = `${className} - Data management and processing manager`;
thaiComment = `${className} - ตัวจัดการข้อมูลและการประมวลผล`;
} else {
englishComment = `${className} - System operations manager`;
thaiComment = `${className} - ตัวจัดการการดำเนินงานระบบ`;
}
break;
case 'controller':
englishComment = `${className} - Application flow controller`;
thaiComment = `${className} - ตัวควบคุมการทำงานของแอปพลิเคชัน`;
break;
case 'service':
englishComment = `${className} - Business logic service provider`;
thaiComment = `${className} - ผู้ให้บริการตรรกะทางธุรกิจ`;
break;
case 'error':
englishComment = `${className} - Custom error handling class`;
thaiComment = `${className} - คลาสจัดการข้อผิดพลาดแบบกำหนดเอง`;
break;
case 'validator':
englishComment = `${className} - Data validation and verification`;
thaiComment = `${className} - การตรวจสอบและยืนยันข้อมูล`;
break;
default:
// ใช้บริบทไฟล์ในการสร้างคอมเมนต์
if (context.type === 'security') {
englishComment = `${className} - Security-related class`;
thaiComment = `${className} - คลาสที่เกี่ยวข้องกับความปลอดภัย`;
} else if (context.type === 'api') {
englishComment = `${className} - API-related class`;
thaiComment = `${className} - คลาสที่เกี่ยวข้องกับ API`;
} else if (context.type === 'database') {
englishComment = `${className} - Database-related class`;
thaiComment = `${className} - คลาสที่เกี่ยวข้องกับฐานข้อมูล`;
} else {
englishComment = `${className} class`;
thaiComment = `คลาส ${className}`;
}
}
return {
english: englishComment,
thai: thaiComment
};
}
// สร้างคอมเมนต์อัจฉริยะสำหรับฟังก์ชัน
// Generate smart comment for function
// ======================================================================
// EN: Create generateSmartFunctionComment
// TH: สร้าง generateSmartFunctionComment
// ======================================================================
function generateSmartFunctionComment(functionName, blueprint, structureInfo) {
// ค้นหาฟังก์ชันใน blueprint
let functionInfo = blueprint.functions.get(functionName);
// ถ้าไม่พบในฟังก์ชันระดับ global ลองหาใน class methods
if (!functionInfo) {
for (const classInfo of blueprint.classes.values()) {
const methodInfo = classInfo.methods.get(functionName);
if (methodInfo) {
functionInfo = {
...methodInfo,
parentClass: classInfo.name,
isMethod: true
};
break;
}
}
}
if (!functionInfo) {
return null;
}
const context = blueprint.context;
let englishComment = '';
let thaiComment = '';
// สร้างคอมเมนต์ตามวัตถุประสงค์และบริบท
switch (functionInfo.purpose) {
case 'generate_crypto':
englishComment = `Generate cryptographic ${functionName.toLowerCase().includes('key') ? 'key' : 'data'}`;
thaiComment = `สร้าง${functionName.toLowerCase().includes('key') ? 'คีย์' : 'ข้อมูล'}เข้ารหัส`;
break;
case 'encrypt_data':
englishComment = 'Encrypt sensitive data';
thaiComment = 'เข้ารหัสข้อมูลที่สำคัญ';
break;
case 'decrypt_data':
englishComment = 'Decrypt encrypted data';
thaiComment = 'ถอดรหัสข้อมูลที่เข้ารหัส';
break;
case 'get_size':
if (functionName.toLowerCase().includes('cache')) {
englishComment = 'Get current cache size';
thaiComment = 'ดึงขนาดแคชปัจจุบัน';
} else {
englishComment = 'Get size information';
thaiComment = 'ดึงข้อมูลขนาด';
}
break;
case 'set_limit':
if (functionName.toLowerCase().includes('cache')) {
englishComment = 'Set maximum cache limit';
thaiComment = 'กำหนดขีดจำกัดแคชสูงสุด';
} else {
englishComment = 'Set operational limit';
thaiComment = 'กำหนดขีดจำกัดการทำงาน';
}
break;
case 'clear_cache':
englishComment = 'Clear cache data';
thaiComment = 'ล้างข้อมูลแคช';
break;
case 'getter':
if (context.domain === 'crypto') {
englishComment = `Get ${functionName.replace(/^get/, '').toLowerCase()} value`;
thaiComment = `ดึงค่า ${functionName.replace(/^get/, '').toLowerCase()}`;
} else {
englishComment = `Get ${functionName.replace(/^get/, '').toLowerCase()}`;
thaiComment = `ดึง ${functionName.replace(/^get/, '').toLowerCase()}`;
}
break;
case 'setter':
let setterName = functionName
.replace(/^set([A-Z])/, '$1') // ลบ "set" และรักษาตัวพิมพ์ใหญ่
.replace(/([A-Z])/g, ' $1') // เพิ่ม space ก่อนตัวพิมพ์ใหญ่
.toLowerCase()
.trim();
englishComment = `Set ${setterName}`;
thaiComment = `กำหนด ${setterName}`;
break;
case 'creator':
let creatorName = functionName
.replace(/^create([A-Z])/, '$1') // ลบ "create" และรักษาตัวพิมพ์ใหญ่
.replace(/([A-Z])/g, ' $1') // เพิ่ม space ก่อนตัวพิมพ์ใหญ่
.toLowerCase()
.trim();
englishComment = `Create new ${creatorName}`;
thaiComment = `สร้าง ${creatorName} ใหม่`;
break;
case 'validator':
let validatorName = functionName
.replace(/^(validate|check|verify)([A-Z])/, '$2') // ลบ prefix และรักษาตัวพิมพ์ใหญ่
.replace(/([A-Z])/g, ' $1') // เพิ่ม space ก่อนตัวพิมพ์ใหญ่
.toLowerCase()
.trim();
englishComment = `Validate ${validatorName}`;
thaiComment = `ตรวจสอบ ${validatorName}`;
break;
case 'processor':
let processorName = functionName
.replace(/^(process|handle|execute)([A-Z])/, '$2') // ลบ prefix และรักษาตัวพิมพ์ใหญ่
.replace(/([A-Z])/g, ' $1') // เพิ่ม space ก่อนตัวพิมพ์ใหญ่
.toLowerCase()
.trim();
englishComment = `Process ${processorName}`;
thaiComment = `ประมวลผล ${processorName}`;
break;
case 'demo':
// แก้ไข regex ให้จัดการคำพิเศษก่อน
let cleanedName = functionName;
if (functionName === 'demonstrateAlgorithms') {
cleanedName = 'advanced algorithms and data structures';
} else if (functionName === 'demonstrateFeatures') {
cleanedName = 'system features';
} else {
// สำหรับชื่อทั่วไป ลบ prefix แล้วเพิ่ม space ก่อนตัวพิมพ์ใหญ่
cleanedName = functionName
.replace(/^(demo|test|example)([A-Z])/, '$2') // ลบ prefix และรักษาตัวพิมพ์ใหญ่
.replace(/([A-Z])/g, ' $1') // เพิ่ม space ก่อนตัวพิมพ์ใหญ่
.toLowerCase()
.trim();
}
englishComment = `Demonstration of ${cleanedName}`;
thaiComment = `การสาธิต ${cleanedName}`;
break;
default:
// ใช้บริบทไฟล์และชื่อฟังก์ชันในการสร้างคอมเมนต์
if (context.type === 'security' && functionName.toLowerCase().includes('key')) {
englishComment = 'Security key operation';
thaiComment = 'การดำเนินการด้านคีย์ความปลอดภัย';
} else if (context.type === 'api' && functionName.toLowerCase().includes('request')) {
englishComment = 'API request operation';
thaiComment = 'การดำเนินการคำขอ API';
} else {
// Fallback ไปที่วิธีเดิม
return null;
}
}
return {
english: englishComment,
thai: thaiComment
};
}
// ===================================================================
// TypeScript Comment Generators/ตัวสร้างคอมเมนต์ TypeScript
// ===================================================================
// สร้างคอมเมนต์สำหรับ Interface
function generateInterfaceComment(interfaceName, blueprint, structureInfo) {
const interfaceInfo = blueprint.classes.get(interfaceName);
if (!interfaceInfo) {
return null;
}
let englishComment = '';
let thaiComment = '';
switch (interfaceInfo.purpose) {
case 'configuration':
englishComment = `${interfaceName} - Configuration interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซการกำหนดค่า`;
break;
case 'result_type':
englishComment = `${interfaceName} - Result data structure`;
thaiComment = `${interfaceName} - โครงสร้างข้อมูลผลลัพธ์`;
break;
case 'input_type':
englishComment = `${interfaceName} - Input parameters interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซพารามิเตอร์นำเข้า`;
break;
case 'error_type':
englishComment = `${interfaceName} - Error information interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซข้อมูลข้อผิดพลาด`;
break;
case 'event_type':
englishComment = `${interfaceName} - Event data interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซข้อมูลเหตุการณ์`;
break;
case 'data_type':
englishComment = `${interfaceName} - Data model interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซโมเดลข้อมูล`;
break;
case 'service_interface':
englishComment = `${interfaceName} - Service contract interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซสัญญาการให้บริการ`;
break;
case 'repository_interface':
englishComment = `${interfaceName} - Repository pattern interface`;
thaiComment = `${interfaceName} - อินเทอร์เฟซรูปแบบพื้นที่เก็บข้อมูล`;
break;
default:
englishComment = `${interfaceName} - Interface definition`;
thaiComment = `${interfaceName} - นิยามอินเทอร์เฟซ`;
}
return {
english: englishComment,
thai: thaiComment
};
}
// สร้างคอมเมนต์สำหรับ Type Alias
// ======================================================================
// EN: Process generateTypeAliasComment
// TH: ประมวลผล generateTypeAliasComment
// ======================================================================
function generateTypeAliasComment(typeName, blueprint, structureInfo) {
const typeInfo = blueprint.functions.get(typeName);
if (!typeInfo) {
return null;
}
let englishComment = '';
let thaiComment = '';
switch (typeInfo.purpose) {
case 'callback_type':
englishComment = `${typeName} - Callback function type`;
thaiComment = `${typeName} - ประเภทฟังก์ชันเรียกกลับ`;
break;
case 'validation_type':
englishComment = `${typeName} - Validation rule type`;
thaiComment = `${typeName} - ประเภทกฎการตรวจสอบ`;
break;
case 'strategy_type':
englishComment = `${typeName} - Strategy pattern type`;
thaiComment = `${typeName} - ประเภทรูปแบบกลยุทธ์`;
break;
case 'string_union':
englishComment = `${typeName} - String union type`;
thaiComment = `${typeName} - ประเภทการรวมสตริง`;
break;
case 'number_union':
englishComment = `${typeName} - Number union type`;
thaiComment = `${typeName} - ประเภทการรวมตัวเลข`;
break;
case 'function_type':
englishComment = `${typeName} - Function signature type`;
thaiComment = `${typeName} - ประเภทลายเซ็นฟังก์ชัน`;
break;
case 'object_type':
englishComment = `${typeName} - Object structure type`;
thaiComment = `${typeName} - ประเภทโครงสร้างออบเจ็กต์`;
break;
default:
englishComment = `${typeName} - Type alias definition`;
thaiComment = `${typeName} - นิยามนามแฝงประเภท`;
}
return {
english: englishComment,
thai: thaiComment
};
}
// สร้างคอมเมนต์สำหรับ Enum
// ======================================================================
// EN: Process generateEnumComment
// TH: ประมวลผล generateEnumComment
// ======================================================================
function generateEnumComment(enumName, blueprint, structureInfo) {
const enumInfo = blueprint.classes.get(enumName);
if (!enumInfo) {
return null;
}
let englishComment = '';
let thaiComment = '';
switch (enumInfo.purpose) {
case 'status_enum':
englishComment = `${enumName} - Status enumeration`;
thaiComment = `${enumName} - การแจงนับสถานะ`;
break;
case 'type_enum':
englishComment = `${enumName} - Type enumeration`;
thaiComment = `${enumName} - การแจงนับประเภท`;
break;
case 'level_enum':
englishComment = `${enumName} - Level enumeration`;
thaiComment = `${enumName} - การแจงนับระดับ`;
break;
case 'direction_enum':
englishComment = `${enumName} - Direction enumeration`;
thaiComment = `${enumName} - การแจงนับทิศทาง`;
break;
case 'mode_enum':
englishComment = `${enumName} - Mode enumeration`;
thaiComment = `${enumName} - การแจงนับโหมด`;
break;
default:
englishComment = `${enumName} - Enumeration values`;
thaiComment = `${enumName} - ค่าการแจงนับ`;
}
return {
english: englishComment,
thai: thaiComment
};
}
// สร้างคอมเมนต์สำหรับ Abstract Class
// ======================================================================
// EN: Process generateAbstractClassComment
// TH: ประมวลผล generateAbstractClassComment
// ======================================================================
function generateAbstractClassComment(className, blueprint, structureInfo) {
const classInfo = blueprint.classes.get(className);
if (!classInfo) {
return null;
}
let englishComment = '';
let thaiComment = '';
switch (classInfo.purpose) {
case 'base_class':
englishComment = `${className} - Abstract base class`;
thaiComment = `${className} - คลาสฐานนามธรรม`;
break;
case 'repository_base':
englishComment = `${className} - Abstract repository base class`;
thaiComment = `${className} - คลาสฐานพื้นที่เก็บข้อมูลนามธรรม`;
break;
case 'service_base':
englishComment = `${className} - Abstract service base class`;
thaiComment = `${className} - คลาสฐานบริการนามธรรม`;
break;
case 'controller_base':
englishComment = `${className} - Abstract controller base class`;
thaiComment = `${className} - คลาสฐานตัวควบคุมนามธรรม`;
break;
case 'component_base':
englishComment = `${className} - Abstract component base class`;
thaiComment = `${className} - คลาสฐานส่วนประกอบนามธรรม`;
break;
default:
englishComment = `${className} - Abstract class definition`;
thaiComment = `${className} - นิยามคลาสนามธรรม`;
}
return {
english: englishComment,
thai: thaiComment
};
}
// สร้างคอมเมนต์สำหรับ Const Declaration
// ======================================================================
// EN: Process generateConstComment
// TH: ประมวลผล generateConstComment
// ======================================================================
function generateConstComment(constName, blueprint, structureInfo, constType) {
// หาข้อมูลจาก blueprint
let constInfo = blueprint.classes.get(constName) || blueprint.functions.get(constName);
if (!constInfo) {
return null;
}
let englishComment = '';
let thaiComment = '';
switch (constType) {
case 'configuration':
englishComment = `${constName} - Application configuration settings`;
thaiComment = `${constName} - การกำหนดค่าแอปพลิเคชัน`;
break;
case 'data_store':
englishComment = `${constName} - In-memory data storage`;
thaiComment = `${constName} - ที่เก็บข้อมูลในหน่วยความจำ`;
break;
case 'storage_config':
englishComment = `${constName} - File upload storage configuration`;
thaiComment = `${constName} - การกำหนดค่าการจัดเก็บไฟล์อัปโหลด`;
break;
case 'rate_limiter':
if (constName.toLowerCase().includes('auth')) {
englishComment = `${constName} - Authentication rate limiting middleware`;
thaiComment = `${constName} - มิดเดิลแวร์จำกัดอัตราการรับรองตัวตน`;
} else {
englishComment = `${constName} - API rate limiting middleware`;
thaiComment = `${constName} - มิดเดิลแวร์จำกัดอัตรา API`;
}
break;
case 'middleware':
if (constInfo.purpose === 'auth_middleware') {
englishComment = `${constName} - Authentication middleware function`;
thaiComment = `${constName} - ฟังก์ชันมิดเดิลแวร์การรับรองตัวตน`;
} else if (constInfo.purpose === 'validation_middleware') {
englishComment = `${constName} - Request validation middleware function`;
thaiComment = `${constName} - ฟังก์ชันมิดเดิลแวร์ตรวจสอบคำขอ`;
} else if (constInfo.purpose === 'async_wrapper') {
englishComment = `${constName} - Async error handling wrapper`;
thaiComment = `${constName} - ตัวห่อหุ้มจัดการข้อผิดพลาดแบบ async`;
} else {
englishComment = `${constName} - Express middleware function`;
thaiComment = `${constName} - ฟังก์ชันมิดเดิลแวร์ Express`;
}
break;
case 'arrow_function':
if (constInfo.purpose === 'finder_function') {
englishComment = `${constName} - Data finder utility function`;
thaiComment = `${constName} - ฟังก์ชันยูทิลิตี้ค้นหาข้อมูล`;
} else if (constInfo.purpose === 'generator_function') {
englishComment = `${constName} - ID generator utility function`;
thaiComment = `${constName} - ฟังก์ชันยูทิลิตี้สร้าง ID`;
} else {
englishComment = `${constName} - Utility function`;
thaiComment = `${constName} - ฟังก์ชันยูทิลิตี้`;
}
break;
case 'express_app':
englishComment = `${constName} - Express application instance`;
thaiComment = `${constName} - อินสแตนซ์แอปพลิเคชัน Express`;
break;
case 'object':
englishComment = `${constName} - Configuration object`;
thaiComment = `${constName} - ออบเจ็กต์การกำหนดค่า`;
break;
case 'array':
englishComment = `${constName} - Data array`;
thaiComment = `${constName} - อาร์เรย์ข้อมูล`;
break;
default:
englishComment = `${constName} - Constant definition`;
thaiComment = `${constName} - นิยามค่าคงที่`;
}
return {
english: englishComment,
thai: thaiComment
};
}
// ======================================================================
// Main Comment Processing Engine/เครื่องมือประมวลผลคอมเมนต์หลัก
// ======================================================================
// ======================================================================
// Process file/ประมวลผลไฟล์
// ======================================================================
function processFile(filePath, options = {}) {
const startTime = Date.now();
try {
// เริ่มต้น logging
logger.debug('FILE_PROCESSING', `Starting to process file: ${filePath}`, {
options: options,
startTime: new Date().toISOString()
});
// SECURITY: File Size Limit Protection (DoS Prevention)
const stat = fs.statSync(filePath);
const fileSizeInMB = stat.size / (1024 * 1024);
const maxSizeInMB = 10; // กำหนด limit ที่ 10MB ตามที่ระบุใน help
if (fileSizeInMB > maxSizeInMB) {
if (options.verbose) {
console.warn(` Skipping large file: ${filePath} (${fileSizeInMB.toFixed(2)} MB > ${maxSizeInMB} MB limit)`);
}
return {
success: true,
changes: false,
skipped: true,
reason: `File too large (${fileSizeInMB.toFixed(2)} MB)`,
statistics: {
totalStructures: 0,
detectedStructures: 0,
missedStructures: 0,
skippedStructures: 0,
inappropriateContexts: 0,
lineNumberCorrections: 0,
commentsAdded: 0,
errorDetails: []
}
};
}
// SECURITY: Symbolic Link Protection
if (stat.isSymbolicLink()) {
if (options.verbose) {
console.warn(` Skipping symbolic link: ${filePath} (security protection)`);
}
return {
success: true,
changes: false,
skipped: true,
reason: 'Symbolic link protection',
statistics: {
totalStructures: 0,
detectedStructures: 0,
missedStructures: 0,
skippedStructures: 0,
inappropriateContexts: 0,
lineNumberCorrections: 0,
commentsAdded: 0,
errorDetails: []
}
};
}
// อ่านไฟล์
const content = fs.readFileSync(filePath, 'utf8');
// สร้าง backup ถ้าต้องการ
if (options.backup) {
logger.debug('BACKUP', `Creating backup for: ${filePath}`);
createBackup(filePath);
}
// ประมวลผลเนื้อหา
let processedContent = content;
let fileStatistics = null;
// ตรวจสอบโหมดการทำงาน
if (options.removeComments) {
// โหมดลบคอมเมนต์
processedContent = removeComments(processedContent);
} else {
// โหมดปกติ: เพิ่ม/แก้ไขคอมเมนต์
// 1. แปลง comments เป็น // format
processedContent = fixComments(processedContent);
// 2. ใช้ tokenizer เพื่อหาฟังก์ชันและเพิ่มคอมเมนต์
if (options.addMissing || options.aiMode) {
const result = addMissingComments(processedContent, options);
processedContent = result.processedContent;
fileStatistics = result.statistics;
}
}
// สร้าง default statistics ถ้ายังไม่มี
if (!fileStatistics) {
fileStatistics = {
totalStructures: 0,
detectedStructures: 0,
missedStructures: 0,
skippedStructures: 0,
inappropriateContexts: 0,
lineNumberCorrections: 0,
commentsAdded: 0,
errorDetails: []
};
}
// 3. จัดระเบียบ zones ถ้าต้องการ
if (options.organizeZones) {
processedContent = organizeCodeByZones(processedContent);
}
// 4. File Comparison & Detailed Analysis (ใช้ระบบอ่านไฟล์ 2 ตัวที่มีอยู่)
let comparisonReport = null;
if (content !== processedContent) {
comparisonReport = fileComparisonAnalyzer.compareAndAnalyze(
content, // ไฟล์ต้นฉบับ
processedContent, // ไฟล์หลังแก้ไข
filePath
);
// อัพเดท statistics จาก comparison report
if (comparisonReport && fileStatistics) {
fileStatistics.comparisonAnalysis = {
structuresSkipped: comparisonReport.changes.structuresSkipped,
skippedFunctions: comparisonReport.skippedStructures.functions,
skippedClasses: comparisonReport.skippedStructures.classes,
totalOriginalStructures: comparisonReport.original.totalStructures,
totalModifiedStructures: comparisonReport.modified.totalStructures
};
}
}
// เขียนไฟล์กลับ (ถ้าไม่ใช่ dry-run)
if (!options.dryRun) {
fs.writeFileSync(filePath, processedContent, 'utf8');
logger.audit('FILE_MODIFIED', filePath, {
originalSize: content.length,
newSize: processedContent.length,
commentsAdded: fileStatistics?.commentsAdded || 0,
comparisonReport: comparisonReport ? {
structuresSkipped: comparisonReport.changes.structuresSkipped,
functionsSkipped: comparisonReport.skippedStructures.functions.length,
classesSkipped: comparisonReport.skippedStructures.classes.length
} : null
});
}
// Performance logging
const duration = Date.now() - startTime;
logger.performance('FILE_PROCESSING', duration, {
filePath: filePath,
originalSize: content.length,
newSize: processedContent.length,
changes: content !== processedContent,
statistics: fileStatistics
});
// Success logging
logger.debug('FILE_PROCESSING', `Successfully processed: ${filePath}`, {
changes: content !== processedContent,
duration: duration,
statistics: fileStatistics
});
return {
success: true,
originalSize: content.length,
newSize: processedContent.length,
changes: content !== processedContent,
preview: options.dryRun ? processedContent : null,
statistics: fileStatistics
};
} catch (error) {
const duration = Date.now() - startTime;
// Error logging
logger.error('FILE_PROCESSING', `Failed to process file: ${filePath}`, error, {
duration: duration,
options: options
});
console.error(`Error processing file ${filePath}: ${error.message}`);
return {
success: false,
error: error.message,
statistics: {
totalStructures: 0,
detectedStructures: 0,
missedStructures: 0,
skippedStructures: 0,
inappropriateContexts: 0,
lineNumberCorrections: 0,
commentsAdded: 0,
errorDetails: [{
file: filePath,
type: 'file_processing_error',
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
}]
}
};
}
}
// ======================================================================
// Remove comments/ลบคอมเมนต์
// ======================================================================
function removeComments(content) {
try {
let result = content;
// ป้องกันการลบ comment ที่อยู่ใน string หรือ regex
const protectedStrings = [];
let stringIndex = 0;
// เก็บ strings และ regex patterns ไว้ก่อน
result = result.replace(/(["'`])(?:(?!\1)[^\\]|\\.)*\1|\/(?:[^\/\\]|\\.)+\/[gimuy]*/g, (match) => {
const placeholder = `__PROTECTED_STRING_${stringIndex}__`;
protectedStrings[stringIndex] = match;
stringIndex++;
return placeholder;
});
// 1. ลบ single-line comments (// แต่อย่าลบ URLs หรือ file paths)
result = result.replace(/(?<!:)\/\/(?!\/).*$/gm, '');
// 2. ลบ multi-line comments (/* */ และ )
result = result.replace(/\/\*[\s\S]*?\*\//g, '');
// คืน strings และ regex patterns กลับ
for (let i = 0; i < protectedStrings.length; i++) {
result = result.replace(`__PROTECTED_STRING_${i}__`, protectedStrings[i]);
}
// 3. ลบบรรทัดว่างที่เหลือจากการลบคอมเมนต์
result = result.replace(/^\s*[\r\n]/gm, '');
// 4. ลบบรรทัดว่างที่ซ้ำกัน (เหลือแค่ 1 บรรทัดว่าง)
result = result.replace(/\n\s*\n\s*\n/g, '\n\n');
// 5. ทำความสะอาดช่องว่างท้ายบรรทัด
result = result.replace(/[ \t]+$/gm, '');
return result;
} catch (error) {
console.warn('Warning: Error removing comments, returning original content');
return content;
}
}
// ======================================================================
// Fix comments/แก้ไขคอมเมนต์
// ======================================================================
function fixComments(content) {
// แปลง comments ที่มีหลายบรรทัด
content = content.replace(/\/\*\*[\s\S]*?\*\//g, (match) => {
// แยกบรรทัดและลบ * ออก
const lines = match.split('\n');
const convertedLines = [];
for (let line of lines) {
// ลบ // และ และ * ที่ขึ้นต้น
line = line.replace(/^\s*\/\*\*\s*/, '').replace(/\s*\*\/\s*$/, '').replace(/^\s*\*\s*/, '').trim();
if (line) {
convertedLines.push(`// ${line}`);
}
}
return convertedLines.join('\n');
});
return content;
}
// ======================================================================
// Add missing comments - เวอร์ชัน FINAL ที่สะอาดและแม่นยำที่สุด
// ======================================================================
function addMissingComments(content, options = {}) {
try {
const statistics = { totalStructures: 0, detectedStructures: 0, missedStructures: 0,
skippedStructures: 0, inappropriateContexts: 0, lineNumberCorrections: 0,
commentsAdded: 0, errorDetails: [] };
const tokenizer = new JavaScriptTokenizer(content, { maxDepth: 50, maxTokens: 100000, maxParsingTime: 15000 });
const tokens = tokenizer.tokenize();
// ใช้ StateMachine v5.2
const parser = new StateMachineStructureParser(tokens, content);
const parsed = parser.parse();
let structures = [
...parsed.functions, ...parsed.classes, ...parsed.methods,
...parsed.arrowFunctions, ...parsed.reactComponents,
...parsed.interfaces, ...parsed.typeAliases, ...parsed.enums
];
statistics.detectedStructures = structures.length;
if (options.verbose) console.log(` [StateMachine v5.2 FINAL] Detected ${structures.length} structures`);
if (structures.length === 0) return { processedContent: content, statistics };
const allItems = [...structures];
const missingElements = detectMissingElements(content, allItems);
// Line correction
missingElements.forEach(el => {
if (el.type.includes('correction')) {
const item = allItems.find(i => i.name === el.name);
if (item) item.line = el.line;
statistics.lineNumberCorrections++;
}
});
const generator = new CommentGenerator();
const commentStatusMap = analyzeCommentStatus(content, structures);
let lines = normalizeLineEndings(content).split('\n');
let processedLines = [...lines];
// เรียงจากล่างขึ้นบน
allItems.sort((a, b) => b.line - a.line);
allItems.forEach(item => {
let lineIndex = item.line - 1;
if (lineIndex < 0 || lineIndex >= processedLines.length) return;
// === สำคัญ: ข้าม zone header เก่า ===
while (lineIndex > 0 && processedLines[lineIndex].includes('=====')) {
lineIndex--;
}
// ตรวจสอบว่ามี comment อยู่ด้านบนแล้วหรือไม่
if (commentStatusMap.get(item.name)?.hasComment) return;
const realStart = generator.findRealStartLine(processedLines, lineIndex);
if (realStart === -1) {
statistics.skippedStructures++;
return;
}
// สร้างคอมเมนต์
const comment = generator.generateFunctionComment(item);
const indent = processedLines[realStart].match(/^\s*/)[0];
const indentedComment = comment.split('\n').map(l => indent + l);
processedLines.splice(realStart, 0, ...indentedComment);
statistics.commentsAdded++;
});
return { processedContent: processedLines.join('\n'), statistics };
} catch (e) {
console.error('addMissingComments error:', e.message);
return { processedContent: content, statistics: { commentsAdded: 0, errorDetails: [e.message] } };
}
}
// ฟังก์ชันช่วยเหลือสำหรับหา methods ที่ tokenizer อาจพลาด
function findMethodsWithRegex(content) {
const methods = [];
const lines = content.split('\n');
lines.forEach((line, index) => {
const trimmed = line.trim();
// รูปแบบ method ต่างๆ ที่อาจถูกพลาด
const patterns = [
/^\s*(\w+)\s*\(\s*[^)]*\)\s*\{/, // methodName() {
/^\s*async\s+(\w+)\s*\(\s*[^)]*\)\s*\{/, // async methodName() {
/^\s*static\s+(\w+)\s*\(\s*[^)]*\)\s*\{/, // static methodName() {
/^\s*get\s+(\w+)\s*\(\s*[^)]*\)\s*\{/, // get propertyName() {
/^\s*set\s+(\w+)\s*\(\s*[^)]*\)\s*\{/, // set propertyName() {
];
for (const pattern of patterns) {
const match = trimmed.match(pattern);
if (match && match[1]) {
const methodName = match[1];
// กรอง keywords และ built-in functions
const excludedNames = [
'constructor', 'super', 'this', 'new', 'Map', 'Set', 'Array', 'Object', 'Promise',
'console', 'Math', 'JSON', 'Date', 'String', 'Number', 'Boolean', 'Error',
'require', 'module', 'exports', 'process', 'Buffer', 'setTimeout', 'setInterval',
'function', 'return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue'
];
if (!excludedNames.includes(methodName) && methodName !== '*') {
// ตรวจสอบว่าอยู่ในคลาสหรือไม่โดยดูบริบทรอบข้าง
let inClass = false;
for (let i = Math.max(0, index - 20); i < index; i++) {
if (lines[i] && lines[i].includes('class ')) {
let braceCount = 0;
for (let j = i; j <= index; j++) {
const testLine = lines[j] || '';
braceCount += (testLine.match(/\{/g) || []).length;
braceCount -= (testLine.match(/\}/g) || []).length;
}
if (braceCount > 0) {
inClass = true;
break;
}
}
}
if (inClass) {
// กำหนดประเภท
let type = 'class_method';
if (trimmed.includes('async ')) type = 'async_class_method';
else if (trimmed.includes('static ')) type = 'static_method';
else if (trimmed.includes('get ')) type = 'getter';
else if (trimmed.includes('set ')) type = 'setter';
methods.push({
type: type,
name: methodName,
line: index + 1,
column: trimmed.indexOf(methodName),
parameters: [],
isAsync: trimmed.includes('async '),
fromRegex: true
});
}
}
}
}
});
return methods;
}
// ======================================================================
// Create backup/สร้างไฟล์สำรอง
// ======================================================================
function createBackup(filePath) {
try {
// ใช้ระบบ Organized Backup Manager ใหม่
return backupManager.createBackup(filePath);
} catch (error) {
logger.error('BACKUP', `Failed to create backup for ${filePath}`, error);
console.error(`Error creating backup: ${error.message}`);
return null;
}
}
// ======================================================================
// Organize code by zones/จัดระเบียบโค้ดตามโซน
// ======================================================================
function organizeCodeByZones(content) {
// Simple zone organization - can be enhanced
const generator = new CommentGenerator();
// เพิ่ม zone headers ที่จุดสำคัญ
let organized = content;
// เพิ่ม main zone header ที่ต้นไฟล์ถ้ายังไม่มี
if (!content.includes('╔═') && !content.includes('Zone')) {
const header = generator.generateZoneHeader(
'Main Application Zone',
'Core functionality and business logic'
);
organized = header + '\n' + organized;
}
return organized;
}
// ======================================================================
// CLI Interface & Options/อินเตอร์เฟซบรรทัดคำสั่งและตัวเลือก
// ======================================================================
// ======================================================================
// Show help message/แสดงข้อความช่วยเหลือ
// ======================================================================
function showHelp() {
console.log(`
╔══════════════════════════════════════════════════════════════════════════════════╗
║ Universal Comment Fixer Tool v3.0.1-beta ║
║ Professional Comment Standardization for JS/TS Projects ║
║ FINAL BETA - No more beta updates after this ║
╚══════════════════════════════════════════════════════════════════════════════════╝
USAGE:
fix-comments [target] [options]
TARGETS:
[file] Process single file
[directory] Process all files in directory
. Process current directory
OPTIONS:
-d, --dry-run Preview changes without modifying files
-v, --verbose Show detailed processing information
-b, --backup Create backup before making changes
-r, --recursive Process all files in subdirectories
--add-missing Add comments to functions without comments
--ai-mode AI-friendly mode (add @function, @description)
--organize-zones Organize code into logical zones
--format Format code beautifully (Code Magician mode)
-s, --smart-learning Enable AI Intent Understanding Engine
--ext <list> Specify file extensions (comma-separated)
-h, --help Show this help message
--version Show version information
EXAMPLES:
fix-comments app.js # Fix single file
fix-comments ./src --backup # Fix directory with backup
fix-comments . -r --add-missing # Recursive with missing comments
fix-comments ./src --ai-mode --verbose # AI-friendly with details
fix-comments . --dry-run # Preview changes only
fix-comments messy-code.js --format # Format messy code beautifully
fix-comments ./src --format -r # Format all files recursively
SUPPORTED FILES:
.js, .ts, .jsx, .tsx - JavaScript/TypeScript files
SECURITY FEATURES:
- Path Traversal Protection: Prevents ../../../etc/passwd attacks
- File Size Limits: 10MB maximum to prevent DoS attacks
- Parsing Timeout: 30-second maximum to prevent infinite loops
- Depth Limits: 100-level maximum nesting to prevent complexity attacks
- Extension Validation: Only valid file extensions accepted
- System Directory Blacklist: Blocks access to sensitive system paths
- Working Directory Enforcement: All operations within project scope
SECURITY WARNINGS:
Run this tool only within your project directories
Avoid running in Home directory or system directories
Tool has built-in protection but exercise caution
Review changes before committing to version control
FINAL BETA RELEASE NOTES:
This is the LAST BETA VERSION - Next release: v1.0.0 Production Ready (Q1 2026)
Current users can continue using this version normally
No more beta version updates will be released
Known Issues (Final Beta):
• Complex TypeScript interface chains may need manual review
• Arrow functions with complex destructuring might generate warnings
• JSX components with conditional rendering require additional validation
Final Beta Guidelines:
• Always use --backup flag for safety
• Try --dry-run first to preview changes
• Report issues with minimal reproducible code samples
• Check diagnostic.log for detailed analysis
Issues & Documentation: https://github.com/chahuadev/chahuadev-fix-comments
`);
}
// ======================================================================
// Show version/แสดงเวอร์ชัน
// ======================================================================
function showVersion() {
console.log('Universal Comment Fixer Tool v3.0.1-beta');
console.log('Professional Comment Standardization Tool for JavaScript/TypeScript Projects');
console.log(' FINAL BETA RELEASE - No more beta updates after this version');
console.log('Copyright (c) 2025 Chahua Development Co., Ltd.');
console.log('');
console.log(' Next Release: v1.0.0 Production Ready (Q1 2026)');
console.log(' Current users can continue using this version normally');
console.log('');
console.log(' Known Issues in Final Beta:');
console.log(' • Complex TypeScript interface chains may need manual review');
console.log(' • Arrow functions with complex destructuring might generate warnings');
console.log(' • JSX components with conditional rendering require additional validation');
console.log('');
console.log(' Report issues with code samples at:');
console.log(' https://github.com/chahuadev/chahuadev-fix-comments/issues');
}
// ======================================================================
// Process directory/ประมวลผลไดเรกทอรี
// ======================================================================
function processDirectory(dirPath, options = {}) {
const extensions = options.extensions || ['.js', '.ts', '.jsx', '.tsx'];
const results = {
total: 0,
processed: 0,
errors: 0,
files: [],
// เพิ่มสถิติรายละเอียด
statistics: {
totalStructures: 0,
detectedStructures: 0,
missedStructures: 0,
skippedStructures: 0,
inappropriateContexts: 0,
lineNumberCorrections: 0,
commentsAdded: 0,
errorDetails: []
}
};
try {
const files = fs.readdirSync(dirPath);
for (const file of files) {
const filePath = path.join(dirPath, file);
// SECURITY: Check if it's a symbolic link first
const lstat = fs.lstatSync(filePath);
if (lstat.isSymbolicLink()) {
if (options.verbose) {
console.warn(` Skipping symbolic link: ${filePath} (circular reference protection)`);
}
continue; // ข้าม symbolic link เพื่อป้องกัน infinite loop
}
const stat = fs.statSync(filePath);
if (stat.isDirectory() && options.recursive) {
// SECURITY: Enhanced system directory protection
const secureSkipDirs = [
'node_modules', '.git', 'dist', 'build', '.chahuadev-fix-comments-backups',
'.npm', '.cache', '.vscode', '.idea', 'coverage', 'logs', 'tmp', 'temp',
'System32', 'etc', 'proc', 'sys', 'Windows', 'Program Files', 'Users',
'.ssh', '.aws', '.config', '.docker'
];
if (secureSkipDirs.some(skipDir => file.toLowerCase().includes(skipDir.toLowerCase()))) {
if (options.verbose) {
console.warn(` Skipping protected directory: ${filePath}`);
}
continue;
}
// ประมวลผลโฟลเดอร์ย่อย
const subResults = processDirectory(filePath, options);
results.total += subResults.total;
results.processed += subResults.processed;
results.errors += subResults.errors;
results.files.push(...subResults.files);
// รวมสถิติรายละเอียด
if (subResults.statistics) {
results.statistics.totalStructures += subResults.statistics.totalStructures;
results.statistics.detectedStructures += subResults.statistics.detectedStructures;
results.statistics.missedStructures += subResults.statistics.missedStructures;
results.statistics.skippedStructures += subResults.statistics.skippedStructures;
results.statistics.inappropriateContexts += subResults.statistics.inappropriateContexts;
results.statistics.lineNumberCorrections += subResults.statistics.lineNumberCorrections;
results.statistics.commentsAdded += subResults.statistics.commentsAdded;
results.statistics.errorDetails.push(...subResults.statistics.errorDetails);
}
} else if (stat.isFile()) {
const ext = path.extname(file);
if (extensions.includes(ext)) {
results.total++;
if (options.verbose) {
console.log(`Processing: ${filePath}`);
}
const result = processFile(filePath, options);
if (result.success) {
results.processed++;
if (result.changes || options.dryRun) {
results.files.push({
path: filePath,
changes: result.changes,
originalSize: result.originalSize,
newSize: result.newSize
});
}
// รวมสถิติรายละเอียด
if (result.statistics) {
results.statistics.totalStructures += result.statistics.totalStructures;
results.statistics.detectedStructures += result.statistics.detectedStructures;
results.statistics.missedStructures += result.statistics.missedStructures;
results.statistics.skippedStructures += result.statistics.skippedStructures;
results.statistics.inappropriateContexts += result.statistics.inappropriateContexts;
results.statistics.lineNumberCorrections += result.statistics.lineNumberCorrections;
results.statistics.commentsAdded += result.statistics.commentsAdded;
if (result.statistics.errorDetails) {
results.statistics.errorDetails.push(...result.statistics.errorDetails);
}
}
} else {
results.errors++;
console.error(`Error processing ${filePath}: ${result.error}`);
// เพิ่ม error ลง statistics
results.statistics.errorDetails.push({
file: filePath,
type: 'processing_error',
message: result.error,
timestamp: new Date().toISOString()
});
}
}
}
}
} catch (error) {
console.error(`Error reading directory ${dirPath}: ${error.message}`);
results.errors++;
}
return results;
}
// ======================================================================
// Main function/ฟังก์ชันหลัก
// ======================================================================
// ======================================================================
// Code Formatter Engine/เครื่องมือจัดรูปแบบโค้ด
// ======================================================================
//
// Code Formatter - เครื่องมือจัดรูปแบบโค้ดให้สวยงาม
// ทำงานร่วมกับ StructureParser เพื่อ rewrite โค้ดในรูปแบบที่สวยงาม
//
// จัดรูปแบบโค้ดให้สวยงาม - Professional Surgeon v3.0
// ใช้หลักการ "วินิจฉัยก่อน จึงลงมือ" เหมือนศัลยแพทย์
function formatCode(content, options = {}) {
try {
// ========================================================================
// PHASE 1: CODE HEALTH DIAGNOSIS/การวินิจฉัยสุขภาพโค้ด
// ========================================================================
console.log('Starting Code Health Diagnosis...');
const healthCheck = performCodeHealthCheck(content);
if (!healthCheck.isHealthy) {
console.error('CODE HEALTH CHECK FAILED:');
console.error(` Syntax Error detected at line ${healthCheck.errorLine}, column ${healthCheck.errorColumn}`);
console.error(` Error: ${healthCheck.errorMessage}`);
console.error(' OPERATION ABORTED: Cannot format unhealthy code.');
console.error(' Please fix syntax errors first, then try again.');
// Return original content with diagnostic info
return content + `\n\n// WARNING: FORMATTING ABORTED: Syntax Error at line ${healthCheck.errorLine}\n// ${healthCheck.errorMessage}`;
}
console.log('Code Health Check PASSED - Patient is ready for surgery');
console.log(` Analysis: ${healthCheck.stats.functions} functions, ${healthCheck.stats.classes} classes, ${healthCheck.stats.complexity} complexity`);
// ========================================================================
// PHASE 1.5: AI INTENT UNDERSTANDING (if enabled)
// ========================================================================
if (options.enableSmartLearning) {
console.log('\n Phase 1.5: AI Intent Understanding Engine...');
const smartAnalysis = analyzeFileWithSmartLearning(content, { security: { maxDepth: 50, maxTokens: 100000, maxParsingTime: 15000 } });
if (smartAnalysis && smartAnalysis.intentAnalysis) {
console.log(' AI Intent Analysis completed successfully');
console.log('\n Intent Analysis Results:');
console.log(JSON.stringify(smartAnalysis.intentAnalysis.summary, null, 2));
// แสดง smart comments ที่สร้างขึ้น
if (smartAnalysis.intentAnalysis.smartComments.length > 0) {
console.log('\n Generated Smart Comments:');
smartAnalysis.intentAnalysis.smartComments.forEach(([item, comment]) => {
console.log(` ${item}: ${comment.thai}`);
});
}
// ใช้ข้อมูล intent analysis สำหรับ smart formatting
options.intentAnalysis = smartAnalysis.intentAnalysis;
} else {
console.log(' AI Intent Analysis failed or returned no results');
}
}
// ========================================================================
// PHASE 2: SAFE SURGICAL FORMATTING/การจัดรูปแบบอย่างปลอดภัย
// ========================================================================
console.log('Starting Safe Surgical Formatting...');
const indentSize = options.indentSize || 4;
// Step 1: Pre-processing with better logic
let formatted = content;
// Fix method declarations after closing braces
formatted = formatted.replace(/}([a-zA-Z_][a-zA-Z0-9_]*\s*\()/g, '}\n\n$1');
formatted = formatted.replace(/}(async\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\()/g, '}\n\n$1');
formatted = formatted.replace(/}(class\s+[a-zA-Z_][a-zA-Z0-9_]*)/g, '}\n\n$1');
formatted = formatted.replace(/}(function\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\()/g, '}\n\n$1');
// Fix destructuring and requires
formatted = formatted.replace(/const\s*{\s*([^}]+)\s*}\s*=/g, (match, vars) => {
const cleanVars = vars.replace(/\s*,\s*/g, ', ').trim();
return `const { ${cleanVars} } =`;
});
// Add proper spacing for operators BEFORE splitting
formatted = addComprehensiveSpacing(formatted);
// Add line breaks after semicolons (careful with for loops)
formatted = formatted.replace(/;(?![^{]*})(?![^()]*\))/g, ';\n');
// Add line breaks around braces (but preserve inline objects)
formatted = formatted.replace(/{(?![^}]*}[^{]*$)/g, '{\n');
formatted = formatted.replace(/([^{;\n\s])}/g, '$1\n}');
// Split and process lines
const lines = formatted.split('\n');
const result = [];
let indentLevel = 0;
let insideFunction = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
if (!line) continue;
// Track function/class context
if (line.includes('function ') || line.includes('class ') || line.startsWith('async ')) {
insideFunction = true;
} // Handle closing braces
if (line === '}' || line.startsWith('}')) {
indentLevel = Math.max(0, indentLevel - 1);
insideFunction = false;
}
// Add indentation
const indentation = ' '.repeat(indentLevel * indentSize);
result.push(indentation + line);
// Handle opening braces
if (line.endsWith('{')) {
indentLevel++;
}
}
return smartCleanup(result.join('\n'));
} catch (error) {
console.error('Enhanced Format error:', error.message);
return content;
}
}
// ======================================================================
// Code Health Diagnosis System/ระบบวินิจฉัยสุขภาพโค้ด
// ======================================================================
// ตรวจสอบสุขภาพโค้ดก่อนการจัดรูปแบบ
// ใช้ Tokenizer และ StructureParser เพื่อวิเคราะห์ความถูกต้องของ syntax
function performCodeHealthCheck(content) {
const healthReport = {
isHealthy: false,
errorLine: null,
errorColumn: null,
errorMessage: '',
stats: {
functions: 0,
classes: 0,
complexity: 'simple',
tokens: 0
}
};
try {
// Phase 1: Tokenization Health Check
console.log(' Phase 1: Tokenization Analysis...');
const tokenizer = new JavaScriptTokenizer(content); // Pass content as first parameter
const tokens = tokenizer.tokenize();
if (!tokens || tokens.length === 0) {
healthReport.errorMessage = 'Failed to tokenize content - possible syntax error';
healthReport.errorLine = 1;
healthReport.errorColumn = 1;
return healthReport;
}
healthReport.stats.tokens = tokens.length;
// Phase 2: Structure Parsing Health Check
console.log(' Phase 2: Structure Analysis...');
const analyzer = new StructureAnalyzer(tokens, content);
const structures = analyzer.analyzeAll();
// Phase 3: Syntax Validation
console.log(' Phase 3: Syntax Validation...');
const syntaxCheck = validateSyntax(content, tokens);
if (!syntaxCheck.isValid) {
healthReport.errorLine = syntaxCheck.errorLine;
healthReport.errorColumn = syntaxCheck.errorColumn;
healthReport.errorMessage = syntaxCheck.errorMessage;
return healthReport;
}
// Phase 4: Statistical Analysis
healthReport.stats.functions = countFunctions(structures);
healthReport.stats.classes = countClasses(structures);
healthReport.stats.complexity = assessComplexity(structures);
// All checks passed
healthReport.isHealthy = true;
console.log(' All health checks PASSED');
return healthReport;
} catch (error) {
console.error(' Health check failed:', error.message);
// Extract line/column info from error if possible
const lineMatch = error.message.match(/line (\d+)/i);
const colMatch = error.message.match(/column (\d+)/i);
healthReport.errorLine = lineMatch ? parseInt(lineMatch[1]) : 1;
healthReport.errorColumn = colMatch ? parseInt(colMatch[1]) : 1;
healthReport.errorMessage = error.message;
return healthReport;
}
}
// ตรวจสอบ syntax ด้วย token analysis
function validateSyntax(content, tokens) {
const result = {
isValid: true,
errorLine: null,
errorColumn: null,
errorMessage: ''
};
try {
// Check for unmatched braces, brackets, parentheses
const stack = [];
const pairs = {
'{': '}',
'[': ']',
'(': ')'
};
for (const token of tokens) {
if (token.type === 'BRACE_OPEN' || token.type === 'BRACKET_OPEN' || token.type === 'PAREN_OPEN') {
stack.push({ token: token.value, line: token.line, column: token.column });
} else if (token.type === 'BRACE_CLOSE' || token.type === 'BRACKET_CLOSE' || token.type === 'PAREN_CLOSE') {
if (stack.length === 0) {
result.isValid = false;
result.errorLine = token.line;
result.errorColumn = token.column;
result.errorMessage = `Unexpected closing '${token.value}'`;
return result;
}
const lastOpen = stack.pop();
const expectedClose = pairs[lastOpen.token];
if (expectedClose !== token.value) {
result.isValid = false;
result.errorLine = token.line;
result.errorColumn = token.column;
result.errorMessage = `Mismatched: expected '${expectedClose}' but found '${token.value}'`;
return result;
}
}
}
// Check for unclosed pairs
if (stack.length > 0) {
const unclosed = stack[stack.length - 1];
result.isValid = false;
result.errorLine = unclosed.line;
result.errorColumn = unclosed.column;
result.errorMessage = `Unclosed '${unclosed.token}'`;
return result;
}
return result;
} catch (error) {
result.isValid = false;
result.errorMessage = `Syntax validation failed: ${error.message}`;
return result;
}
}
// นับจำนวน functions
function countFunctions(structures) {
let count = 0;
if (structures && structures.functions) {
count = structures.functions.length || 0;
}
return count;
}
// นับจำนวน classes
function countClasses(structures) {
let count = 0;
if (structures && structures.classes) {
count = structures.classes.length || 0;
}
return count;
}
// ประเมินความซับซ้อนของโค้ด
function assessComplexity(structures) {
const functionCount = countFunctions(structures);
const classCount = countClasses(structures);
const totalElements = functionCount + classCount;
if (totalElements <= 5) return 'simple';
if (totalElements <= 15) return 'moderate';
return 'complex';
}// เพิ่มช่องว่างที่ครอบคลุม
function addComprehensiveSpacing(content) {
let formatted = content;
// Fix arrow function spacing (handle edge cases)
formatted = formatted.replace(/=\s*>/g, ' => ');
formatted = formatted.replace(/\s+=>\s+/g, ' => ');
// Assignment operators
formatted = formatted.replace(/([a-zA-Z0-9_)\]])=([^=])/g, '$1 = $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])==([^=])/g, '$1 == $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])===([^=])/g, '$1 === $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])!=([^=])/g, '$1 != $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])!==([^=])/g, '$1 !== $2');
// Comparison operators
formatted = formatted.replace(/([a-zA-Z0-9_)\]])<([a-zA-Z0-9_(\[])/g, '$1 < $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])>([a-zA-Z0-9_(\[])/g, '$1 > $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])<=([a-zA-Z0-9_(\[])/g, '$1 <= $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])>=([a-zA-Z0-9_(\[])/g, '$1 >= $2');
// Logical operators
formatted = formatted.replace(/([a-zA-Z0-9_)\]])&&([a-zA-Z0-9_(\[])/g, '$1 && $2');
formatted = formatted.replace(/([a-zA-Z0-9_)\]])\|\|([a-zA-Z0-9_(\[])/g, '$1 || $2');
// Arithmetic operators (avoid negative numbers)
formatted = formatted.replace(/(\w)\+(\w)/g, '$1 + $2');
formatted = formatted.replace(/(\w)-(\w)/g, '$1 - $2');
formatted = formatted.replace(/(\w)\*(\w)/g, '$1 * $2');
formatted = formatted.replace(/(\w)\/(\w)/g, '$1 / $2');
// Keywords
formatted = formatted.replace(/\b(if|for|while|switch|catch)\(/g, '$1 (');
formatted = formatted.replace(/\b(function|class|async function)\s+/g, '$1 ');
// Braces
formatted = formatted.replace(/([^{\s]){/g, '$1 {');
// Commas
formatted = formatted.replace(/,(?!\s)/g, ', ');
// Colons in objects
formatted = formatted.replace(/(\w):(?!\s)/g, '$1: ');
return formatted;
}
// Smart cleanup with better logic
function smartCleanup(content) {
let cleaned = content;
// Remove excessive empty lines
cleaned = cleaned.replace(/\n{4,}/g, '\n\n\n');
// Add empty lines before major declarations (but not the first one)
cleaned = cleaned.replace(/(\n.+\n)(\s*)(class |function |async function )/g, '$1\n$2$3');
// Add empty lines after class/function closing braces
cleaned = cleaned.replace(/(\n\s*})\n(\s*)(class |function |const |let |var )/g, '$1\n\n$2$3');
// Remove trailing spaces
cleaned = cleaned.replace(/[ \t]+$/gm, '');
// Fix indentation inconsistencies
const lines = cleaned.split('\n');
const indentSize = 4;
let indentLevel = 0;
const fixedLines = [];
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) {
fixedLines.push('');
continue;
}
// Adjust indent for closing braces
if (trimmed === '}' || trimmed.startsWith('}')) {
indentLevel = Math.max(0, indentLevel - 1);
}
// Apply consistent indentation
fixedLines.push(' '.repeat(indentLevel * indentSize) + trimmed);
// Adjust indent for opening braces
if (trimmed.endsWith('{')) {
indentLevel++;
}
}
return fixedLines.join('\n').trim();
}
// จัดรูปแบบไฟล์โค้ด
function formatFile(filePath, options = {}) {
try {
// ตรวจสอบนามสกุลไฟล์
const ext = path.extname(filePath).toLowerCase();
if (!options.extensions.includes(ext)) {
return { success: false, error: `Unsupported file extension: ${ext}` };
}
// อ่านไฟล์
const content = fs.readFileSync(filePath, 'utf8');
// จัดรูปแบบเนื้อหา
const formattedContent = formatCode(content, options);
if (options.dryRun) {
return {
success: true,
changes: formattedContent !== content,
preview: formattedContent
};
} else {
// สร้าง backup ถ้าต้องการ
if (options.backup && formattedContent !== content) {
createBackup(filePath);
}
// เขียนไฟล์ใหม่ถ้ามีการเปลี่ยนแปลง
if (formattedContent !== content) {
fs.writeFileSync(filePath, formattedContent, 'utf8');
return { success: true, changes: true };
} else {
return { success: true, changes: false };
}
}
} catch (error) {
return { success: false, error: error.message };
}
}
function main() {
const sessionStartTime = Date.now();
const args = process.argv.slice(2);
// Session logging
logger.info('SESSION', 'Code Magician session started', {
args: args,
cwd: process.cwd(),
nodeVersion: process.version,
platform: process.platform
});
// ตรวจสอบคำสั่ง
if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
showHelp();
return;
}
if (args.includes('--version')) {
showVersion();
return;
}
// กำหนดค่าเริ่มต้น
const options = {
dryRun: args.includes('-d') || args.includes('--dry-run'),
verbose: args.includes('-v') || args.includes('--verbose'),
backup: args.includes('-b') || args.includes('--backup'),
recursive: args.includes('-r') || args.includes('--recursive'),
addMissing: args.includes('--add-missing'),
aiMode: args.includes('--ai-mode'),
organizeZones: args.includes('--organize-zones'),
formatOnly: args.includes('--format'),
removeComments: args.includes('--remove-comments') || args.includes('--remove'),
enableSmartLearning: args.includes('--smart-learning') || args.includes('-s'),
extensions: ['.js', '.ts', '.jsx', '.tsx']
};
// ดึง extension ที่กำหนด และตรวจสอบความปลอดภัย
const extIndex = args.findIndex(arg => arg === '--ext');
if (extIndex !== -1 && args[extIndex + 1]) {
// SECURITY: Extension Validation - ป้องกันการใส่อินพุตที่ไม่ถูกต้อง
const inputExtensions = args[extIndex + 1]
.split(',')
.map(ext => ext.trim().toLowerCase())
// กรองเอาเฉพาะ extension ที่มีรูปแบบถูกต้อง (ขึ้นต้นด้วย . และตามด้วยตัวอักษร/ตัวเลข)
.filter(ext => {
// ตรวจสอบว่าเป็นรูปแบบ extension ที่ถูกต้อง
if (!/^\.[a-z0-9]+$/.test(ext)) {
console.warn(`Warning: Invalid extension format '${ext}' ignored. Extensions must start with '.' followed by alphanumeric characters.`);
return false;
}
// ตรวจสอบความยาวที่สมเหตุสมผล
if (ext.length > 10) {
console.warn(`Warning: Extension '${ext}' too long (max 10 chars), ignored.`);
return false;
}
return true;
});
if (inputExtensions.length > 0) {
options.extensions = inputExtensions;
} else {
console.warn(`Warning: No valid extensions provided, using defaults: ${options.extensions.join(', ')}`);
}
}
// หา target (ไฟล์หรือไดเรกทอรี)
let target = '.';
for (let i = 0; i < args.length; i++) {
if (!args[i].startsWith('-') &&
(extIndex === -1 || i !== extIndex + 1)) {
target = args[i];
break;
}
}
// SECURITY: Path Traversal Protection
const workingDir = process.cwd();
const resolvedTarget = path.resolve(target);
// ป้องกันการเข้าถึงไฟล์นอกโปรเจกต์ปัจจุบัน
if (!resolvedTarget.startsWith(workingDir)) {
console.error(` Security Error: Target path '${target}' is outside of the current project directory.`);
console.error(` Working directory: ${workingDir}`);
console.error(` Resolved target: ${resolvedTarget}`);
console.error(` Access denied for security reasons.`);
process.exit(1);
}
// SECURITY: System Directory Protection
const forbiddenPaths = [
'node_modules', '.git', '.npm', '.cache', 'System32', 'etc', 'proc', 'sys',
'Windows', 'Program Files', 'Users', '.ssh', '.aws', '.config'
];
const targetLower = target.toLowerCase();
for (const forbidden of forbiddenPaths) {
if (targetLower.includes(forbidden.toLowerCase())) {
console.error(` Security Error: Access to '${forbidden}' directories is prohibited for safety.`);
process.exit(1);
}
}
// ตรวจสอบว่า target มีอยู่จริง
if (!fs.existsSync(target)) {
console.error(`Error: Target '${target}' does not exist.`);
process.exit(1);
}
// เริ่มประมวลผล
console.log(` Starting Code Magician v3.0.1-beta...`);
console.log(` Beta Release - Help us improve with your feedback!`);
console.log(`Target: ${target}`);
console.log(`Mode: ${options.dryRun ? 'DRY RUN' : 'LIVE'}`);
if (options.formatOnly) {
console.log(`Operation: CODE FORMATTING ONLY`);
}
const startTime = Date.now();
const stat = fs.statSync(target);
let results;
if (stat.isFile()) {
// ประมวลผลไฟล์เดียว
console.log(`Processing single file...`);
if (options.formatOnly) {
// Format-only mode
const result = formatFile(target, options);
if (result.success) {
console.log(` File formatted successfully`);
if (options.dryRun && result.preview) {
console.log('\n--- FORMATTED PREVIEW ---');
console.log(result.preview);
console.log('--- END PREVIEW ---\n');
}
} else {
console.error(` Error formatting file: ${result.error}`);
}
results = { processed: 1, modified: result.success ? 1 : 0, errors: result.success ? 0 : 1 };
} else {
// Normal comment processing
const result = processFile(target, options);
if (result.success) {
if (result.changes) {
console.log(` File processed successfully`);
if (options.dryRun && result.preview) {
console.log('\n--- PREVIEW ---');
console.log(result.preview);
console.log('--- END PREVIEW ---\n');
}
} else {
console.log(`- No changes needed`);
}
} else {
console.error(` Error processing file: ${result.error}`);
}
results = { processed: 1, modified: result.changes ? 1 : 0, errors: result.success ? 0 : 1 };
}
} else if (stat.isDirectory()) {
// ประมวลผลไดเรกทอรี
console.log(`Processing directory${options.recursive ? ' (recursive)' : ''}...`);
results = processDirectory(target, options);
// แสดงผลสรุป
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
console.log(`\n═══════════════════════════════════════════════════════════════════════════════════`);
console.log(`SUMMARY:`);
console.log(` Files found: ${results.total}`);
console.log(` Files processed: ${results.processed}`);
console.log(` Files with changes: ${results.files.length}`);
console.log(` Errors: ${results.errors}`);
console.log(` Duration: ${duration}s`);
// เพิ่มสถิติรายละเอียด
if (results.statistics) {
console.log(`\nSTRUCTURE ANALYSIS STATISTICS:`);
console.log(` Total structures found: ${results.statistics.totalStructures}`);
console.log(` Successfully detected: ${results.statistics.detectedStructures}`);
console.log(` Missed by parser: ${results.statistics.missedStructures}`);
console.log(` Comments added: ${results.statistics.commentsAdded}`);
console.log(` Skipped (inappropriate context): ${results.statistics.inappropriateContexts}`);
console.log(` Line number corrections: ${results.statistics.lineNumberCorrections}`);
// คำนวณ success rate
const detectionRate = results.statistics.totalStructures > 0
? ((results.statistics.detectedStructures / results.statistics.totalStructures) * 100).toFixed(1)
: '0.0';
console.log(` Detection success rate: ${detectionRate}%`);
// แสดง error details ถ้ามี
if (results.statistics.errorDetails && results.statistics.errorDetails.length > 0) {
console.log(`\nERROR DETAILS:`);
const errorSummary = {};
results.statistics.errorDetails.forEach(error => {
const key = error.type || 'unknown_error';
errorSummary[key] = (errorSummary[key] || 0) + 1;
});
Object.entries(errorSummary).forEach(([type, count]) => {
console.log(` ${type}: ${count} occurrences`);
});
// แสดงรายละเอียด error ถ้าเป็น verbose mode
if (options.verbose && results.statistics.errorDetails.length <= 10) {
console.log(`\nDETAILED ERRORS:`);
results.statistics.errorDetails.forEach(error => {
console.log(` • ${error.file || 'unknown'}: ${error.message || error.type}`);
});
} else if (results.statistics.errorDetails.length > 10) {
console.log(` (Use --verbose to see detailed error list)`);
}
}
// แสดง bugs/issues summary
const totalIssues = results.statistics.missedStructures +
results.statistics.inappropriateContexts +
results.errors;
if (totalIssues > 0) {
console.log(`\n BETA TESTING INSIGHTS:`);
console.log(` Total learning opportunities: ${totalIssues}`);
if (results.statistics.missedStructures > 0) {
console.log(` TypeScript patterns to enhance: ${results.statistics.missedStructures}`);
console.log(` Help us: Share your .ts files with interfaces/abstract classes!`);
}
if (results.statistics.inappropriateContexts > 0) {
console.log(` Context analysis improvements needed: ${results.statistics.inappropriateContexts}`);
console.log(` Help us: Submit JSX/arrow function examples that caused issues!`);
}
if (results.errors > 0) {
console.log(` Processing challenges: ${results.errors}`);
console.log(` Help us: Report these with --verbose logs to our GitHub!`);
}
} else {
console.log(`\n EXCELLENT! All structures processed successfully!`);
console.log(` Your code is a perfect example for our pattern recognition!`);
console.log(` Consider sharing your project structure to help other developers!`);
}
}
if (options.dryRun && results.files.length > 0) {
console.log(`\nFiles that would be modified:`);
results.files.forEach(file => {
console.log(` - ${file.path}`);
});
}
console.log(`═══════════════════════════════════════════════════════════════════════════════════`);
}
console.log(`\n Universal Code Magician Beta completed ${options.dryRun ? '(DRY RUN)' : 'successfully'}!`);
console.log(` Your feedback helps us build better tools for the developer community!`);
// Session summary logging
const sessionDuration = Date.now() - sessionStartTime;
logger.performance('SESSION_COMPLETE', sessionDuration, {
mode: options.dryRun ? 'DRY_RUN' : 'LIVE',
totalFiles: results?.total || 0,
processedFiles: results?.processed || 0,
modifiedFiles: results?.files?.length || 0,
errors: results?.errors || 0,
options: options
});
// Cleanup old backups
backupManager.cleanupOldBackups(7); // Keep backups for 7 days
logger.info('SESSION', 'Code Magician session completed successfully', {
duration: sessionDuration,
summary: results
});
}
// ======================================================================
// Missing Elements Detection/ตรวจสอบองค์ประกอบที่หายไป
// ======================================================================
function detectMissingElements(content, detectedItems) {
const missing = [];
// ใช้ normalize line endings เพื่อจัดการ \r\n และ \r
const normalizedContent = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const lines = normalizedContent.split('\n');
const detectedNames = new Set(detectedItems.map(item => item.name));
// ค้นหาคลาสที่อาจจะหายไป - และส่งคืนข้อมูล line numbers ที่ถูกต้อง
const classRegex = /^\s*class\s+(\w+)/gm;
let match;
while ((match = classRegex.exec(normalizedContent)) !== null) {
const className = match[1];
const lineNumber = normalizedContent.substring(0, match.index).split('\n').length;
// เพิ่มเฉพาะคลาสที่ไม่ได้ถูกตรวจพบ หรือที่มี line number ผิด
if (!detectedNames.has(className)) {
missing.push({
type: 'class',
name: className,
line: lineNumber,
reason: 'Class not detected by parsing system'
});
} else {
// ถ้าคลาสถูกตรวจพบแล้ว แต่ line number อาจจะผิด
const existingItem = detectedItems.find(item => item.name === className);
if (existingItem && existingItem.line === 1 && lineNumber > 1) {
missing.push({
type: 'class_correction',
name: className,
line: lineNumber,
reason: 'Line number correction needed'
});
}
}
}
// ค้นหาฟังก์ชันที่อาจจะหายไป
const functionRegex = /^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)/gm;
let funcMatch;
while ((funcMatch = functionRegex.exec(normalizedContent)) !== null) {
const funcName = funcMatch[1];
const lineNumber = normalizedContent.substring(0, funcMatch.index).split('\n').length;
if (!detectedNames.has(funcName)) {
missing.push({
type: 'function',
name: funcName,
line: lineNumber,
reason: 'Function not detected by parsing system'
});
}
}
// ค้นหา arrow functions ที่อาจจะหายไป
const arrowFuncRegex = /^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>/gm;
let arrowMatch;
while ((arrowMatch = arrowFuncRegex.exec(normalizedContent)) !== null) {
const funcName = arrowMatch[1];
const lineNumber = normalizedContent.substring(0, arrowMatch.index).split('\n').length;
if (!detectedNames.has(funcName)) {
missing.push({
type: 'arrow_function',
name: funcName,
line: lineNumber,
reason: 'Arrow function not detected by parsing system'
});
}
}
// ค้นหา methods ภายในคลาสที่อาจจะหายไป (สำหรับสถิติเท่านั้น)
const methodRegex = /^\s+(?:async\s+)?(\w+)\s*\([^)]*\)\s*{/gm;
let methodMatch;
while ((methodMatch = methodRegex.exec(normalizedContent)) !== null) {
const methodName = methodMatch[1];
const lineNumber = normalizedContent.substring(0, methodMatch.index).split('\n').length;
// ข้าม constructor และ keywords - แต่นับเป็นสถิติ
if (methodName !== 'constructor' &&
!['if', 'for', 'while', 'switch', 'catch', 'function'].includes(methodName) &&
!detectedNames.has(methodName)) {
// เพิ่มเป็นสถิติเท่านั้น ไม่ได้เป็นข้อผิดพลาด
}
}
return missing;
}
// ========================================================
// STATE MACHINE STRUCTURE PARSER v5.2 - FINAL FIX
// แก้ปัญหาคอมเมนต์อยู่ใต้ class + จับตำแหน่งแม่นยำขึ้น
// ========================================================
class StateMachineStructureParser {
constructor(tokens, originalContent) {
this.tokens = tokens.filter(t => t.type !== TOKEN_TYPES.WHITESPACE && t.type !== TOKEN_TYPES.NEWLINE);
this.content = originalContent;
this.cursor = 0;
this.structures = {
classes: [], functions: [], methods: [], arrowFunctions: [],
reactComponents: [], interfaces: [], typeAliases: [], enums: []
};
}
parse() {
while (this.cursor < this.tokens.length) {
this.tryParseDeclaration();
this.cursor++;
}
return this.structures;
}
tryParseDeclaration() {
const token = this.tokens[this.cursor];
if (!token || token.type !== TOKEN_TYPES.IDENTIFIER) return;
const name = token.value;
const prev = this.tokens[this.cursor - 1];
const next = this.tokens[this.cursor + 1];
const prev2 = this.tokens[this.cursor - 2];
// 1. Class / Interface / Enum / Type (รองรับ export, abstract)
if (prev && ['class', 'interface', 'enum', 'type', 'abstract'].includes(prev.value)) {
const target = prev.value === 'class' ? 'classes' :
prev.value === 'interface' ? 'interfaces' :
prev.value === 'enum' ? 'enums' : 'typeAliases';
this.structures[target].push({
type: prev.value + '_declaration',
name,
line: token.line
});
return;
}
// 2. Function declaration
if (prev && prev.value === 'function' && next && next.value === '(') {
this.structures.functions.push({ type: 'function_declaration', name, line: token.line });
return;
}
// 3. Class method (อยู่หลัง { ของ class) - แต่ไม่ใช่ method call หรือ constructor call
// ตรวจสอบว่าไม่มี dot (.) อยู่ข้างหน้า (ถ้ามี = method call, ไม่ใช่ declaration)
// และไม่มี new ข้างหน้า (ถ้ามี = constructor call, ไม่ใช่ method declaration)
const hasDotBefore = prev && prev.value === '.';
const hasNewBefore = prev && prev.value === 'new';
if (next && next.value === '(' && this.isInsideClassBody() && !hasDotBefore && !hasNewBefore) {
if (name !== 'constructor') {
this.structures.methods.push({ type: 'class_method', name, line: token.line });
}
return;
}
// 4. Arrow function / React Component
if (prev && prev.value === '=' && ['const','let','var'].includes(prev2?.value || '')) {
const isReact = /^[A-Z]/.test(name) && this.looksLikeReactFC(token.line);
const target = isReact ? 'reactComponents' : 'arrowFunctions';
this.structures[target].push({
type: isReact ? 'react_component' : 'arrow_function',
name,
line: token.line
});
}
}
isInsideClassBody() {
let braceCount = 0;
for (let i = this.cursor - 1; i >= 0; i--) {
if (this.tokens[i].value === '{') braceCount++;
if (this.tokens[i].value === '}') braceCount--;
if (this.tokens[i].value === 'class' && braceCount > 0) return true;
if (braceCount < 0) return false;
}
return false;
}
looksLikeReactFC(startLine) {
for (let i = this.cursor; i < Math.min(this.cursor + 80, this.tokens.length); i++) {
if (this.tokens[i].line > startLine + 50) break;
if (this.tokens[i].value === '=>' ||
(this.tokens[i].value === 'return' && this.tokens[i+1]?.value === '<')) {
return true;
}
}
return false;
}
}
// เรียกใช้ฟังก์ชันหลักถ้าไฟล์นี้ถูกเรียกใช้โดยตรง
if (require.main === module) {
main();
}
// Export สำหรับการใช้งานเป็น module
module.exports = {
// === Core Processing Functions ===
processFile, // - ประมวลผลไฟล์หลัก
processDirectory, // - ประมวลผลไดเรกทอรี
fixComments, // - แก้ไขรูปแบบคอมเมนต์
addMissingComments, // - เพิ่มคอมเมนต์ที่ขาดหาย
removeComments, // - ลบคอมเมนต์ออกจากโค้ด
// === Code Analysis & Tokenization Classes ===
JavaScriptTokenizer, // - ตัวแยกโทเค็น JavaScript/TypeScript
FunctionPatternMatcher, // - ตัวจับคู่แพทเทิร์นฟังก์ชัน
StructureParser, // - ตัววิเคราะห์โครงสร้างโค้ด
SmartFileAnalyzer, // - ตัววิเคราะห์ไฟล์อัจฉริยะ
StructureAnalyzer, // - ตัววิเคราะห์โครงสร้างขั้นสูง
EnhancedPatternDetector, // - ตัวตรวจจับแพทเทิร์นขั้นสูง
CommentGenerator, // - ตัวสร้างคอมเมนต์อัจฉริยะ
StateMachineStructureParser, // State Machine Parser v4.0 - Token-based + Context-aware parsing
// === Security & Utility Classes ===
TokenizerSecurityManager, // - ตัวจัดการความปลอดภัย Tokenizer
ProfessionalLogger, // - ระบบ Logging แบบมืออาชีพ
OrganizedBackupManager, // - ตัวจัดการ Backup แบบจัดระเบียบ
FileComparisonAnalyzer, // - ตัววิเคราะห์การเปรียบเทียบไฟล์
// === Code Formatting Functions ===
formatCode, // - จัดรูปแบบโค้ดให้สวยงาม
formatFile, // - จัดรูปแบบไฟล์โค้ด
performCodeHealthCheck, // - ตรวจสอบสุขภาพโค้ด
validateSyntax, // - ตรวจสอบไวยากรณ์
addComprehensiveSpacing, // - เพิ่มช่องว่างแบบครอบคลุม
smartCleanup, // - ทำความสะอาดโค้ดอัจฉริยะ
// === Smart Learning & AI Functions ===
analyzeFileWithSmartLearning, // - วิเคราะห์ไฟล์ด้วย Smart Learning
generateSmartComment, // - สร้างคอมเมนต์อัจฉริยะ
generateSmartClassComment, // - สร้างคอมเมนต์คลาสอัจฉริยะ
generateSmartFunctionComment, // - สร้างคอมเมนต์ฟังก์ชันอัจฉริยะ
// === TypeScript Comment Generators ===
generateInterfaceComment, // - สร้างคอมเมนต์ Interface
generateTypeAliasComment, // - สร้างคอมเมนต์ Type Alias
generateEnumComment, // - สร้างคอมเมนต์ Enum
generateAbstractClassComment, // - สร้างคอมเมนต์ Abstract Class
generateConstComment, // - สร้างคอมเมนต์ Const Declaration
// === Backup & Organization Functions ===
createBackup, // - สร้างไฟล์สำรอง
organizeCodeByZones, // - จัดระเบียบโค้ดตาม Zone
// === CLI & Helper Functions ===
showHelp, // - แสดงคำแนะนำการใช้งาน
showVersion, // - แสดงเวอร์ชันโปรแกรม
main, // - ฟังก์ชันหลักของโปรแกรม
// === Analysis & Detection Functions ===
detectMissingElements, // - ตรวจสอบองค์ประกอบที่หายไป
findMethodsWithRegex, // - ค้นหา Methods ด้วย Regex
countFunctions, // - นับจำนวนฟังก์ชัน
countClasses, // - นับจำนวนคลาส
assessComplexity, // - ประเมินความซับซ้อนโค้ด
// === Utility Helper Functions ===
calculateLineNumber, // - คำนวณหมายเลขบรรทัด
normalizeLineEndings, // - ปรับ Line Endings ให้มาตรฐาน
analyzeCommentStatus, // - วิเคราะห์สถานะคอมเมนต์
}; |