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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 30x 30x 30x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 2x 2x 2x 2x 2x 2x 2x 11x 11x 11x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 2x 1x 1x 1x 1x 4x 4x 4x 4x 4x 3x 3x 4x 2x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 10x 6x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 6x 6x 9x 9x 1x 1x 3x 3x 3x 3x 15x 15x 15x 8x 8x 7x 7x 7x 3x 3x 1x 1x 1x 4x 4x 4x 1x 1x 1x 3x 3x 3x 3x 4x 4x 4x 4x 1x 1x 6x 6x 6x 6x 6x 6x 5x 5x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 4x 4x 5x 5x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x 13x 13x 34x 2x 5x 5x 2x 34x 26x 26x 26x 26x 13x 13x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 4x 5x 5x 5x 5x 5x 1x 1x 1x 4x 4x 4x 4x 3x 3x 3x 1x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 3x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 2x 2x 2x 2x 2x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 2x 2x 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 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 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 13x 13x 13x 13x 13x 10x 10x 13x 13x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 1x 1x 1x 26x 26x 24x 24x 1x 1x 1x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 1x 1x 1x 1x 1x 9x 9x 9x 1x 1x 1x 5x 5x 5x 5x 4x 4x 23x 23x 18x 18x 18x 4x 4x 4x 4x 4x 4x 5x 5x 3x 5x 5x 1x 1x 1x | import { isCAS } from '@/utils/typeGuards/common';
import { withTtlCache } from '@/helpers/requestCache';
import { isPubChemCID } from '@/utils/typeGuards/common';
import { hasAdvancedSyntax } from '@/utils/search-query/parseSearchQuery';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('pubchem');
/**
* SDQ (Structure Data Query) agent from PubChem API
* @see https://pubchem.ncbi.nlm.nih.gov/sdq/sdqagent.cgi
* @see https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest#section=Operation
*
* SDQ types are declared globally in types/pubchem.d.ts
* @source
*/
/**
* Base URL for PubChem's PUG-REST API.
* @see https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest
* @source
*/
const PUG_REST_BASE = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug';
/**
* Base URL for PubChem's PUG-View API (annotation data such as GHS and solubility).
* @see https://pubchem.ncbi.nlm.nih.gov/docs/pug-view
* @source
*/
const PUG_VIEW_BASE = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data';
/**
* Compound property fields requested from PUG-REST's `/property` operation. Uses the current
* `SMILES` field (PubChem retired `CanonicalSMILES` in 2025).
* @source
*/
const COMPOUND_PROPERTY_FIELDS =
'MolecularFormula,MolecularWeight,IUPACName,SMILES,InChI,InChIKey,Title,XLogP,TPSA';
/**
* A subset of PubChem compound properties, normalized to friendly camelCase field names.
* Every field is optional because PUG-REST omits properties it cannot compute for a compound.
* @category Science Helpers
* @source
*/
export interface PubChemProperties {
/** The compound's CID. */
cid?: PubChemCID;
/** Molecular formula, e.g. `"C3H6O"`. */
molecularFormula?: string;
/** Molecular weight in g/mol. PubChem returns this as a string, e.g. `"58.08"`. */
molecularWeight?: string;
/** IUPAC systematic name. */
iupacName?: string;
/** Canonical SMILES string. */
smiles?: string;
/** InChI string. */
inchi?: string;
/** InChIKey (hashed InChI). */
inchiKey?: string;
/** PubChem's preferred title/name for the compound. */
title?: string;
/** Computed octanol/water partition coefficient (XLogP3); a lipophilicity/polarity indicator. */
xLogP?: number;
/** Topological polar surface area in Ų. */
tpsa?: number;
}
/**
* A compound's textual description from PUG-REST's `/description` operation.
* @category Science Helpers
* @source
*/
export interface PubChemDescription {
/** The compound title, if provided. */
title?: string;
/** The description text. */
description?: string;
/** Human-readable name of the description's source. */
source?: string;
/** URL of the description's source. */
url?: string;
}
/**
* Extracts the CID list from a PUG-REST `IdentifierList` response, narrowing the parsed JSON
* without type assertions.
* @param data - The parsed JSON response body
* @returns The array of CID numbers, or undefined if the shape is unexpected/empty
* @source
*/
function extractCids(data: unknown): number[] | undefined {
if (typeof data !== 'object' || data === null) return undefined;
const identifierList = Reflect.get(data, 'IdentifierList');
if (typeof identifierList !== 'object' || identifierList === null) return undefined;
const cid = Reflect.get(identifierList, 'CID');
if (!Array.isArray(cid)) return undefined;
const nums = cid.filter((entry): entry is number => typeof entry === 'number');
return nums.length > 0 ? nums : undefined;
}
/**
* Extracts the first compound-property record from a PUG-REST `PropertyTable` response and maps it
* to a {@link PubChemProperties}, narrowing every field without type assertions.
* @param data - The parsed JSON response body
* @returns The normalized properties, or undefined if the shape is unexpected/empty
* @source
*/
function extractProperties(data: unknown): PubChemProperties | undefined {
if (typeof data !== 'object' || data === null) return undefined;
const table = Reflect.get(data, 'PropertyTable');
if (typeof table !== 'object' || table === null) return undefined;
const properties = Reflect.get(table, 'Properties');
if (!Array.isArray(properties) || properties.length === 0) return undefined;
const first = properties[0];
if (typeof first !== 'object' || first === null) return undefined;
const readString = (key: string): string | undefined => {
const value = Reflect.get(first, key);
return typeof value === 'string' ? value : undefined;
};
const cidValue = Reflect.get(first, 'CID');
const weight = Reflect.get(first, 'MolecularWeight');
return {
cid: isPubChemCID(cidValue) ? cidValue : undefined,
molecularFormula: readString('MolecularFormula'),
// PubChem usually returns MolecularWeight as a string, but tolerate a numeric payload too.
molecularWeight:
typeof weight === 'string' ? weight : typeof weight === 'number' ? String(weight) : undefined,
iupacName: readString('IUPACName'),
smiles: readString('SMILES'),
inchi: readString('InChI'),
inchiKey: readString('InChIKey'),
title: readString('Title'),
xLogP:
typeof Reflect.get(first, 'XLogP') === 'number' ? Reflect.get(first, 'XLogP') : undefined,
tpsa: typeof Reflect.get(first, 'TPSA') === 'number' ? Reflect.get(first, 'TPSA') : undefined,
};
}
/**
* Extracts a compound description from a PUG-REST `InformationList` response. PubChem often splits
* the description text and its source across separate entries, so fields are merged across all
* entries. Narrows every field without type assertions.
* @param data - The parsed JSON response body
* @returns The merged description, or undefined when no description text is present
* @source
*/
function extractDescription(data: unknown): PubChemDescription | undefined {
if (typeof data !== 'object' || data === null) return undefined;
const list = Reflect.get(data, 'InformationList');
if (typeof list !== 'object' || list === null) return undefined;
const information = Reflect.get(list, 'Information');
if (!Array.isArray(information)) return undefined;
const readString = (entry: object, key: string): string | undefined => {
const value = Reflect.get(entry, key);
return typeof value === 'string' ? value : undefined;
};
let title: string | undefined;
let description: string | undefined;
let source: string | undefined;
let url: string | undefined;
for (const entry of information) {
if (typeof entry !== 'object' || entry === null) continue;
title ??= readString(entry, 'Title');
description ??= readString(entry, 'Description');
source ??= readString(entry, 'DescriptionSourceName');
url ??= readString(entry, 'DescriptionURL');
}
if (!description) return undefined;
return { title, description, source, url };
}
/**
* Network implementation for {@link getCidsByCas}; see it for details.
* @param cas - The CAS registry number to look up
* @returns The matching CIDs, or undefined if none
* @source
*/
async function getCidsByCasUncached(cas: CAS<string>): Promise<PubChemCID[] | undefined> {
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/xref/rn/${encodeURIComponent(cas)}/cids/JSON`,
);
if (!response.ok) return undefined;
const data = await response.json();
const cids = extractCids(data);
if (!cids) return undefined;
const valid = cids.filter(isPubChemCID);
return valid.length > 0 ? valid : undefined;
} catch (error) {
logger.error(`Error fetching PubChem CIDs by CAS: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Retrieves the PubChem CIDs registered for a CAS number via PUG-REST's xref/registry-number
* lookup. A single CAS number can map to multiple CIDs (e.g. different salt or hydrate forms).
* Results are cached for three days; unknown CAS numbers resolve to undefined.
* @category Science Helpers
* @param cas - The CAS registry number to look up
* @returns The matching CIDs, or undefined if PubChem has no cross-reference
* @example
* ```typescript
* await getCidsByCas("15681-89-7");
* // Returns: [4311764, 22959485, 23673181]
* await getCidsByCas("0000-00-0");
* // Returns: undefined
* ```
* @source
*/
export const getCidsByCas: (cas: CAS<string>) => Promise<PubChemCID[] | undefined> = withTtlCache(
getCidsByCasUncached,
{ namespace: 'cidsByCas' },
);
/**
* Network implementation for {@link getCidByName}; see it for details.
* @param name - The chemical name to look up
* @returns The first matching CID, or undefined
* @source
*/
async function getCidByNameUncached(name: string): Promise<PubChemCID | undefined> {
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/name/${encodeURIComponent(name)}/cids/JSON`,
);
if (!response.ok) return undefined;
const data = await response.json();
const first = extractCids(data)?.[0];
return isPubChemCID(first) ? first : undefined;
} catch (error) {
logger.error(`Error fetching PubChem CID by name: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Resolves a chemical name to its best-matching PubChem CID via PUG-REST. Returns the first
* (highest-ranked) CID PubChem reports. Results are cached for three days.
* @category Science Helpers
* @param name - The chemical name to look up
* @returns The best-matching CID, or undefined if PubChem has no match
* @example
* ```typescript
* await getCidByName("aspirin");
* // Returns: 2244
* ```
* @source
*/
export const getCidByName: (name: string) => Promise<PubChemCID | undefined> = withTtlCache(
getCidByNameUncached,
{ namespace: 'cidByName' },
);
/**
* Network implementation for {@link getCidByFormula}; see it for details.
* @param formula - The molecular formula to look up
* @returns The best-matching CID, or undefined
* @source
*/
async function getCidByFormulaUncached(formula: string): Promise<PubChemCID | undefined> {
// PubChem's fastformula search wants plain digits, but a display-formatted formula may use
// subscripts (Na₆O₁₈P₆ → Na6O18P6). Inlined rather than importing `subscriptToAscii` from
// `@/helpers/science` to avoid a pubchem→science→smiles→pubchem import cycle.
const ascii = formula.replace(/[₀-₉]/g, (c) => String(c.charCodeAt(0) - 0x2080));
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/fastformula/${encodeURIComponent(ascii)}/cids/JSON?MaxRecords=1`,
);
if (!response.ok) return undefined;
const data = await response.json();
const first = extractCids(data)?.[0];
return isPubChemCID(first) ? first : undefined;
} catch (error) {
logger.error(`Error fetching PubChem CID by formula: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Resolves a molecular formula to its best-matching PubChem CID via the PUG-REST `fastformula`
* search (the plain name endpoint 404s on most formulas). Returns the first CID PubChem reports.
* Cached for three days.
* @category Science Helpers
* @param formula - The molecular formula to look up (e.g. `"Na6O18P6"`)
* @returns The best-matching CID, or undefined if PubChem has no match
* @example
* ```typescript
* await getCidByFormula("Na6O18P6"); // 24968
* ```
* @source
*/
export const getCidByFormula: (formula: string) => Promise<PubChemCID | undefined> = withTtlCache(
getCidByFormulaUncached,
{ namespace: 'cidByFormula' },
);
/**
* Network implementation for {@link getCidBySmiles}; see it for details.
* @param smiles - The SMILES string to look up
* @returns The first matching CID, or undefined
* @source
*/
async function getCidBySmilesUncached(smiles: string): Promise<PubChemCID | undefined> {
// The SMILES goes in the query string, not the path. PubChem splits the request path
// before percent-decoding it, so a SMILES containing `/`, `#` or `+` (stereo bonds,
// triple bonds, charges) 404s against the path form even when correctly encoded.
const url = new URL(`${PUG_REST_BASE}/compound/smiles/cids/JSON`);
url.searchParams.set('smiles', smiles);
try {
const response = await fetch(url);
if (!response.ok) return undefined;
const data = await response.json();
const first = extractCids(data)?.[0];
return isPubChemCID(first) ? first : undefined;
} catch (error) {
logger.error(`Error fetching PubChem CID by SMILES: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Resolves a SMILES string to its PubChem CID. Results are cached for three days.
* @category Science Helpers
* @param smiles - The SMILES string to look up
* @returns The matching CID, or undefined if PubChem has no match
* @example
* ```typescript
* await getCidBySmiles('CC(=O)Oc1ccccc1C(=O)O');
* // Returns: 2244
* ```
* @source
*/
export const getCidBySmiles: (smiles: string) => Promise<PubChemCID | undefined> = withTtlCache(
getCidBySmilesUncached,
{ namespace: 'cidBySmiles' },
);
/**
* Which depiction of a structure PubChem should return: a computed 3D conformer, or the
* flat 2D layout.
* @category Science Helpers
* @source
*/
export type StructureRecordType = '2d' | '3d';
/**
* A structure record fetched from PubChem, tagged with which depiction was actually served.
* @category Science Helpers
* @source
*/
export interface StructureRecord {
/** Raw SDF (molfile V2000) text. */
sdf: string;
/** Which depiction this is — `'3d'` only when a real conformer was available. */
recordType: StructureRecordType;
}
/**
* Network implementation for {@link getStructureSdf}; see it for details.
* @param cid - The compound's PubChem CID
* @returns The structure record, or undefined if neither depiction is available
* @source
*/
async function getStructureSdfUncached(cid: PubChemCID): Promise<StructureRecord | undefined> {
// PubChem only computes 3D conformers for covalent species: ionic salts and most
// inorganics (NaCl, NaOH, KMnO4 …) 404 on `record_type=3d` but always have a 2D record.
const preference: StructureRecordType[] = ['3d', '2d'];
for (const recordType of preference) {
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/cid/${cid}/SDF?record_type=${recordType}`,
);
if (!response.ok) continue;
const sdf = await response.text();
if (sdf.trim() === '') continue;
return { sdf, recordType };
} catch (error) {
logger.error(`Error fetching PubChem ${recordType} SDF: ${getErrorMessage(error)}`, {
error,
});
}
}
return undefined;
}
/**
* Fetches a compound's structure as SDF, preferring the computed 3D conformer and falling
* back to the 2D layout when PubChem has no 3D record for it. Cached for three days.
* @category Science Helpers
* @param cid - The compound's PubChem CID
* @returns The SDF text and which depiction it is, or undefined if neither is available
* @example
* ```typescript
* await getStructureSdf(2519); // caffeine: { sdf: '2519\n -OEChem-…', recordType: '3d' }
* await getStructureSdf(5234); // sodium chloride, no conformer: { sdf: …, recordType: '2d' }
* ```
* @source
*/
export const getStructureSdf: (cid: PubChemCID) => Promise<StructureRecord | undefined> =
withTtlCache(getStructureSdfUncached, { namespace: 'structureSdf' });
/**
* How many candidate names {@link resolveIdentifierNames} keeps. Enough to reach a common
* name even when brand/registry synonyms rank above it, without ballooning the per-item
* fuzzy-scoring cost.
* @source
*/
const MAX_CANDIDATE_NAMES = 12;
/**
* Cleans a PubChem synonym into a usable search-name candidate, or rejects it. Strips a
* trailing parenthetical formula/registry suffix (so `Sodium hexametaphosphate (Na6P6O18)`
* becomes `Sodium hexametaphosphate`) and drops registry-style codes — a CAS number, or an
* all-caps/no-lowercase token such as `EINECS 233-343-1` or `N40N91DW96` — along with
* anything too short, too long, or lacking a letter.
* @param raw - A raw PubChem synonym or Title
* @returns The cleaned name, or undefined when it isn't a usable common name
* @example
* ```typescript
* cleanCandidateName("Sodium hexametaphosphate (Na6P6O18)"); // "Sodium hexametaphosphate"
* cleanCandidateName("EINECS 233-343-1"); // undefined
* ```
* @source
*/
function cleanCandidateName(raw: string): string | undefined {
const name = raw.replace(/\s*\([^)]*\)\s*$/, '').trim();
if (name.length < 3 || name.length > 60) {
return undefined;
}
// A registry code (EINECS/UNII/HSDB/FEMA/EC numbers, "N40N91DW96", …) has no lowercase
// letter; a real common name does. Also reject bare CAS numbers and leading-digit tokens.
if (!/[a-z]/.test(name) || isCAS(name) || /^\d/.test(name)) {
return undefined;
}
return name;
}
/**
* Builds the ranked, deduped list of candidate search names from a compound's Title and its
* popularity-ranked synonyms (each via {@link cleanCandidateName}), capped at
* {@link MAX_CANDIDATE_NAMES}. The Title leads; synonyms follow in popularity order.
* @param title - The compound Title (may be undefined)
* @param synonyms - The compound's popularity-ranked synonyms (may be undefined)
* @returns The candidate names, best first (empty when none are usable)
* @example
* ```typescript
* buildCandidateNames("Hexasodium hexametaphosphate", ["Calgon S", "Sodium hexametaphosphate (Na6P6O18)"]);
* // ["Hexasodium hexametaphosphate", "Calgon S", "Sodium hexametaphosphate"]
* ```
* @source
*/
function buildCandidateNames(title: string | undefined, synonyms: string[] | undefined): string[] {
const names: string[] = [];
const seen = new Set<string>();
for (const raw of [title, ...(synonyms ?? [])]) {
if (names.length >= MAX_CANDIDATE_NAMES) {
break;
}
const cleaned = raw ? cleanCandidateName(raw) : undefined;
if (!cleaned || seen.has(cleaned.toLowerCase())) {
continue;
}
seen.add(cleaned.toLowerCase());
names.push(cleaned);
}
return names;
}
/**
* Resolves a chemical identifier (CAS number or molecular formula) to a ranked list of
* human-readable chemical-name candidates via PubChem — the compound's Title plus its cleaned
* popularity-ranked synonyms. Used to let suppliers that can only search by name answer
* identifier queries: the identifier is converted to names, and a product is matched against
* whichever candidate scores best (so e.g. "Sodium hexametaphosphate" is reached even when the
* Title is "Hexasodium hexametaphosphate"). SMILES is handled separately by `resolveSmiles` in
* `@/helpers/smiles`.
* @category Science Helpers
* @param term - The raw identifier (a CAS number or a molecular formula)
* @param termType - Which kind of identifier `term` is
* @returns The candidate names (and the CAS, for a CAS query), or undefined when unresolved
* @example
* ```typescript
* await resolveIdentifierNames("10124-56-8", "cas");
* // { names: ["Hexasodium hexametaphosphate", "Sodium hexametaphosphate", …], cas: ["10124-56-8"] }
* ```
* @source
*/
export async function resolveIdentifierNames(
term: string,
termType: 'cas' | 'formula',
): Promise<{ names: string[]; cas?: string[] } | undefined> {
const cid = termType === 'formula' ? await getCidByFormula(term) : await getCidByName(term);
if (cid === undefined) {
return undefined;
}
const [properties, synonyms] = await Promise.all([
getCompoundProperties(cid),
getSynonymsByCid(cid),
]);
const names = buildCandidateNames(properties?.title, synonyms);
if (names.length === 0) {
return undefined;
}
return termType === 'cas' ? { names, cas: [term] } : { names };
}
/**
* Network implementation for {@link getCompoundProperties}; see it for details.
* @param cid - The compound's CID
* @returns The normalized properties, or undefined
* @source
*/
async function getCompoundPropertiesUncached(
cid: PubChemCID,
): Promise<PubChemProperties | undefined> {
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/cid/${cid}/property/${COMPOUND_PROPERTY_FIELDS}/JSON`,
);
if (!response.ok) return undefined;
const data = await response.json();
return extractProperties(data);
} catch (error) {
logger.error(`Error fetching PubChem compound properties: ${getErrorMessage(error)}`, {
error,
});
return undefined;
}
}
/**
* Fetches core physical/chemical properties for a compound (formula, molecular weight, IUPAC name,
* SMILES, InChI, InChIKey, title) via PUG-REST. These map directly onto ChemPal's product fields,
* so this is the primary way to enrich a product once its CID is known. Cached for
* three days.
* @category Science Helpers
* @param cid - The compound's CID
* @returns The compound's properties, or undefined if the CID is unknown
* @example
* ```typescript
* await getCompoundProperties(180);
* // Returns: { cid: 180, molecularFormula: "C3H6O", molecularWeight: "58.08",
* // iupacName: "propan-2-one", smiles: "CC(C)=O", inchiKey: "CSCPPACGZOOCGX-UHFFFAOYSA-N", ... }
* ```
* @source
*/
export const getCompoundProperties: (cid: PubChemCID) => Promise<PubChemProperties | undefined> =
withTtlCache(getCompoundPropertiesUncached, {
namespace: 'properties',
});
/**
* Network implementation for {@link getSynonymsByCid}; see it for details.
* @param cid - The compound's CID
* @returns The synonym list, or undefined
* @source
*/
async function getSynonymsByCidUncached(cid: PubChemCID): Promise<string[] | undefined> {
try {
const response = await fetch(`${PUG_REST_BASE}/compound/cid/${cid}/synonyms/JSON`);
if (!response.ok) return undefined;
const data = await response.json();
return extractSynonyms(data);
} catch (error) {
logger.error(`Error fetching PubChem synonyms by CID: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Fetches PubChem's popularity-ranked synonyms for a compound by CID via PUG-REST. Prefer this
* over {@link getRankedNamesByName} when the CID is already known, as it avoids an ambiguous
* name lookup. Cached for three days.
* @category Science Helpers
* @param cid - The compound's CID
* @returns The ranked synonym list, or undefined if the CID is unknown
* @example
* ```typescript
* await getSynonymsByCid(180);
* // Returns: ["acetone", "propan-2-one", "67-64-1", "2-propanone", ...]
* ```
* @source
*/
export const getSynonymsByCid: (cid: PubChemCID) => Promise<string[] | undefined> = withTtlCache(
getSynonymsByCidUncached,
{ namespace: 'synonymsByCid' },
);
/**
* Network implementation for {@link getCompoundDescription}; see it for details.
* @param cid - The compound's CID
* @returns The merged description, or undefined
* @source
*/
async function getCompoundDescriptionUncached(
cid: PubChemCID,
): Promise<PubChemDescription | undefined> {
try {
const response = await fetch(`${PUG_REST_BASE}/compound/cid/${cid}/description/JSON`);
if (!response.ok) return undefined;
const data = await response.json();
return extractDescription(data);
} catch (error) {
logger.error(`Error fetching PubChem description: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Fetches a short human-readable description of a compound (with its source) by CID via PUG-REST.
* Useful for surfacing a plain-language blurb in the product detail view. Cached for
* three days.
* @category Science Helpers
* @param cid - The compound's CID
* @returns The description and its source, or undefined if none is available
* @example
* ```typescript
* await getCompoundDescription(180);
* // Returns: { title: "Acetone", description: "Acetone is a manufactured chemical...",
* // source: "NCI Thesaurus", url: "https://..." }
* ```
* @source
*/
export const getCompoundDescription: (cid: PubChemCID) => Promise<PubChemDescription | undefined> =
withTtlCache(getCompoundDescriptionUncached, {
namespace: 'descriptionByCid',
});
/**
* GHS classification for a compound, from PubChem's PUG-View `GHS Classification` section.
* @category Science Helpers
* @group Chemical Info
* @source
*/
export interface PubChemGhs {
/** Pictogram codes, e.g. `"GHS02"`, with the icon URL PubChem serves for each. */
pictograms: Array<{ code: string; label: string; url: string }>;
/** Signal word: `"Danger"` or `"Warning"`. */
signal?: string;
/** Hazard statements, e.g. `"H225: Highly Flammable liquid and vapor"`. */
hazardStatements: string[];
}
/**
* Recursively collects every `Information` entry in a PUG-View record, which nests them under
* arbitrarily deep `Section` arrays.
* @param node - A PUG-View record or section
* @returns All information entries found
* @source
*/
function collectInformation(node: unknown): object[] {
if (typeof node !== 'object' || node === null) return [];
const found: object[] = [];
const information = Reflect.get(node, 'Information');
if (Array.isArray(information)) {
for (const entry of information) {
if (typeof entry === 'object' && entry !== null) found.push(entry);
}
}
for (const key of ['Record', 'Section']) {
const child = Reflect.get(node, key);
const children = Array.isArray(child) ? child : [child];
for (const item of children) found.push(...collectInformation(item));
}
return found;
}
/**
* Reads an information entry's `Value.StringWithMarkup` items.
* @param entry - A PUG-View information entry
* @returns The string/markup items
* @source
*/
function markupItems(entry: object): Array<{ text: string; markup: object[] }> {
const value = Reflect.get(entry, 'Value');
const items =
typeof value === 'object' && value !== null
? Reflect.get(value, 'StringWithMarkup')
: undefined;
if (!Array.isArray(items)) return [];
return items.flatMap((item: unknown) => {
if (typeof item !== 'object' || item === null) return [];
const text = Reflect.get(item, 'String');
const markup = Reflect.get(item, 'Markup');
return typeof text === 'string'
? [
{
text,
markup: Array.isArray(markup)
? markup.filter((m) => typeof m === 'object' && m !== null)
: [],
},
]
: [];
});
}
/**
* Parses a PUG-View `GHS Classification` response into a {@link PubChemGhs}. Multiple sources
* report the same fields; pictograms and statements are de-duplicated and the first signal word
* wins.
* @param data - The parsed JSON response body
* @returns The classification, or undefined when it holds no pictograms, signal, or statements
* @source
*/
export function extractGhs(data: unknown): PubChemGhs | undefined {
const pictograms = new Map<string, { code: string; label: string; url: string }>();
const statements = new Set<string>();
let signal: string | undefined;
for (const entry of collectInformation(data)) {
const name = Reflect.get(entry, 'Name');
for (const { text, markup } of markupItems(entry)) {
if (name === 'Pictogram(s)') {
for (const mark of markup) {
const url = Reflect.get(mark, 'URL');
const label = Reflect.get(mark, 'Extra');
const code = typeof url === 'string' ? /(GHS\d{2})\.svg$/.exec(url)?.[1] : undefined;
if (code !== undefined && typeof url === 'string') {
pictograms.set(code, { code, label: typeof label === 'string' ? label : code, url });
}
}
} else if (name === 'Signal') {
signal ??= text.trim() || undefined;
} else if (name === 'GHS Hazard Statements') {
const statement = text.replace(/\s*\[.*\]\s*$/, '').trim();
if (statement !== '') statements.add(statement);
}
}
}
if (pictograms.size === 0 && signal === undefined && statements.size === 0) return undefined;
return {
pictograms: [...pictograms.values()].sort((a, b) => a.code.localeCompare(b.code)),
signal,
hazardStatements: [...statements],
};
}
/**
* Network implementation for {@link getGhsClassification}; see it for details.
* @param cid - The compound's CID
* @returns The classification, or undefined
* @source
*/
async function getGhsClassificationUncached(cid: PubChemCID): Promise<PubChemGhs | undefined> {
try {
const response = await fetch(
`${PUG_VIEW_BASE}/compound/${cid}/JSON?heading=GHS+Classification`,
);
if (!response.ok) return undefined;
return extractGhs(await response.json());
} catch (error) {
logger.error(`Error fetching PubChem GHS classification: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Fetches a compound's GHS pictograms, signal word and hazard statements via PUG-View. Cached for
* three days.
* @category Science Helpers
* @group Chemical Info
* @param cid - The compound's CID
* @returns The GHS classification, or undefined if PubChem has none
* @example
* ```typescript
* await getGhsClassification(180);
* // Returns: { pictograms: [{ code: "GHS02", label: "Flammable", url: "https://..." }, ...],
* // signal: "Danger", hazardStatements: ["H225: Highly Flammable liquid and vapor", ...] }
* ```
* @source
*/
export const getGhsClassification: (cid: PubChemCID) => Promise<PubChemGhs | undefined> =
withTtlCache(getGhsClassificationUncached, { namespace: 'ghsByCid' });
/**
* Parses a PUG-View `Solubility` response into de-duplicated plain-text statements.
* @param data - The parsed JSON response body
* @returns Up to five distinct solubility statements, or undefined when none exist
* @source
*/
export function extractSolubility(data: unknown): string[] | undefined {
const lines = new Set<string>();
for (const entry of collectInformation(data)) {
for (const { text } of markupItems(entry)) {
const trimmed = text.trim();
if (trimmed !== '') lines.add(trimmed);
}
}
return lines.size > 0 ? [...lines].slice(0, 5) : undefined;
}
/**
* Network implementation for {@link getSolubility}; see it for details.
* @param cid - The compound's CID
* @returns The statements, or undefined
* @source
*/
async function getSolubilityUncached(cid: PubChemCID): Promise<string[] | undefined> {
try {
const response = await fetch(`${PUG_VIEW_BASE}/compound/${cid}/JSON?heading=Solubility`);
if (!response.ok) return undefined;
return extractSolubility(await response.json());
} catch (error) {
logger.error(`Error fetching PubChem solubility: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Fetches experimental solubility statements for a compound via PUG-View. Cached for three days.
* @category Science Helpers
* @group Chemical Info
* @param cid - The compound's CID
* @returns Up to five solubility statements, or undefined if PubChem has none
* @example
* ```typescript
* await getSolubility(180);
* // Returns: ["Miscible with water", "Miscible with benzene", ...]
* ```
* @source
*/
export const getSolubility: (cid: PubChemCID) => Promise<string[] | undefined> = withTtlCache(
getSolubilityUncached,
{ namespace: 'solubilityByCid' },
);
/**
* Builds the URL of a compound's PubChem summary page from its CID.
* @category Science Helpers
* @param cid - The compound's CID
* @returns The PubChem compound page URL
* @example
* ```typescript
* pubchemCompoundUrl(180);
* // Returns: "https://pubchem.ncbi.nlm.nih.gov/compound/180"
* ```
* @source
*/
export function pubchemCompoundUrl(cid: PubChemCID): string {
return `https://pubchem.ncbi.nlm.nih.gov/compound/${cid}`;
}
/**
* Builds a PubChem search URL for a CAS number. Use this when the exact CID is unknown — PubChem's
* search lands the user on the matching compound (or a short result list) for the CAS number.
* @category Science Helpers
* @param cas - The CAS registry number
* @returns The PubChem search URL for the CAS number
* @example
* ```typescript
* pubchemCasSearchUrl("67-64-1");
* // Returns: "https://pubchem.ncbi.nlm.nih.gov/#query=67-64-1"
* ```
* @source
*/
export function pubchemCasSearchUrl(cas: string): string {
return `https://pubchem.ncbi.nlm.nih.gov/#query=${encodeURIComponent(cas)}`;
}
/**
* Builds the URL of a compound's 2D structure image (PNG) from its CID.
* @category Science Helpers
* @param cid - The compound's CID
* @returns The PUG-REST PNG image URL
* @example
* ```typescript
* pubchemStructureImageUrl(180);
* // Returns: "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/180/PNG"
* ```
* @source
*/
export function pubchemStructureImageUrl(cid: PubChemCID): string {
return `${PUG_REST_BASE}/compound/cid/${cid}/PNG`;
}
/**
* Type guard to assert that data is a valid SDQResponse
* @param data - The data to validate
* @source
*/
function assertIsSDQResponse(data: unknown): asserts data is SDQResponse {
if (typeof data !== 'object' || data === null) {
throw new Error('data is not an object');
}
if (!('SDQOutputSet' in data) || typeof data.SDQOutputSet !== 'object') {
throw new Error('data.SDQOutputSet is not an object');
}
}
/**
* Type guard to assert that data is a valid SDQQueryWhere
* @param data - The data to validate
* @source
*/
function assertIsSDQWhere(where: unknown): asserts where is SDQWhere {
if (typeof where !== 'object' || where === null) {
throw new Error('where is not an object');
}
}
/**
* Network implementation for {@link executeSDQSearch}; see it for details.
* @param query - The SDQ agent query (where clause, select fields, limit)
* @returns The matching SDQ result rows, or undefined
* @source
*/
async function executeSDQSearchUncached({
where,
select = '*',
limit = 10,
}: SDQAgentQuery): Promise<SDQResultItem[] | undefined> {
try {
assertIsSDQWhere(where);
if (select !== '*') {
if (Array.isArray(select)) {
select = select.join(',');
} else {
select = '*';
}
}
const pubchemQuery = {
select,
limit,
collection: 'compound',
order: ['cid,asc'],
start: 1,
where: { ands: [where] },
};
logger.debug('Built PubChem SDQ query', { pubchemQuery });
const queryURLString = JSON.stringify(pubchemQuery);
const response = await fetch(
`https://pubchem.ncbi.nlm.nih.gov/sdq/sdqagent.cgi?infmt=json&outfmt=json&query=${queryURLString}`,
);
const data = await response.json();
assertIsSDQResponse(data);
const outputSets = data.SDQOutputSet;
if (!outputSets || outputSets.length === 0) {
return undefined;
}
if (outputSets[0].status.code !== 0) {
logger.warn(`SDQ agent returned a non-zero status code: ${outputSets[0].status.code}`, {
where,
select,
limit,
response: data,
});
return undefined;
}
if (outputSets[0].totalCount === 0 || outputSets[0]?.rows?.length === 0) {
logger.debug(`SDQ agent returned no results`, { where, select, limit, response: data });
return undefined;
}
return outputSets[0].rows;
} catch (error) {
logger.error(`Error querying SDQ agent: ${getErrorMessage(error)}`, { error });
}
}
/**
* Query the SDQ agent for a compound name from a synonym. Results are cached for
* three days.
* @category Science Helpers
* @param query - The SDQ agent query (where clause, select fields, limit)
* @returns The compound name from the SDQ agent.
* @example
* ```typescript
* const cmpd = await executeSDQSearch({
* where: { cmpdsynonym: "2-Acetoxybenzenecarboxylic acid" },
* select: ["cid", "cmpdname"],
* limit: 1,
* });
* console.log(cmpd);
* // Outputs: Aspirin
* ```
* @source
*/
export const executeSDQSearch: (query: SDQAgentQuery) => Promise<SDQResultItem[] | undefined> =
withTtlCache(executeSDQSearchUncached, { namespace: 'sdqSearch' });
/**
* Get the compound name from a synonym.
* @category Science Helpers
* @param cmpdsynonym - The synonym to get the compound name from.
* @returns The compound name from the synonym.
* @example
* ```typescript
* const cmpd = await getCompoundNameFromAlias("2-Acetoxybenzenecarboxylic acid");
* console.log(cmpd);
* // Outputs: Aspirin
* ```
* @source
*/
export async function getCompoundNameFromAlias(cmpdsynonym: string): Promise<string | undefined> {
const searchResult = await executeSDQSearch({
where: { cmpdsynonym },
select: ['cid', 'cmpdname', 'iupacname'],
limit: 1,
});
if (!searchResult) {
return undefined;
}
return searchResult[0].cmpdname;
}
/**
* How many of the top (most-popular) PubChem synonyms to consider when suggesting an alternative
* name. Keeps suggestions to widely-recognized names and avoids the obscure long tail.
* @source
*/
const POPULARITY_WINDOW = 3;
/**
* Extracts the synonym list from a PUG-REST synonyms response, narrowing the parsed JSON.
* @param data - The parsed JSON response body
* @returns The array of synonym strings, or undefined if the shape is unexpected/empty
* @source
*/
function extractSynonyms(data: unknown): string[] | undefined {
if (typeof data !== 'object' || data === null || !('InformationList' in data)) {
return undefined;
}
const list = (data as { InformationList?: { Information?: { Synonym?: unknown }[] } })
.InformationList?.Information?.[0]?.Synonym;
if (!Array.isArray(list)) return undefined;
const names = list.filter((entry): entry is string => typeof entry === 'string');
return names.length > 0 ? names : undefined;
}
/**
* Network implementation for {@link getRankedNamesByName}; see it for details.
* @param name - The chemical name to look up
* @returns The ranked synonym list, or undefined
* @source
*/
async function getRankedNamesByNameUncached(name: string): Promise<string[] | undefined> {
try {
const response = await fetch(
`${PUG_REST_BASE}/compound/name/${encodeURIComponent(name)}/synonyms/JSON`,
);
if (!response.ok) return undefined;
const data = await response.json();
return extractSynonyms(data);
} catch (error) {
logger.error(`Error fetching PubChem synonyms: ${getErrorMessage(error)}`, { error });
return undefined;
}
}
/**
* Fetches PubChem's popularity-ranked synonyms for a chemical name via PUG-REST, caching results
* for three days. The leading entries are the most commonly used names, and CAS numbers
* appear inline among them. Returns undefined when PubChem has no match.
* @category Science Helpers
* @param name - The chemical name to look up
* @returns The ranked synonym list, or undefined if not found
* @example
* ```typescript
* await getRankedNamesByName("acetone");
* // Returns: ["acetone", "2-propanone", "67-64-1", "propanone", ...]
* ```
* @source
*/
export const getRankedNamesByName: (name: string) => Promise<string[] | undefined> = withTtlCache(
getRankedNamesByNameUncached,
{ namespace: 'rankedNames' },
);
/**
* Tidies a chemical name for display in a suggestion. PubChem often returns common names in all
* caps (e.g. "ACETYLSALICYLIC ACID"); these are lowercased to read naturally. Names that already
* contain lowercase letters keep their casing, preserving meaningful capitalization (e.g. brand
* names like "Tylenol"). Search matching is case-insensitive, so this only affects presentation.
* @param name - The chemical name to format
* @returns The display-friendly name
* @example
* ```typescript
* formatSuggestedName("ACETYLSALICYLIC ACID") // "acetylsalicylic acid"
* formatSuggestedName("Tylenol") // "Tylenol"
* ```
* @source
*/
function formatSuggestedName(name: string): string {
return /[a-z]/.test(name) ? name : name.toLowerCase();
}
/**
* Determines whether a chemical name is "simple" enough to suggest to a user — an ordinary common
* name made only of letters and spaces, not a long IUPAC- or registry-style technical identifier.
* @category Science Helpers
* @param name - The candidate chemical name
* @returns True if the name is short and contains only letters and spaces
* @example
* ```typescript
* isSimpleName("acetone") // true
* isSimpleName("aspirin") // true
* isSimpleName("2-acetyloxybenzoic acid") // false (contains digits)
* ```
* @source
*/
export function isSimpleName(name: string): boolean {
const trimmed = name.trim();
if (trimmed.length < 3 || trimmed.length > 30) return false;
return /^[A-Za-z][A-Za-z ]*$/.test(trimmed);
}
/**
* Suggests a simpler alternative search term when a query yields no results. Pulls PubChem's
* popularity-ranked synonyms for the query, keeps only simple common names (see {@link isSimpleName}),
* and skips any term the user has already tried. Falls back to the compound's CAS number when no
* suitable simple name remains. Either field may be undefined.
* @category Science Helpers
* @param query - The original (unsuccessful) search query
* @param excluded - Lowercased terms to skip (e.g. previously searched, zero-result queries)
* @returns The best simple alternative name and/or a CAS fallback
* @example
* ```typescript
* await suggestAlternativeSearch("2-propanone", new Set(["2-propanone"]));
* // Returns: { name: "acetone", cas: "67-64-1" }
* ```
* @source
*/
export async function suggestAlternativeSearch(
query: string,
excluded: ReadonlySet<string>,
): Promise<{ name?: string; cas?: string }> {
const ranked = await getRankedNamesByName(query);
if (!ranked) return {};
const queryLc = query.toLowerCase();
const isSkipped = (value: string): boolean =>
value.toLowerCase() === queryLc || excluded.has(value.toLowerCase());
// PubChem returns synonyms in descending popularity. Only suggest a name from the few most
// common ones — deeper entries are obscure (e.g. "Dimethyl ketone" for acetone) and just as
// unlikely to yield results, so we'd rather offer the CAS than a name nobody recognizes.
const match = ranked
.slice(0, POPULARITY_WINDOW)
.find((entry) => isSimpleName(entry) && !isSkipped(entry));
const name = match ? formatSuggestedName(match) : undefined;
const cas = ranked.find((entry) => isCAS(entry) && !excluded.has(entry.toLowerCase()));
return { name, cas };
}
/**
* How many alternative names {@link suggestAdvancedQuery} combines into one advanced query.
* @source
*/
const ADVANCED_QUERY_NAME_COUNT = 3;
/**
* Formats a single term for an advanced (AST) query, quoting it when it contains whitespace or
* parentheses so the parser keeps it as one phrase.
* @param term - The name or CAS number
* @returns The term, quoted if necessary
* @example
* ```typescript
* quoteAdvancedTerm("dimethyl ketone") // '"dimethyl ketone"'
* quoteAdvancedTerm("propanone") // 'propanone'
* ```
* @source
*/
function quoteAdvancedTerm(term: string): string {
return /[\s()]/.test(term) ? `"${term}"` : term;
}
/**
* Suggests an advanced (AST) search for a query that returned no results. Combines the three most
* common PubChem names for the compound, plus its CAS number, with `OR`. The original query (and
* any term in `excluded`) is left out of the result, since it is already known to find nothing.
* Returns undefined when PubChem has no match or fewer than two terms remain.
* @category Science Helpers
* @param query - The original (unsuccessful) basic search query
* @param excluded - Lowercased terms to skip (e.g. previously searched, zero-result queries)
* @returns The advanced query string, or undefined if there is nothing worth suggesting
* @example
* ```typescript
* await suggestAdvancedQuery("acetone", new Set(["acetone"]));
* // Returns: "2-propanone OR propanone OR propan-2-one OR 67-64-1"
* ```
* @source
*/
export async function suggestAdvancedQuery(
query: string,
excluded: ReadonlySet<string>,
): Promise<string | undefined> {
const ranked = await getRankedNamesByName(query);
if (!ranked) return undefined;
const seen = new Set<string>([query.trim().toLowerCase(), ...excluded]);
const take = (entry: string): boolean => {
const key = entry.toLowerCase();
if (seen.has(key) || entry.includes('"')) return false;
seen.add(key);
return true;
};
const names = ranked
.filter((entry) => !isCAS(entry))
.filter(take)
.slice(0, ADVANCED_QUERY_NAME_COUNT)
.map((entry) => quoteAdvancedTerm(formatSuggestedName(entry)));
const cas = ranked.find((entry) => isCAS(entry) && take(entry));
const terms = cas ? [...names, cas] : names;
if (terms.length < 2) return undefined;
const advanced = terms.join(' OR ');
return hasAdvancedSyntax(advanced) ? advanced : undefined;
}
/**
* Gets the PubChem ID from the links in the document.
* @category Science Helpers
* @param doc - The document to search for PubChem links
* @returns The PubChem ID, or undefined if not found
* @example
* ```typescript
* const pubchemId = getPubchemIdFromDocument(document);
* console.log(pubchemId);
* // Outputs: 1234567890
* ```
*/
export function getPubchemIdFromDocument(doc: Document): number | undefined {
const link = doc.querySelector('a[href*="pubchem.ncbi.nlm.nih.gov/substance"]');
if (!(link instanceof HTMLAnchorElement)) return undefined;
const pubchemId = link.href.split('/').pop();
if (!pubchemId || isNaN(Number(pubchemId))) return undefined;
return Number(pubchemId);
}
|