All files / src/utils ProductBuilder.ts

73.98% Statements 879/1188
78.13% Branches 243/311
82.5% Functions 66/80
73.98% Lines 879/1188

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 22781x 1x 1x 1x 1x 1x 1x 1x 1x                                     1x                                                   1x                                                                 1x 1x 1x 1x   1x 1x   1x 1x   1x 1x   1x               1x 1x 330x 330x 330x   1x                             1x 1x 60x     60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x 60x   60x 171x 4x 4x 4x 167x 171x     167x 167x 167x 167x 60x 60x   1x                                 1x 1x 185x 185x   1x                 1x 1x 207x 200x 207x 3x 3x 207x 207x   1x                 1x 1x 188x 188x 188x     188x 188x   1x                 1x 1x 220x 220x 220x 220x     220x 220x   1x                 1x 1x 53x 53x 46x 53x 3x 3x 53x 53x   1x                     1x 1x 12x 12x 8x 12x     12x 12x   1x                     1x 1x 4x 4x 4x 4x     4x 4x   1x                 1x 1x                   1x                         1x 1x 91x 91x 65x 90x     91x 91x   1x                       1x 1x 26x 26x 8x 26x     26x 26x   1x                     1x 1x 12x 12x 11x 12x 1x 1x 12x 12x   1x                   1x 1x 6x 6x 5x 6x     6x 6x   1x                         1x 1x 24x 24x 24x   1x                       1x 1x 1x 1x 1x   1x                             1x 1x 184x 96x 96x 184x 184x   1x                         1x 1x 25x     25x 25x 53x 47x 47x 53x 4x 6x 2x 2x 53x 25x   1x                         1x 1x 182x 182x 182x 182x 182x 182x 47x 47x 135x 182x 71x 71x 135x 135x   1x                     1x 1x 47x     47x 47x   1x                 1x 1x 62x 29x 29x 62x 62x   1x                   1x 1x 73x 64x 64x 73x 73x   1x                                 1x 1x 60x 4x 4x 56x 56x 56x 56x 56x 56x 60x 55x 55x 55x 1x 1x 1x 1x 1x 1x 1x   1x                       1x 1x 20x 16x 20x     20x 20x   1x                   1x 1x 20x                   20x 20x 20x 20x 20x 20x   1x                     1x 1x 32x 32x 32x           32x 32x   1x                   1x 1x 33x 33x 33x           33x 33x                                                                                                         1x 132x 132x 132x 132x 132x 17x 17x 17x 17x 17x 115x 115x   115x                             115x   115x 115x   1x                                 1x 1x 129x   129x 4x 4x 4x 4x   129x                                           125x 125x 125x 125x 106x 106x 125x 125x                     1x                 1x 1x               1x                   1x 1x 19x 19x 19x     19x 19x   1x                   1x 1x 10x 10x 10x     10x 10x   1x                   1x 1x 4x 4x 4x     4x 4x   1x                   1x 1x 9x 9x 9x 9x 9x           9x 9x   1x                           1x 1x 13x 10x 10x 13x 13x 3x 3x 13x   1x                     1x 1x 11x 11x 3x 11x 6x 6x 6x 6x 6x 11x 11x   1x                     1x 1x 2x 2x 2x 2x           2x 2x   1x                       1x 1x 146x 111x 146x 3x 3x 146x 146x   1x                 1x 1x 26x 1x 26x 3x 3x 3x 3x 3x 26x 26x   1x                 1x 1x 18x         18x     18x 18x   1x                 1x 1x 18x         18x     18x 18x   1x                           1x 1x 134x 43x 43x           43x 43x   101x 41x 121x 50x 50x 34x 34x 50x 91x 91x   1x                   1x 1x 143x 142x 142x     143x 143x   1x                   1x 1x 7x 7x 7x     7x 7x   1x                   1x 1x 129x 109x 129x 3x 3x 129x 129x   1x                         1x 1x 170x 167x 170x 1x 3x     170x 170x   1x                     1x 1x 21x   21x 21x       21x           21x 21x   1x                     1x 1x 2x 2x 2x                     2x 2x   1x                       1x 1x                                 1x                     1x 1x                                 1x                       1x 1x                     1x                   1x 1x 12x 5x 12x 3x 3x 12x 12x   1x                                   1x 1x 110x   110x 65x 65x 65x 65x 65x 65x 65x       45x 64x   16x 16x 16x 16x 16x 8x 16x 16x 1x 16x   16x 1x 16x 1x 16x   16x 1x 16x 1x 16x   16x   16x 1x 16x 1x 16x   16x 1x 16x 16x 110x   1x                             1x 1x 110x   110x 1x 1x 1x   109x 109x 109x   1x                               1x 1x 21x 5x 5x 21x 21x 21x   1x                                             1x 1x 1x 6x 6x 1x 1x   1x                           1x 1x 20x     20x 20x 20x   1x                                   1x 1x 71x 71x 27x 27x 27x 47x 39x 39x   71x 66x 66x 71x 71x   1x                           1x 1x 30x 22x 22x 30x 30x   1x                   1x 1x 62x 7x 7x   62x 53x 53x 62x 62x   1x                     1x 1x 290x 241x 241x   49x 49x   1x                     1x 1x 138x 34x 34x 138x 138x   1x                 1x 1x 2x     2x 2x   1x                 1x 1x             1x                 1x 1x 1x 1x 1x 1x 1x   1x                 1x 1x             1x                       1x 1x 9x 1x 1x 8x   9x 3x 3x 2x 2x 3x 9x 9x     9x 1x 1x 8x 8x   9x     9x 6x 6x   9x 7x 7x 8x 8x   1x                   1x 1x                                     1x                   1x 1x               1x                   1x 1x                 1x                   1x 1x                   1x                   1x 1x                   1x                   1x 1x                         1x                     1x 1x       1x                     1x 1x 492x 397x 397x 95x 95x 95x   1x                       1x 1x 471x     471x 413x 413x 58x 58x   1x                                               1x 1x 39x       39x 39x 39x 39x 39x   39x 3x 3x   39x 39x 1x 1x   1x 1x 1x                 1x                 1x 1x 1x   1x       1x 1x 1x 1x 1x     1x 1x 1x   1x       1x 1x 1x 1x 1x 1x 1x   1x 1x   1x   1x 1x 1x   39x       39x               39x 39x 39x 39x 39x 39x 39x 39x   1x                         1x 1x 120x 120x   1x                                 1x 1x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 4x 1x  
import { AVAILABILITY, type Availability } from '@/constants/common';
import { findCAS } from '@/helpers/cas';
import { parsePrice, toUSD } from '@/helpers/currency';
import { parseQuantity, toBaseQuantity } from '@/helpers/quantity';
import { findFormulaInHtml, findPurity, isMoleForm } from '@/helpers/science';
import { htmlToAscii } from '@/helpers/utils';
import { Logger } from '@/utils/Logger';
import { IS_DEV_BUILD } from '@/utils/isDevBuild';
import {
  isCAS,
  isCountryCode,
  isCurrencyCode,
  isCurrencySymbol,
  isInChI,
  isInChIKey,
  isIupacName,
  isMinimalProduct,
  isParsedPrice,
  isPaymentMethod,
  isProduct,
  isPubChemCID,
  isQuantityObject,
  isShippingRange,
  isSmiles,
  isUOM,
  toPubChemCID,
} from '@/utils/typeGuards/common';
import { isAvailability, isProductImage, isValidVariant } from '@/utils/typeGuards/productbuilder';
 
/**
 * The names of every {@link ProductBuilder} method whose signature is exactly
 * `(value: unknown) => ProductBuilder<T>` — i.e. the validating single-argument setters
 * {@link ProductBuilder.setData} can dispatch to purely by name. The overloaded, multi-field
 * `setPricing` doesn't match; setData routes its constituent fields (`price`, `currencyCode`,
 * `currencySymbol`) to their individual setters instead.
 * @typeParam T - The product type the builder produces.
 * @group Utils
 */
type UnarySetterName<T extends Product> = {
  [K in keyof ProductBuilder<T>]: ProductBuilder<T>[K] extends (value: unknown) => ProductBuilder<T>
    ? K
    : never;
}[keyof ProductBuilder<T>];
 
/**
 * A {@link ProductBuilder.setData} dispatch handler for one {@link Product} field: the name of a
 * validating unary setter (called by name), or `null` for synthetic/display-only fields that are
 * intentionally dropped on hydration.
 * @typeParam T - The product type the builder produces.
 * @group Utils
 */
type SetDataHandler<T extends Product> = UnarySetterName<T> | null;
 
/**
 * Builder class for constructing Product objects with a fluent interface.
 * Implements the Builder pattern to handle complex product construction with optional fields
 * and data validation.
 *
 * @remarks
 * This is a utility class for building product data up over different requests.
 * It is used to build the product data up over different requests, and then return a complete
 * product object.
 *
 * @category Utils
 * @summary
 * Builder class for constructing Product objects with a fluent interface.
 * Implements the Builder pattern to handle complex product construction with optional fields
 * and data validation.
 * @example
 * ```typescript
 * const builder = new ProductBuilder<Product>('https://example.com');
 * const product = await builder
 *   .setBasicInfo('Sodium Chloride', '/products/nacl', 'ChemSupplier')
 *   .setPricing(29.99, 'USD', '$')
 *   .setQuantity(500, 'g')
 *   .setDescription('99.9% pure NaCl')
 *   .setCAS('7647-14-5')
 *   .build();
 *
 * if (product) {
 *   console.log(product.title); // "Sodium Chloride"
 *   console.log(product.price); // 29.99
 *   console.log(product.uom);   // "g"
 * }
 * ```
 * @source
 */
export class ProductBuilder<T extends Product> {
  /** The partial product object being built */
  private product: Partial<T> = {};
 
  /** The base URL of the supplier's website. Fixed at construction; used to resolve relative URLs. */
  private readonly baseURL: string;
 
  /** The logger for the product builder */
  private logger: Logger;
 
  /** Whether to show failed validation warnings */
  private showFailedValidation: boolean = IS_DEV_BUILD;
 
  /**
   * Creates a new ProductBuilder instance.
   * @param baseURL - The base URL of the supplier's website, used for resolving relative URLs
   * @example
   * ```typescript
   * const builder = new ProductBuilder('https://example.com');
   * ```
   * @source
   */
  constructor(baseURL: string) {
    this.baseURL = baseURL;
    this.logger = new Logger('ProductBuilder');
  }
 
  /**
   * Sets the data for the product by merging the provided data object.
   *
   * @param data - The data to merge into the product
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setData({
   *   title: "Test Chemical",
   *   price: 29.99,
   *   quantity: 500,
   *   uom: "g"
   * });
   * ```
   * @source
   */
  setData(data: Partial<T>): ProductBuilder<T> {
    if (data === null || typeof data !== 'object') {
      return this;
    }
    // setData exists for cache hydration (createFromCache / SupplierBase): it revives builders
    // from untrusted, unknown-shaped cached data, so every key is routed through its validating
    // setter rather than a blind Object.assign that could bypass the per-field checks.
    //
    // Each key maps to a handler: the name of a validating unary setter (called by name), or null
    // for synthetic/display-only fields that are intentionally dropped on hydration.
    // Typing this `Record<keyof Product, …>` keeps it exhaustive — adding a Product field without
    // a handler is a compile error. Keys not part of Product are dropped with a warning.
    const handlers: Record<keyof Product, SetDataHandler<T>> = {
      title: 'setTitle',
      supplier: 'setSupplier',
      url: 'setURL',
      permalink: 'setPermalink',
      description: 'setDescription',
      shortDescription: 'setShortDescription',
      manufacturer: 'setManufacturer',
      vendor: 'setVendor',
      sku: 'setSku',
      id: 'setID',
      uuid: 'setUUID',
      cacheKey: 'setCacheKey',
      cas: 'setCAS',
      formula: 'setFormula',
      smiles: 'setSmiles',
      iupacName: 'setIupacName',
      pubchemId: 'setPubchemId',
      inchiKey: 'setInChIKey',
      inchi: 'setInChI',
      moleweight: 'setMoleweight',
      purity: 'setPurity',
      grade: 'setGrade',
      concentration: 'setConcentration',
      moles: 'setMoles',
      price: 'setPrice',
      usdPrice: 'setUsdPrice',
      localPrice: 'setLocalPrice',
      currencyCode: 'setCurrencyCode',
      currencySymbol: 'setCurrencySymbol',
      uom: 'setUOM',
      baseUom: 'setBaseUom',
      baseQuantity: 'setBaseQuantity',
      quantity: 'setQuantity',
      rating: 'setRating',
      reviewCount: 'setReviewCount',
      status: 'setStatus',
      statusTxt: 'setStatusTxt',
      shippingInformation: 'setShippingInformation',
      purchaseRestriction: 'setPurchaseRestriction',
      attributes: 'setAttributes',
      images: 'addImages',
      sdsUrl: 'setSDSUrl',
      coaUrl: 'setCoaUrl',
      specSheetUrl: 'setSpecSheetUrl',
      docLinks: 'setDocLinks',
      supplierCountry: 'setSupplierCountry',
      supplierShipping: 'setSupplierShipping',
      paymentMethods: 'setSupplierPaymentMethods',
      supplierEbayStoreURL: 'setSupplierEbayStoreURL',
      supplierAmazonStoreURL: 'setSupplierAmazonStoreURL',
      matchPercentage: 'setMatchPercentage',
      availability: 'setAvailability',
      variants: 'setVariants',
      // Synthetic/display-only fields that are recomputed after hydration (or redundant with a
      // field that round-trips on its own) — dropped so stale cached values can't leak back in.
      _fuzz: null, // redundant with matchPercentage, which round-trips via setMatchPercentage
      _id: null, // positional row index, re-stamped by useSearch after every search
      parentProduct: null,
      priceSeriesKey: null,
      priceTrendValue: null,
    };
 
    // `Object.entries` widens each key to `string`; narrow it back via `in` (handlers is keyed
    // by every `keyof Product`) so no cast is needed.
    const isProductKey = (key: string): key is keyof Product => key in handlers;
 
    for (const [key, value] of Object.entries(data)) {
      if (!isProductKey(key)) {
        this.logger.warn('setData| dropping unsupported key', { key, value });
        continue;
      }
      const handler = handlers[key];
      if (handler === null) {
        continue;
      }
      // handler is a UnarySetterName<T> — every such setter is (value: unknown) => this, so
      // calling by name is type-safe without a cast.
      this[handler](value);
    }
    return this;
  }
 
  /**
   * Sets the basic information for the product by delegating to {@link setTitle},
   * {@link setURL}, and {@link setSupplier}, each of which validates its own input.
   *
   * @param title - The display name/title of the product, or any value (invalid input is ignored)
   * @param url - The URL where the product can be found (can be relative to baseURL), or any value
   * @param supplier - The name of the supplier/vendor, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setBasicInfo(
   *   'Hydrochloric Acid',
   *   '/products/hcl-solution',
   *   'ChemSupplier'
   * );
   * ```
   * @source
   */
  setBasicInfo(title: unknown, url: unknown, supplier: unknown): ProductBuilder<T> {
    return this.setTitle(title).setURL(url).setSupplier(supplier);
  }
 
  /**
   * Sets the product title. A value that isn't a non-empty string is ignored.
   * @param title - The display name/title of the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setTitle("Hydrochloric Acid");
   * ```
   * @source
   */
  setTitle(title: unknown): ProductBuilder<T> {
    if (typeof title === 'string' && title.trim().length > 0) {
      this.product.title = title;
    } else if (this.shouldWarn(title)) {
      this.logger.warn('setTitle| Invalid title value', { title, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the supplier name. A value that isn't a non-empty string is ignored.
   * @param supplier - The name of the supplier/vendor, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplier("ChemSupplier");
   * ```
   * @source
   */
  setSupplier(supplier: unknown): ProductBuilder<T> {
    if (typeof supplier === 'string' && supplier.trim().length > 0) {
      this.product.supplier = supplier;
    } else if (this.shouldWarn(supplier)) {
      this.logger.warn('setSupplier| Invalid supplier value', { supplier, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the URL for the product. A value that isn't a usable URL is ignored.
   * @param url - The URL to set, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setURL("https://example.com/products/sodium-chloride-500g");
   * ```
   * @source
   */
  setURL(url: unknown): ProductBuilder<T> {
    const href = this.resolveHref(url);
    if (href) {
      this.product.url = href;
    } else if (this.shouldWarn(url)) {
      this.logger.warn('setURL| Invalid URL', { url, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the permalink for the product. A value that isn't a usable URL is ignored.
   * @param permalink - The permalink to set, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPermalink("https://example.com/products/sodium-chloride-500g");
   * ```
   * @source
   */
  setPermalink(permalink: unknown): ProductBuilder<T> {
    const href = this.resolveHref(permalink);
    if (href) {
      this.product.permalink = href;
    } else if (this.shouldWarn(permalink)) {
      this.logger.warn('setPermalink| Invalid permalink', { permalink, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the SDS URL for the product. Accepts the often-optional result of a parser directly;
   * a value that isn't a usable URL (undefined, empty, wrong type) is ignored.
   * @param sdsUrl - The SDS URL to set, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSDSUrl("https://example.com/sds.pdf");
   * builder.setSDSUrl(findPdfHref(html)); // no-ops when findPdfHref returns undefined
   * ```
   * @source
   */
  setSDSUrl(sdsUrl: unknown): ProductBuilder<T> {
    const href = this.resolveHref(sdsUrl);
    if (href) {
      this.product.sdsUrl = href;
    } else if (this.shouldWarn(sdsUrl)) {
      this.logger.warn('setSDSUrl| Invalid SDS URL', { sdsUrl, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the Certificate of Analysis (COA) URL for the product. Accepts the often-optional result
   * of a parser directly; a value that isn't a usable URL (undefined, empty, wrong type) is ignored.
   * @param coaUrl - The COA URL to set, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setCoaUrl("https://example.com/coa.pdf");
   * builder.setCoaUrl(findPdfHref(html)); // no-ops when findPdfHref returns undefined
   * ```
   * @source
   */
  setCoaUrl(coaUrl: unknown): ProductBuilder<T> {
    const href = this.resolveHref(coaUrl);
    if (href) {
      this.product.coaUrl = href;
    } else if (this.shouldWarn(coaUrl)) {
      this.logger.warn('setCoaUrl| Invalid COA URL', { coaUrl, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the spec sheet URL for the product. A value that isn't a non-empty string is ignored.
   * @param specSheetUrl - The spec sheet URL to set, or any value (non-strings are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSpecSheetUrl("https://example.com/spec-sheet.pdf");
   * ```
   * @source
   */
  setSpecSheetUrl(specSheetUrl: unknown): ProductBuilder<T> {
    const href = this.resolveHref(specSheetUrl);
    if (href) {
      this.product.specSheetUrl = href;
    } else if (this.shouldWarn(specSheetUrl)) {
      this.logger.warn('setSpecSheetUrl| Invalid spec sheet URL', { specSheetUrl, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the product's default (primary) full-size image. Placed first among the image-type entries
   * so it's treated as the default; a previous default set this way is replaced. A value that isn't
   * a usable URL is ignored; alt text is only applied alongside a valid image.
   * @param imageURL - The image URL to set, or any value (non-URLs are ignored)
   * @param imageAltText - The alt text for the image, or any value (non-strings are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setImage("https://example.com/image.jpg");
   * builder.setImage("https://example.com/image.jpg", "Sodium Chloride ACS Grade 500g");
   * ```
   * @source
   */
  setImage(imageURL: unknown, imageAltText?: unknown): ProductBuilder<T> {
    const image = this.buildImage(imageURL, 'image', imageAltText);
    if (image) {
      this.setDefaultImage(image);
    } else if (this.shouldWarn(imageURL)) {
      this.logger.warn('setImage| Invalid image URL', { imageURL, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the product's default (primary) thumbnail. Placed first among the thumbnail-type entries so
   * it's treated as the default; a previous default set this way is replaced. A supplier's main
   * thumbnail is often distinct from its gallery images, so this is kept as its own entry rather than
   * attached to any image. A value that isn't a usable URL is ignored.
   * @param thumbnail - The thumbnail URL to set, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setThumbnail("https://example.com/thumb.jpg");
   * ```
   * @source
   */
  setThumbnail(thumbnail: unknown): ProductBuilder<T> {
    const image = this.buildImage(thumbnail, 'thumbnail');
    if (image) {
      this.setDefaultImage(image);
    } else if (this.shouldWarn(thumbnail)) {
      this.logger.warn('setThumbnail| Invalid thumbnail URL', { thumbnail, builder: this });
    }
    return this;
  }
 
  /**
   * Appends a full-size image to the product's image list. Unlike {@link setImage}, this doesn't
   * replace the default — use it for gallery images. A value that isn't a usable URL is ignored.
   * @param imageURL - The image URL to add, or any value (non-URLs are ignored)
   * @param imageAltText - The alt text for the image, or any value (non-strings are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addImage("https://example.com/a.jpg", "front label");
   * ```
   * @source
   */
  addImage(imageURL: unknown, imageAltText?: unknown): ProductBuilder<T> {
    const image = this.buildImage(imageURL, 'image', imageAltText);
    if (image) {
      this.pushImage(image);
    } else if (this.shouldWarn(imageURL)) {
      this.logger.warn('addImage| Invalid image URL', { imageURL, builder: this });
    }
    return this;
  }
 
  /**
   * Appends a thumbnail to the product's image list. Unlike {@link setThumbnail}, this doesn't
   * replace the default. A value that isn't a usable URL is ignored.
   * @param thumbnail - The thumbnail URL to add, or any value (non-URLs are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addThumbnail("https://example.com/a-t.jpg");
   * ```
   * @source
   */
  addThumbnail(thumbnail: unknown): ProductBuilder<T> {
    const image = this.buildImage(thumbnail, 'thumbnail');
    if (image) {
      this.pushImage(image);
    } else if (this.shouldWarn(thumbnail)) {
      this.logger.warn('addThumbnail| Invalid thumbnail URL', { thumbnail, builder: this });
    }
    return this;
  }
 
  /**
   * Appends multiple full-size images to the product's image list. Each entry may be a plain URL
   * string (added via {@link addImage} as an `"image"`) or a pre-built `{ href, type, altText? }`
   * {@link ProductImage} object (whose explicit `type` is preserved, so mixed image/thumbnail arrays
   * are supported). Entries that don't resolve are ignored.
   * @param images - An array of URL strings and/or {@link ProductImage} values, or any value (non-arrays are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addImages(["https://example.com/a.jpg", "https://example.com/b.jpg"]);
   * builder.addImages([{ href: "https://example.com/a-t.jpg", type: "thumbnail" }]);
   * ```
   * @source
   */
  addImages(images: unknown): ProductBuilder<T> {
    this.addImageEntries(images, 'image');
    return this;
  }
 
  /**
   * Appends multiple thumbnails to the product's image list. Each entry may be a plain URL string
   * (added via {@link addThumbnail} as a `"thumbnail"`) or a pre-built `{ href, type, altText? }`
   * {@link ProductImage} object (whose explicit `type` is preserved). Entries that don't resolve are
   * ignored.
   * @param thumbnails - An array of URL strings and/or {@link ProductImage} values, or any value (non-arrays are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addThumbnails(["https://example.com/a-t.jpg", "https://example.com/b-t.jpg"]);
   * ```
   * @source
   */
  addThumbnails(thumbnails: unknown): ProductBuilder<T> {
    this.addImageEntries(thumbnails, 'thumbnail');
    return this;
  }
 
  /**
   * Whether an invalid value is worth a validation warning. Only in dev builds, and only when a
   * value was actually supplied: `undefined`, `null` and blank strings mean "this supplier has no
   * data for that field", which is normal and would otherwise flood the log (one warning per
   * product per field).
   *
   * @param value - The value a setter rejected
   * @returns `true` when the rejection should be logged
   * @example
   * ```typescript
   * this.shouldWarn('');        // false (blank)
   * this.shouldWarn(undefined); // false (absent)
   * this.shouldWarn(42);        // true when a string was expected
   * ```
   * @source
   */
  private shouldWarn(value: unknown): boolean {
    if (!this.showFailedValidation || value == null) {
      return false;
    }
    return !(typeof value === 'string' && value.trim() === '');
  }
 
  /**
   * Appends each entry of an array to the product's image list. Pre-built {@link ProductImage}
   * objects are resolved with their explicit `type` preserved; any other entry is treated as a raw
   * URL and added with `defaultType` via {@link addImage}/{@link addThumbnail}.
   * @param entries - The array of URL strings and/or {@link ProductImage} values (non-arrays are ignored)
   * @param defaultType - The `type` to stamp on raw-URL entries
   * @returns Nothing.
   * @example
   * ```typescript
   * this.addImageEntries(["/a.jpg"], "image"); // adds { href: "https://base/a.jpg", type: "image" }
   * this.addImageEntries([{ href: "/a-t.jpg", type: "thumbnail" }], "image"); // preserves "thumbnail"
   * ```
   * @source
   */
  private addImageEntries(entries: unknown, defaultType: ProductImageType): void {
    if (!Array.isArray(entries)) {
      return;
    }
    const uniqueEntries = [...new Set(entries)];
    for (const entry of uniqueEntries) {
      if (isProductImage(entry)) {
        const resolved = this.resolveImageEntry(entry);
        if (resolved) this.pushImage(resolved);
      } else if (defaultType === 'image') {
        this.addImage(entry);
      } else {
        this.addThumbnail(entry);
      }
    }
  }
 
  /**
   * Builds a {@link ProductImage} of the given type from a URL, resolving it to an absolute href, or
   * `undefined` when the URL isn't usable.
   * @param url - The image URL.
   * @param type - Whether the entry is a full-size image or a thumbnail.
   * @param altText - Optional alt text; applied only when it's a non-empty string.
   * @returns The built image entry, or `undefined` when the URL doesn't resolve.
   * @example
   * ```typescript
   * this.buildImage("/a.jpg", "image", "front"); // => { href: "https://base/a.jpg", type: "image", altText: "front" }
   * this.buildImage("", "thumbnail"); // => undefined
   * ```
   * @source
   */
  private buildImage(
    url: unknown,
    type: ProductImageType,
    altText?: unknown,
  ): ProductImage | undefined {
    const href = this.resolveHref(url);
    if (!href) {
      return undefined;
    }
    const image: ProductImage = { href, type };
    if (typeof altText === 'string' && altText.trim().length > 0) {
      image.altText = altText;
    }
    return image;
  }
 
  /**
   * Normalizes an unknown `{ href, type, altText? }` value into a {@link ProductImage} with an
   * absolute href, or `undefined` when it isn't a valid entry or its href doesn't resolve.
   * @param entry - The candidate image entry.
   * @returns The resolved image entry, or `undefined` when it's not valid.
   * @example
   * ```typescript
   * this.resolveImageEntry({ href: "/a.jpg", type: "image" }); // => { href: "https://base/a.jpg", type: "image" }
   * this.resolveImageEntry({ href: "/a.jpg", type: "banner" }); // => undefined
   * ```
   * @source
   */
  private resolveImageEntry(entry: unknown): ProductImage | undefined {
    if (!isProductImage(entry)) {
      return undefined;
    }
    return this.buildImage(entry.href, entry.type, entry.altText);
  }
 
  /**
   * Appends an image entry to the product's image list, creating the list on first use.
   * @param image - The already-resolved image entry to append.
   * @returns Nothing.
   * @example
   * ```typescript
   * this.pushImage({ href: "https://example.com/a.jpg", type: "image" });
   * ```
   * @source
   */
  private pushImage(image: ProductImage): void {
    if (!this.product.images) {
      this.product.images = [];
    }
    this.product.images.push(image);
  }
 
  /**
   * Makes an image entry the default for its type by inserting it at the front of the list, so it's
   * the first entry of that type. Existing entries (gallery images/thumbnails) are kept.
   * @param image - The image entry to set as its type's default.
   * @returns Nothing.
   * @example
   * ```typescript
   * this.setDefaultImage({ href: "https://example.com/a.jpg", type: "image" });
   * ```
   * @source
   */
  private setDefaultImage(image: ProductImage): void {
    if (!this.product.images) {
      this.product.images = [];
    }
    this.product.images.unshift(image);
  }
 
  /**
   * Sets the formula for the product. A value that isn't a recognizable formula is ignored.
   *
   * @param formula - The formula to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setFormula('foobar K<sub>2</sub>Cr<sub>2</sub>O<sub>7</sub> baz');
   * // sets this.product.formula to "K₂Cr₂O₇"
   * builder.setFormula("H<sub>2</sub>SO<sub>4</sub>");
   * // sets this.product.formula to "H₂SO₄"
   * builder.setFormula("NaBH4");
   * // sets this.product.formula to "NaBH4" (clean formula stored as-is)
   * builder.setFormula("Just some text");
   * // leaves this.product.formula unset
   * ```
   * @source
   */
  setFormula(formula: unknown): ProductBuilder<T> {
    if (typeof formula !== 'string' || formula.trim().length === 0) {
      return this;
    }
    const trimmed = formula.trim();
    // Store as-is when the value is already a finished formula: a clean ASCII formula (incl. ones
    // containing "1" like "C12H22O11", which findFormulaInHtml mishandles), or one already
    // display-formatted with unicode subscripts / hydrate notation (e.g. "NH₄NaC₄H₄O₆ x 4H₂O"), or
    // a polymer repeating unit carrying a variable subscript index (e.g. "(C3H3NaO2)ₙ"). Re-parsing
    // those would corrupt them.
    if (!trimmed.includes('<sub>') && (isMoleForm(trimmed) || /[₀-₉ₙₘₓ]/.test(trimmed))) {
      this.product.formula = trimmed;
      return this;
    }
    // Otherwise extract and subscript-format a formula from HTML/surrounding text.
    const parsedResult = findFormulaInHtml(trimmed);
    if (parsedResult) {
      this.product.formula = parsedResult;
    }
    return this;
  }
 
  /**
   * Sets the grade/purity level of the product.
   * Only sets the grade if a non-empty string is provided.
   *
   * @param grade - The grade or purity level of the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setGrade("ACS Grade");
   * builder.setGrade("Reagent Grade");
   * ```
   * @source
   */
  setGrade(grade: unknown): ProductBuilder<T> {
    if (typeof grade === 'string' && grade.trim().length > 0) {
      this.product.grade = grade;
    } else if (this.shouldWarn(grade)) {
      this.logger.warn('setGrade| Invalid grade value', { grade, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the price for the product. This is useful for if the price and currency are easier
   * to add separately (eg: getting the currency code is done in a different request handler)
   * @param price - The price to set (a number or numeric string), or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPrice(123.34);
   * ```
   * @source
   */
  setPrice(price: unknown): ProductBuilder<T> {
    if (typeof price !== 'number' && typeof price !== 'string') {
      // A non-null, non-numeric value is a genuine misuse worth flagging; absent input is a quiet no-op.
      if (this.shouldWarn(price)) {
        this.logger.warn('setPrice| Invalid price', {
          price,
          builder: this,
        });
      }
      return this;
    }
    const value = Number(price);
    if (!Number.isNaN(value)) {
      this.product.price = value;
    }
    return this;
  }
 
  /**
   * Sets the currency symbol for the product. This is useful for if the price and currency are easier
   * to add separately (eg: getting the currency code is done in a different request handler).
   * If no currency symbol is set, then it will be inferred from the currencyCode
   * @param sign - The currency symbol to set, or any value (anything that isn't a known symbol is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setCurrencySymbol('$');
   * ```
   * @source
   */
  setCurrencySymbol(sign: unknown): ProductBuilder<T> {
    if (isCurrencySymbol(sign)) {
      this.product.currencySymbol = sign;
    } else if (this.shouldWarn(sign)) {
      this.logger.warn('setCurrencySymbol| Invalid currency symbol', {
        sign,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the currency code for the product. This is useful for if the price and currency are easier
   * to add separately (eg: getting the currency code is done in a different request handler).
   * @param code - The currency code to set, or any value (anything that isn't a known code is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setCurrencyCode('USD');
   * ```
   * @source
   */
  setCurrencyCode(code: unknown): ProductBuilder<T> {
    if (isCurrencyCode(code)) {
      this.product.currencyCode = code;
    } else if (this.shouldWarn(code)) {
      this.logger.warn('setCurrencyCode| Invalid currency code', {
        code,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the pricing information for the product including price and currency details when given a parsedPrice object
   * @overload
   * @param price - ParsedPrice instance
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPricing(parsePrice('$123.34'));
   * // Sets this.product.price to 123.34
   * // Sets this.product.currencyCode to 'USD'
   * // Sets this.product.currencySymbol to '$'
   * ```
   * @source
   */
  setPricing(price: ParsedPrice): ProductBuilder<T>;
  /**
   * Sets the pricing information for the product including price and currency details when given a price
   * @overload
   * @param price - Price in string format
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPricing('$123.34');
   * // Sets this.product.price to 123.34
   * // Sets this.product.currencyCode to 'USD'
   * // Sets this.product.currencySymbol to '$'
   * ```
   * @source
   */
  setPricing(price: string): ProductBuilder<T>;
  /**
   * Sets the pricing information for the product including price and currency details when given a price
   * @overload
   * @param price - Price in number format
   * @param currencyCode - The ISO currency code (e.g., 'USD', 'EUR')
   * @param currencySymbol - The currency symbol (e.g., '$', '€')
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPricing(123.34, 'USD', '$');
   * // Sets this.product.price to 123.34
   * // Sets this.product.currencyCode to 'USD'
   * // Sets this.product.currencySymbol to '$'
   * ```
   * @source
   */
  setPricing(
    price: number | string,
    currencyCode: string,
    currencySymbol: string,
  ): ProductBuilder<T>;
  setPricing(
    price: number | string | ParsedPrice,
    currencyCode?: string,
    currencySymbol?: string,
  ): ProductBuilder<T> {
    if (isParsedPrice(price)) {
      this.product.price = price.price;
      this.product.currencyCode = price.currencyCode;
      this.product.currencySymbol = price.currencySymbol;
      return this;
    }
    if (typeof currencyCode === 'string') this.product.currencyCode = currencyCode;
    if (typeof currencySymbol === 'string') this.product.currencySymbol = currencySymbol;
 
    if (typeof price === 'string') {
      if (Number.isNaN(Number(price)) === false) {
        this.product.price = Number(price);
        return this;
      }
 
      const parsedPrice = parsePrice(price);
      if (parsedPrice) {
        this.product.price = parsedPrice.price;
        this.product.currencyCode = parsedPrice.currencyCode;
        this.product.currencySymbol = parsedPrice.currencySymbol;
        return this;
      }
    }
 
    this.product.price = Number(price);
 
    return this;
  }
 
  /**
   * Sets the quantity information for the product from an arbitrary value, guarding internally.
   * Accepts a {@link QuantityObject}, a string (`'500g'` — parsed into quantity + uom), or a
   * numeric quantity with an optional `uom`. When a bare number is given with **no** `uom`, only
   * the numeric `quantity` is set and the uom is left untouched — this is what lets {@link setData}
   * drive it, since there `quantity` and `uom` arrive as independent keys. Invalid input is ignored.
   * @param quantity - A QuantityObject, a `'<amount><unit>'` string, or a numeric quantity (any other value is ignored)
   * @param uom - The unit of measure (e.g. `'g'`, `'ml'`), used only with a numeric `quantity`; omit to set the amount alone
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setQuantity(parseQuantity('500g')); // quantity 500, uom 'g'
   * builder.setQuantity('500g');                // quantity 500, uom 'g'
   * builder.setQuantity(500, 'g');              // quantity 500, uom 'g'
   * builder.setQuantity(500);                   // quantity 500, uom unchanged
   * ```
   * @source
   */
  setQuantity(quantity: unknown, uom?: unknown): ProductBuilder<T> {
    if (typeof quantity === 'undefined') return this;
 
    if (isQuantityObject(quantity)) {
      this.product.quantity = quantity.quantity;
      this.product.uom = quantity.uom;
      return this;
    }
 
    if (typeof quantity === 'string' && typeof uom === 'undefined') {
      const parsedQuantity = parseQuantity(quantity);
      if (parsedQuantity) {
        this.product.quantity = parsedQuantity.quantity;
        this.product.uom = parsedQuantity.uom;
        return this;
      }
 
      const [qty, unit] = quantity.split(/\s(.+)/s);
 
      if (Number.isNaN(Number(qty))) {
        this.logger.warn(`setQuantity| Unable to parse quantity from string`, {
          quantity,
          builder: this,
        });
        return this;
      }
      this.product.quantity = Number(qty);
      this.product.uom = unit;
      return this;
    }
 
    if (typeof quantity === 'number') {
      this.product.quantity = quantity;
      // Only set uom when explicitly provided; setData sets it via its own `uom` key.
      if (typeof uom === 'string') {
        this.product.uom = uom;
      }
      return this;
    }
 
    if (this.showFailedValidation) {
      this.logger.warn('setQuantity| Unknown quantity type', {
        quantity,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the moles for the product.
   * @param moles - The moles to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setMoles(23.5);
   * ```
   * @source
   */
  setMoles(moles: unknown): ProductBuilder<T> {
    if (typeof moles === 'number' && !Number.isNaN(moles) && moles > 0) {
      this.product.moles = moles;
    } else if (this.shouldWarn(moles)) {
      this.logger.warn('setMoles| Invalid moles', { moles, builder: this });
    }
    return this;
  }
  /**
   * Sets the unit of measure for the product.
   *
   * @param uom - The unit of measure to set, or any value (anything that isn't a known UOM is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setUOM('g');
   * ```
   * @source
   */
  setUOM(uom: unknown): ProductBuilder<T> {
    if (isUOM(uom)) {
      this.product.uom = uom;
    } else if (this.shouldWarn(uom)) {
      this.logger.warn('setUOM| Invalid UOM', { uom, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the country of the supplier.
   *
   * @param country - The country of the supplier, or any value (anything that isn't a known country code is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplierCountry("US");
   * ```
   * @source
   */
  setSupplierCountry(country: unknown): ProductBuilder<T> {
    if (isCountryCode(country)) {
      this.product.supplierCountry = country;
    } else if (this.shouldWarn(country)) {
      this.logger.warn('setSupplierCountry| Invalid country value', { country, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the shipping scope of the supplier.
   *
   * @param shipping - The shipping scope, or any value (anything that isn't a known shipping range is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplierShipping("worldwide");
   * ```
   * @source
   */
  setSupplierShipping(shipping: unknown): ProductBuilder<T> {
    if (isShippingRange(shipping)) {
      this.product.supplierShipping = shipping;
    } else if (this.shouldWarn(shipping)) {
      this.logger.warn('setSupplierShipping| Invalid shipping value', { shipping, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the payment methods accepted by the supplier.
   *
   * @param paymentMethods - A payment method or array of them, or any value (non-payment-method entries are dropped)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplierPaymentMethods(["visa", "mastercard"]);
   * ```
   * @source
   */
  setSupplierPaymentMethods(paymentMethods: unknown): ProductBuilder<T> {
    const candidates = Array.isArray(paymentMethods) ? paymentMethods : [paymentMethods];
    const valid = candidates.filter(isPaymentMethod);
    if (valid.length > 0) {
      this.product.paymentMethods = valid;
    } else if (this.shouldWarn(paymentMethods)) {
      this.logger.warn('setSupplierPaymentMethods| Invalid payment methods', {
        paymentMethods,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Narrows a value to an absolute http(s) URL string.
   *
   * Storefront URLs live on a foreign host, so they can't go through {@link ProductBuilder.resolveHref}
   * (which resolves against the supplier's own `baseURL`), and `isFullURL` is too permissive — it
   * accepts any scheme, including `javascript:`, and these values are rendered into an `href`.
   * @param value - The candidate URL, or any value
   * @returns The normalized absolute URL, or undefined when it isn't one
   * @example
   * ```typescript
   * this.absoluteHttpURL("https://www.ebay.com/str/x"); // "https://www.ebay.com/str/x"
   * this.absoluteHttpURL("javascript:alert(1)");        // undefined
   * ```
   * @source
   */
  private absoluteHttpURL(value: unknown): string | undefined {
    if (typeof value !== 'string' || value.length === 0) return undefined;
    try {
      const url = new URL(value);
      return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : undefined;
    } catch {
      return undefined;
    }
  }
 
  /**
   * Sets the supplier's eBay storefront URL, shown in the expanded product row for suppliers that
   * restrict shipping on their own site but ship more freely via eBay.
   *
   * @param storeURL - The storefront URL, or any value (anything that isn't an absolute http(s) URL is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplierEbayStoreURL("https://www.ebay.com/str/dailybiousa");
   * ```
   * @source
   */
  setSupplierEbayStoreURL(storeURL: unknown): ProductBuilder<T> {
    const href = this.absoluteHttpURL(storeURL);
    if (href) {
      this.product.supplierEbayStoreURL = href;
    } else if (this.shouldWarn(storeURL)) {
      this.logger.warn('setSupplierEbayStoreURL| Invalid eBay store URL', {
        storeURL,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the supplier's Amazon storefront URL. Counterpart to
   * {@link ProductBuilder.setSupplierEbayStoreURL}, for suppliers that accept `"amazononly"`.
   *
   * @param storeURL - The storefront URL, or any value (anything that isn't an absolute http(s) URL is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSupplierAmazonStoreURL("https://www.amazon.com/s?k=HiMedia");
   * ```
   * @source
   */
  setSupplierAmazonStoreURL(storeURL: unknown): ProductBuilder<T> {
    const href = this.absoluteHttpURL(storeURL);
    if (href) {
      this.product.supplierAmazonStoreURL = href;
    } else if (this.shouldWarn(storeURL)) {
      this.logger.warn('setSupplierAmazonStoreURL| Invalid Amazon store URL', {
        storeURL,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the product description.
   *
   * @param description - The detailed description of the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setDescription(
   *   'High purity sodium chloride, 99.9% pure, suitable for laboratory use'
   * );
   * ```
   * @source
   */
  setDescription(description: unknown): ProductBuilder<T> {
    if (typeof description === 'string' && description.trim().length > 0) {
      this.product.description = htmlToAscii(description);
    } else if (this.shouldWarn(description)) {
      this.logger.warn('setDescription| Invalid description', { description, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the short description for the product.
   * @param shortDescription - The short description to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setShortDescription("Sodium Chloride 500g");
   * ```
   * @source
   */
  setShortDescription(shortDescription: unknown): ProductBuilder<T> {
    if (typeof shortDescription === 'string' && shortDescription.trim().length > 0) {
      this.product.shortDescription = htmlToAscii(shortDescription);
    } else if (this.shouldWarn(shortDescription)) {
      this.logger.warn('setShortDescription| Invalid short description', {
        shortDescription,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the rating for the product.
   * @param rating - The rating to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setRating(4.5);
   * ```
   * @source
   */
  setRating(rating: unknown): ProductBuilder<T> {
    if (typeof rating === 'number' || typeof rating === 'string') {
      const value = Number(rating);
      if (!Number.isNaN(value)) {
        this.product.rating = value;
      }
    } else if (this.shouldWarn(rating)) {
      this.logger.warn('setRating| Invalid rating', { rating, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the review count for the product.
   * @param reviewCount - The review count to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setReviewCount(100);
   * ```
   * @source
   */
  setReviewCount(reviewCount: unknown): ProductBuilder<T> {
    if (typeof reviewCount === 'number' || typeof reviewCount === 'string') {
      const value = Number(reviewCount);
      if (!Number.isNaN(value)) {
        this.product.reviewCount = value;
      }
    } else if (reviewCount != null) {
      this.logger.warn('setReviewCount| Invalid review count', { reviewCount, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the CAS (Chemical Abstracts Service) registry number for the product.
   * Validates the CAS number format before setting.
   *
   * @param cas - The CAS registry number in format "XXXXX-XX-X", or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * // For sodium chloride
   * builder.setCAS('7647-14-5');
   * // For invalid CAS number (will not set)
   * builder.setCAS('invalid-cas');
   * ```
   * @source
   */
  setCAS(cas: unknown): ProductBuilder<T> {
    if (typeof cas !== 'string') {
      // Only flag a genuine misuse (a non-string value); an absent value is a quiet no-op.
      if (cas != null) {
        this.logger.warn(`setCAS| Invalid CAS number`, {
          cas,
          builder: this,
        });
      }
      return this;
    }
 
    if (isCAS(cas)) {
      this.product.cas = cas;
    } else {
      const parsedACAS = findCAS(cas);
      if (parsedACAS) {
        this.product.cas = parsedACAS;
      }
    }
    return this;
  }
 
  /**
   * Sets the ID for the product.
   *
   * @param id - The unique identifier for the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setID(12345);
   * ```
   * @source
   */
  setID(id: unknown): ProductBuilder<T> {
    if (typeof id === 'number' || typeof id === 'string') {
      this.product.id = id;
    } else if (this.shouldWarn(id)) {
      this.logger.warn('setID| Invalid ID value', { id, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the UUID for the product.
   *
   * @param uuid - The UUID string for the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setUUID('550e8400-e29b-41d4-a716-446655440000');
   * ```
   * @source
   */
  setUUID(uuid: unknown): ProductBuilder<T> {
    if (typeof uuid === 'string' && uuid.trim().length > 0) {
      this.product.uuid = uuid;
    } else if (this.shouldWarn(uuid)) {
      this.logger.warn('setUUID| Invalid UUID value', { uuid, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the SKU (Stock Keeping Unit) for the product.
   *
   * @param sku - The SKU string for the product, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSku('CHEM-NaCl-500G');
   * ```
   * @source
   */
  setSku(sku: unknown): ProductBuilder<T> {
    if (typeof sku === 'string' && sku.trim().length > 0) {
      this.product.sku = sku;
    } else if (this.shouldWarn(sku)) {
      this.logger.warn('setSku| Invalid SKU value', { sku, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the stable per-product cache/exclusion identity (see
   * {@link Product.cacheKey}). Accepts a non-empty string or a number
   * (coerced to string, since some suppliers key on a numeric id). Invalid
   * input is ignored.
   * @param cacheKey - The identity string/number, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setCacheKey("FAM_889460");
   * builder.setCacheKey(12345); // stored as "12345"
   * ```
   * @source
   */
  setCacheKey(cacheKey: unknown): ProductBuilder<T> {
    if (typeof cacheKey === 'string' && cacheKey.trim().length > 0) {
      this.product.cacheKey = cacheKey;
    } else if (typeof cacheKey === 'number' && Number.isFinite(cacheKey)) {
      this.product.cacheKey = String(cacheKey);
    } else if (this.shouldWarn(cacheKey)) {
      this.logger.warn('setCacheKey| Invalid cache key value', { cacheKey, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the SMILES for the product. An absent value (undefined/null/empty) is ignored silently;
   * a value that is present but fails SMILES validation is ignored and logged as a warning.
   * @param smiles - The SMILES to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setSmiles("C1=CC=CC=C1");
   * builder.setSmiles(undefined); // no-op, no warning
   * ```
   * @source
   */
  setSmiles(smiles: unknown): ProductBuilder<T> {
    if (isSmiles(smiles)) {
      this.product.smiles = smiles;
    } else if (
      smiles !== undefined &&
      smiles !== null &&
      smiles !== '' &&
      this.showFailedValidation
    ) {
      this.logger.warn('setSmiles| Invalid SMILES', {
        smiles,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the IUPAC name for the product. An absent value (undefined/null/empty) is ignored
   * silently; a value that is present but not a usable name is ignored and logged as a warning.
   * @param iupacName - The IUPAC name to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setIupacName("dipotassium;oxalate");
   * builder.setIupacName(undefined); // no-op, no warning
   * ```
   * @source
   */
  setIupacName(iupacName: unknown): ProductBuilder<T> {
    if (isIupacName(iupacName)) {
      this.product.iupacName = iupacName;
    } else if (
      iupacName !== undefined &&
      iupacName !== null &&
      iupacName !== '' &&
      this.showFailedValidation
    ) {
      this.logger.warn('setIupacName| Invalid IUPAC name', {
        iupacName,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the PubChem Compound ID (CID) for the product. Numeric strings are coerced first; an
   * absent value (undefined/null/empty) is ignored silently; a value that is present but not a
   * positive integer is ignored and logged as a warning.
   * @param pubchemId - The PubChem CID to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPubchemId(11413);
   * builder.setPubchemId("11413"); // coerced to 11413
   * ```
   * @source
   */
  setPubchemId(pubchemId: unknown): ProductBuilder<T> {
    if (isPubChemCID(pubchemId)) {
      this.product.pubchemId = toPubChemCID(pubchemId);
    } else if (
      pubchemId !== undefined &&
      pubchemId !== null &&
      pubchemId !== '' &&
      this.showFailedValidation
    ) {
      this.logger.warn('setPubchemId| Invalid PubChem CID', {
        pubchemId,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the InChIKey for the product. An absent value (undefined/null/empty) is ignored silently;
   * a value that is present but fails InChIKey validation is ignored and logged as a warning.
   * @param inchiKey - The InChIKey to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setInChIKey("IRXRGVFLQOSHOH-UHFFFAOYSA-L");
   * builder.setInChIKey(undefined); // no-op, no warning
   * ```
   * @source
   */
  setInChIKey(inchiKey: unknown): ProductBuilder<T> {
    if (isInChIKey(inchiKey)) {
      this.product.inchiKey = inchiKey;
    } else if (
      inchiKey !== undefined &&
      inchiKey !== null &&
      inchiKey !== '' &&
      this.showFailedValidation
    ) {
      this.logger.warn('setInChIKey| Invalid InChIKey', {
        inchiKey,
        builder: this,
      });
    }
    return this;
  }
 
  /**
   * Sets the InChI string for the product. An absent value (undefined/null/empty) is ignored
   * silently; a value that is present but fails InChI validation is ignored and logged as a
   * warning.
   * @param inchi - The InChI string to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setInChI("1S/C2H2O4.2K/c3-1(4)2(5)6;;/h(H,3,4)(H,5,6);;/q;2*+1/p-2");
   * builder.setInChI(undefined); // no-op, no warning
   * ```
   * @source
   */
  setInChI(inchi: unknown): ProductBuilder<T> {
    if (isInChI(inchi)) {
      this.product.inchi = inchi;
    } else if (inchi !== undefined && inchi !== null && inchi !== '' && this.showFailedValidation) {
      this.logger.warn('setInChI| Invalid InChI', {
        inchi,
        builder: this,
      });
    }
    return this;
  }
  /**
   * Sets the vendor for the product.
   *
   * @param vendor - The vendor name, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setVendor('Vendor Name');
   * ```
   * @source
   */
  setVendor(vendor: unknown): ProductBuilder<T> {
    if (typeof vendor === 'string' && vendor.trim().length > 0) {
      this.product.vendor = vendor;
    } else if (this.shouldWarn(vendor)) {
      this.logger.warn('setVendor| Invalid vendor value', { vendor, builder: this });
    }
    return this;
  }
 
  /**
   * Tries to determine the availability of the product based on variable input.
   *
   * @param availability - The availability of the product
   * @returns The availability of the product
   * @example
   * ```typescript
   * // In stock
   * builder.determineAvailability("instock");
   * builder.determineAvailability(true);
   * builder.determineAvailability("outofstock");
   * builder.determineAvailability("unavailable");
   * builder.determineAvailability(false);
   * builder.determineAvailability("preorder");
   * builder.determineAvailability("backorder");
   * builder.determineAvailability("discontinued");
   * ```
   * @source
   */
  determineAvailability(availability?: unknown): Maybe<Availability> {
    if (typeof availability === 'undefined') return;
 
    if (isAvailability(availability)) {
      // isAvailability accepts strings case-insensitively, so normalize to the
      // canonical lowercase enum member rather than storing the raw input
      // (e.g. schema.org's "PreOrder" -> "preorder").
      if (typeof availability === 'string') {
        const normalized = availability.toLowerCase();
        return isAvailability(normalized) ? normalized : availability;
      }
      return availability;
    }
 
    if (typeof availability === 'boolean')
      return availability ? AVAILABILITY.IN_STOCK : AVAILABILITY.OUT_OF_STOCK;
 
    if (typeof availability === 'string') {
      // converting to lower and removing all non-alpha characters just to standardize the values for easier processing.
      switch (availability.toLowerCase().replaceAll(/[^a-z]/g, '')) {
        case 'instock':
        case 'available':
          return AVAILABILITY.IN_STOCK;
        case 'limitedstock':
        case 'limitedavailability':
          return AVAILABILITY.LIMITED_STOCK;
        case 'unavailable':
          return AVAILABILITY.UNAVAILABLE;
        case 'outofstock':
          return AVAILABILITY.OUT_OF_STOCK;
        case 'soldout':
          return AVAILABILITY.SOLD_OUT;
        case 'preorder':
          return AVAILABILITY.PRE_ORDER;
        case 'presale':
          return AVAILABILITY.PRE_SALE;
        case 'madetoorder':
          return AVAILABILITY.MADE_TO_ORDER;
        case 'backorder':
          return AVAILABILITY.BACKORDER;
        case 'reserved':
          return AVAILABILITY.RESERVED;
        case 'onlineonly':
          return AVAILABILITY.ONLINE_ONLY;
        case 'instoreonly':
          return AVAILABILITY.IN_STORE_ONLY;
        case 'discontinued':
          return AVAILABILITY.DISCONTINUED;
        default:
          return;
      }
    }
  }
 
  /**
   * Sets the availability of the product.
   *
   * @param availability - The availability of the product
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * // In stock
   * builder.setAvailability("IN_STOCK");
   * // Set as in stock
   * builder.setAvailability(false);
   * // Out of stock
   * // etc
   * ```
   * @source
   */
  setAvailability(availability: unknown): ProductBuilder<T> {
    const avail = this.determineAvailability(availability);
 
    if (typeof avail === 'undefined') {
      this.logger.warn('Unknown availability', { availability, builder: this });
      return this;
    }
 
    this.product.availability = avail;
    return this;
  }
 
  /**
   * Adds a single variant to the product.
   *
   * @param variant - The variant object to add
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addVariant({
   *   title: '500g Package',
   *   price: 49.99,
   *   quantity: 500,
   *   uom: 'g',
   *   sku: 'CHEM-500G'
   * });
   * ```
   * @source
   */
  addVariant(variant: Partial<Variant>): ProductBuilder<T> {
    if (!this.product.variants) {
      this.product.variants = [];
    }
    this.product.variants.push(variant);
    return this;
  }
 
  /**
   * Adds multiple variants to the product at once.
   *
   * @param variants - Array of variant objects to add
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.addVariants([
   *   {
   *     title: '500g Package',
   *     price: 49.99,
   *     quantity: 500,
   *     uom: 'g'
   *   },
   *   {
   *     title: '1kg Package',
   *     price: 89.99,
   *     quantity: 1000,
   *     uom: 'g'
   *   }
   * ]);
   * ```
   * @source
   */
  addVariants(variants: Partial<Variant>[]): ProductBuilder<T> {
    for (const variant of variants) {
      this.addVariant(variant);
    }
    return this;
  }
 
  /**
   * Sets the variants for the product, replacing any existing variants. Slightly different from
   * {@link addVariants} in that it replaces rather than appends. Accepts an arbitrary value and
   * guards internally (per the builder's optional-setter convention): a non-array is ignored, and
   * each element is validated with {@link isValidVariant}, so malformed variants (e.g. from cached
   * data) are dropped rather than stored.
   *
   * @param variants - The variants to set, or any value (non-arrays and invalid items are ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setVariants([{ id: 1, title: '500g Package', price: 49.99, quantity: 500, uom: 'g' }]);
   * ```
   * @source
   */
  setVariants(variants: unknown): ProductBuilder<T> {
    if (!Array.isArray(variants)) {
      return this;
    }
    this.product.variants = variants.filter(isValidVariant);
    return this;
  }
 
  /**
   * Sets the purity for the product, stored as a string. A number in the `(0, 100]` range is
   * normalized to `"<n>%"`. A string is resolved via {@link findPurity}: a percentage token (with an
   * optional comparator `<`, `>`, `≤`, `≥`, `≈`) is kept when present, otherwise a recognized
   * chemical grade (`"ACS"`, `"HPLC"`, …) is used — so purity may hold either kind of value. Input
   * that yields neither is ignored.
   * @param purity - The purity to set (e.g. `99`, `"≥99%"`, `"ACS reagent"`), or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPurity(98);                       // stored as "98%"
   * builder.setPurity("≥99.995% metals basis");  // stored as "≥99.995%"
   * builder.setPurity("≥98%(HPLC)");             // stored as "≥98%" (percentage wins)
   * builder.setPurity("60% in Water");           // stored as "60%"
   * builder.setPurity("ACS reagent");            // stored as "ACS" (grade fallback)
   * builder.setPurity("Ships in 3 days");        // ignored
   * ```
   * @source
   */
  setPurity(purity: unknown): ProductBuilder<T> {
    let value: string | undefined;
    if (typeof purity === 'number') {
      if (!Number.isNaN(purity) && purity > 0 && purity <= 100) {
        value = `${purity}%`;
      }
    } else if (typeof purity === 'string') {
      value = findPurity(purity);
    }
 
    if (value !== undefined) {
      this.product.purity = value;
    }
    return this;
  }
 
  /**
   * Sets the concentration for the product.
   * @param concentration - The concentration to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setConcentration("98%");
   * builder.setConcentration("98.5%");
   * builder.setConcentration("99%");
   * builder.setConcentration("99.5%");
   * builder.setConcentration("100%");
   * builder.setConcentration("1M");
   * ```
   * @source
   */
  setConcentration(concentration: unknown): ProductBuilder<T> {
    if (typeof concentration === 'string' && concentration.trim().length > 0) {
      this.product.concentration = concentration;
    }
    return this;
  }
 
  /**
   * Sets the molecular weight for the product. A value that doesn't resolve to a positive number
   * is ignored.
   * @param moleweight - The molecular weight to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setMoleweight(100.00);
   * ```
   * @source
   */
  setMoleweight(moleweight: unknown): ProductBuilder<T> {
    if (typeof moleweight === 'string') {
      moleweight = Number(moleweight);
    }
 
    if (typeof moleweight === 'number' && !Number.isNaN(moleweight) && moleweight > 0) {
      this.product.moleweight = moleweight;
    }
    return this;
  }
 
  /**
   * Get a specific property from the product.
   *
   * @param key - The key of the property to get
   * @returns The value of the property
   * @example
   * ```typescript
   * const title = builder.get("title");
   * console.log(title); // "Sodium Chloride"
   * ```
   * @source
   */
  get(key: keyof T): T[keyof T] | Maybe<T[keyof T]> {
    if (key in this.product && typeof this.product[key] !== 'undefined') {
      return this.product[key];
    }
 
    return;
  }
 
  /**
   * Sets the match percentage (Levenshtein result) for the product title
   * compared to the search string.
   *
   * @param matchPercentage - The match percentage to set, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setMatchPercentage(95);
   * ```
   * @source
   */
  setMatchPercentage(matchPercentage: unknown): ProductBuilder<T> {
    if (typeof matchPercentage === 'number' && !Number.isNaN(matchPercentage)) {
      this.product.matchPercentage = matchPercentage;
    }
    return this;
  }
 
  /**
   * Sets the manufacturer name. A value that isn't a non-empty string is ignored.
   * @param manufacturer - The manufacturer name, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setManufacturer("Sigma-Aldrich");
   * ```
   * @source
   */
  setManufacturer(manufacturer: unknown): ProductBuilder<T> {
    if (typeof manufacturer === 'string' && manufacturer.trim().length > 0) {
      this.product.manufacturer = manufacturer;
    }
    return this;
  }
 
  /**
   * Sets the status code of the product. A value that isn't a non-empty string is ignored.
   * @param status - The status code, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setStatus("IN_STOCK");
   * ```
   * @source
   */
  setStatus(status: unknown): ProductBuilder<T> {
    if (typeof status === 'string' && status.trim().length > 0) {
      this.product.status = status;
    }
    return this;
  }
 
  /**
   * Sets the human-readable status text of the product. A non-string value is ignored.
   * @param statusTxt - The status description, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setStatusTxt("In Stock");
   * ```
   * @source
   */
  setStatusTxt(statusTxt: unknown): ProductBuilder<T> {
    if (typeof statusTxt === 'string' && statusTxt.trim().length > 0) {
      this.product.statusTxt = statusTxt;
    }
    return this;
  }
 
  /**
   * Sets special shipping information for the product. A non-string value is ignored.
   * @param shippingInformation - The shipping note, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setShippingInformation("Hazardous material - special shipping required");
   * ```
   * @source
   */
  setShippingInformation(shippingInformation: unknown): ProductBuilder<T> {
    if (typeof shippingInformation === 'string' && shippingInformation.trim().length > 0) {
      this.product.shippingInformation = shippingInformation;
    }
    return this;
  }
 
  /**
   * Sets the parsed purchase restrictions for the product. Accepts an object shaped like
   * {@link PurchaseRestriction} and keeps only the recognized, well-typed fields
   * (`excludedCountries` is filtered to valid country codes); anything else is dropped.
   * The restriction is stored only when at least one meaningful field survives.
   * @param restriction - The purchase restriction object, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setPurchaseRestriction({ excludedCountries: ["US", "DE"], buyerRestricted: true });
   * ```
   * @source
   */
  setPurchaseRestriction(restriction: unknown): ProductBuilder<T> {
    if (typeof restriction !== 'object' || restriction === null) {
      return this;
    }
    const result: PurchaseRestriction = {};
 
    if ('excludedCountries' in restriction && Array.isArray(restriction.excludedCountries)) {
      const codes = restriction.excludedCountries.filter(isCountryCode);
      if (codes.length > 0) {
        result.excludedCountries = codes;
      }
    }
    if ('euOnly' in restriction && restriction.euOnly === true) result.euOnly = true;
    if ('restrictedDelivery' in restriction && restriction.restrictedDelivery === true) {
      result.restrictedDelivery = true;
    }
    if ('buyerRestricted' in restriction && restriction.buyerRestricted === true) {
      result.buyerRestricted = true;
    }
    if (
      'declarationOfUseRequired' in restriction &&
      restriction.declarationOfUseRequired === true
    ) {
      result.declarationOfUseRequired = true;
    }
    if ('note' in restriction && typeof restriction.note === 'string' && restriction.note.trim()) {
      result.note = restriction.note.trim();
    }
 
    if (Object.keys(result).length > 0) {
      this.product.purchaseRestriction = result;
    }
    return this;
  }
 
  /**
   * Sets the product attributes. Accepts an array and keeps only entries shaped like
   * `{ name: string; value: string }`; anything else is dropped.
   * @param attributes - The attributes array, or any value (invalid entries are dropped)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setAttributes([{ name: "Size", value: "500g" }]);
   * ```
   * @source
   */
  setAttributes(attributes: unknown): ProductBuilder<T> {
    if (!Array.isArray(attributes)) {
      return this;
    }
    const valid = attributes.filter(
      (entry): entry is { name: string; value: string } =>
        typeof entry === 'object' &&
        entry !== null &&
        'name' in entry &&
        typeof entry.name === 'string' &&
        'value' in entry &&
        typeof entry.value === 'string',
    );
    if (valid.length > 0) {
      this.product.attributes = valid;
    }
    return this;
  }
 
  /**
   * Sets the reference (base) quantity used for unit conversions. A value that doesn't
   * resolve to a positive number is ignored.
   * @param baseQuantity - The base quantity, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setBaseQuantity(500);
   * ```
   * @source
   */
  setBaseQuantity(baseQuantity: unknown): ProductBuilder<T> {
    const value = typeof baseQuantity === 'string' ? Number(baseQuantity) : baseQuantity;
    if (typeof value === 'number' && !Number.isNaN(value) && value > 0) {
      this.product.baseQuantity = value;
    }
    return this;
  }
 
  /**
   * Sets the reference (base) unit of measure used for conversions. Anything that isn't a
   * known UOM is ignored.
   * @param baseUom - The base unit of measure, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setBaseUom("g");
   * ```
   * @source
   */
  setBaseUom(baseUom: unknown): ProductBuilder<T> {
    if (isUOM(baseUom)) {
      this.product.baseUom = baseUom;
    } else if (baseUom != null) {
      this.logger.warn('Invalid base UOM', { baseUom, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the price converted to USD. A value that doesn't resolve to a non-negative number
   * is ignored. Note: {@link build} recomputes this from price/currency, so it is normally derived.
   * @param usdPrice - The USD price, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setUsdPrice(19.99);
   * ```
   * @source
   */
  setUsdPrice(usdPrice: unknown): ProductBuilder<T> {
    const value = typeof usdPrice === 'string' ? Number(usdPrice) : usdPrice;
    if (typeof value === 'number' && !Number.isNaN(value) && value >= 0) {
      this.product.usdPrice = value;
    } else if (usdPrice != null) {
      this.logger.warn('Invalid USD price', { usdPrice, builder: this });
    }
    return this;
  }
 
  /**
   * Sets the price converted to the user's local currency. A value that doesn't resolve to a
   * non-negative number is ignored.
   * @param localPrice - The local price, or any value (invalid input is ignored)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setLocalPrice(18.5);
   * ```
   * @source
   */
  setLocalPrice(localPrice: unknown): ProductBuilder<T> {
    const value = typeof localPrice === 'string' ? Number(localPrice) : localPrice;
    if (typeof value === 'number' && !Number.isNaN(value) && value >= 0) {
      this.product.localPrice = value;
    } else if (localPrice != null) {
      this.logger.warn('Invalid local price', { localPrice, builder: this });
    }
    return this;
  }
 
  /**
   * Sets related documentation links (MSDS, SDS, etc.). Accepts an array and keeps only the
   * non-empty string entries; anything else is dropped.
   * @param docLinks - The documentation URLs, or any value (invalid entries are dropped)
   * @returns The builder instance for method chaining
   * @example
   * ```typescript
   * builder.setDocLinks(["https://supplier.com/msds/nacl.pdf"]);
   * ```
   * @source
   */
  setDocLinks(docLinks: unknown): ProductBuilder<T> {
    if (!Array.isArray(docLinks)) {
      return this;
    }
    const valid = docLinks.filter(
      (link): link is string => typeof link === 'string' && link.trim().length > 0,
    );
    if (valid.length > 0) {
      this.product.docLinks = valid;
    }
    return this;
  }
 
  /**
   * Gets a specific variant from the product.
   *
   * @param index - The index of the variant to get
   * @returns The variant object
   * @example
   * ```typescript
   * const variant = builder.getVariant(0);
   * console.log(variant); // { id: 1, title: '500g Package', price: 49.99, quantity: 500, uom: 'g' }
   * ```
   * @source
   */
  getVariant(index: number): Variant | undefined {
    return this.product.variants?.[index];
  }
 
  /**
   * Converts a relative or partial URL to an absolute URL using the base URL.
   *
   * @param path - The URL or path to convert
   * @returns The absolute URL as a string
   * @example
   * ```typescript
   * const url = this.href('/products/123');
   * // Returns: 'https://example.com/products/123'
   * ```
   * @source
   */
  private href(path: string | URL): string {
    if (URL.canParse(path)) {
      return String(path);
    }
    const urlObj = new URL(path, this.baseURL);
    return String(urlObj);
  }
 
  /**
   * Resolves an unknown value to an absolute URL string, or undefined when it isn't URL-like.
   * Lets the URL setters accept the often-optional output of a parser (e.g. `findPdfHref`)
   * directly, without each caller having to null-check first.
   * @param value - The candidate URL (string or URL), or anything else
   * @returns The absolute URL as a string, or undefined if the value isn't a usable URL
   * @example
   * ```typescript
   * this.resolveHref("/sds.pdf");  // "https://example.com/sds.pdf"
   * this.resolveHref(undefined);    // undefined
   * ```
   * @source
   */
  private resolveHref(value: unknown): string | undefined {
    if (value instanceof URL) {
      return this.href(value);
    }
    if (typeof value === 'string' && value.trim().length > 0) {
      return this.href(value);
    }
    return undefined;
  }
 
  /**
   * Builds and validates the final Product object.
   * Performs the following steps:
   * 1. Validates minimum required properties
   * 2. Calculates USD price if in different currency
   * 3. Converts quantity to base units
   * 4. Converts relative URLs to absolute
   * 5. Processes and validates variants if present
   *
   * @example
   * ```typescript
   * const product = await builder
   *   .setBasicInfo('Test Chemical', '/products/test', 'Supplier')
   *   .setPricing(29.99, 'USD', '$')
   *   .setQuantity(100, 'g')
   *   .addVariant({
   *     title: '500g Package',
   *     price: 49.99,
   *     quantity: 500,
   *     uom: 'g'
   *   })
   *   .build();
   * ```
   * @source
   */
  async build(): Promise<Maybe<T>> {
    if (!isMinimalProduct(this.product)) {
      return;
    }
 
    this.product.usdPrice = this.product.price;
    const baseQuantity = toBaseQuantity(this.product.quantity, this.product.uom);
    if (baseQuantity) {
      this.product.baseQuantity = baseQuantity;
    }
 
    if (this.product.currencyCode !== 'USD') {
      this.product.usdPrice = await toUSD(this.product.price, this.product.currencyCode);
    }
 
    // Process variants if present
    if (this.product.variants?.length) {
      // Filter out invalid variants
      this.product.variants = this.product.variants.filter((variant) => isValidVariant(variant));
 
      // Process each variant
      for (const variant of this.product.variants ?? []) {
        if ('quantity' in variant === false || !variant.quantity) {
          this.logger.warn('Skipping variant, no quantity found', {
            variant,
            product: this.product,
            builder: this,
          });
          continue;
        }
 
        if ('price' in variant === false || !variant.price) {
          this.logger.warn('Skipping variant, no price found', {
            variant,
            product: this.product,
            builder: this,
          });
          continue;
        }
 
        if ('usdPrice' in variant === false || !variant.usdPrice) {
          variant.usdPrice = await toUSD(variant.price, this.product.currencyCode);
        }
 
        if ('uom' in variant === false || !variant.uom) {
          variant.uom = this.product.uom;
        }
 
        // Sometimes variants don't have their own titles, they're just a dropdown on
        // the same page, so if that's the case then we should append the quantity to
        // the title to differentiate them.
        if (
          'title' in variant === false ||
          !variant.title?.trim()?.length ||
          variant.title === this.product.title
        ) {
          variant.title = `${this.product.title} - ${variant.quantity}${variant.uom}`;
        }
 
        if (variant.url) {
          variant.url = this.href(variant.url);
        }
 
        // Default the variant's human-facing permalink to its own permalink,
        // then its processing URL, then the parent product's permalink/URL.
        const variantPermalink =
          variant.permalink ?? variant.url ?? this.product.permalink ?? this.product.url;
        if (variantPermalink) {
          variant.permalink = this.href(variantPermalink);
        }
 
        // Re-populate the variant using the parent product properties as defaults and the current
        // values as overrides.
 
        const { variants: _, ...defaults } = this.product;
 
        Object.assign(variant, defaults, { ...variant });
      }
    }
 
    if (this.product._fuzz) {
      this.product.matchPercentage = this.product._fuzz.score;
    }
 
    if (!isProduct(this.product)) {
      this.logger.error(`ProductBuilder| Invalid product`, {
        product: this.product,
        builder: this,
      });
      return;
    }
 
    this.product.url = this.href(this.product.url);
    // Human-facing permalink defaults to the processing URL when a supplier
    // didn't set one (the common case for scraped suppliers).
    this.product.permalink = this.href(this.product.permalink ?? this.product.url);
    this.logger.debug('ProductBuilder| Built product', { product: this.product, builder: this });
    // isProduct() above narrows to the base Product; T is the caller's concrete subtype of Product.
    return this.product as T;
  }
 
  /**
   * Returns the current state of the product being built.
   * Useful for debugging or inspecting the build progress.
   *
   * @returns The current partial product object
   * @example
   * ```typescript
   * const partialProduct = builder
   *   .setBasicInfo('Test', '/test', 'Supplier')
   *   .dump();
   * console.log(partialProduct);
   * ```
   * @source
   */
  dump(): Partial<T> {
    return this.product;
  }
 
  /**
   * Creates an array of ProductBuilder instances from cached product data.
   * This is used to restore builders from cache storage.
   *
   * @param baseURL - The base URL of the supplier's website
   * @param data - Array of cached product data (from .dump())
   * @returns Array of ProductBuilder instances
   * @example
   * ```typescript
   * const cachedData = await chrome.storage.local.get('cached_products');
   * const builders = ProductBuilder.createFromCache('https://example.com', cachedData);
   * for (const builder of builders) {
   *   const product = await builder.build();
   *   console.log(product.title);
   * }
   * ```
   * @source
   */
  public static createFromCache<T extends Product>(
    baseURL: string,
    data: unknown[],
  ): ProductBuilder<T>[] {
    return data.map((d) => {
      const builder = new ProductBuilder<T>(baseURL);
      // Cached .dump() output is opaque unknown[]; no runtime shape exists for the generic Partial<T>,
      // and build() re-validates the result via isProduct() before use.
      builder.setData(d as Partial<T>);
      return builder;
    });
  }
}