All files / src/suppliers SupplierBaseAmazon.ts

21.13% Statements 78/369
0% Branches 0/1
0% Functions 0/9
21.13% Lines 78/369

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 5191x 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                                 1x           1x 1x                                                                                                                                                                                                                                                                                                                       1x         1x 1x                             1x         1x 1x                                                           1x           1x         1x 1x     1x  
import { AVAILABILITY } from '@/constants/common';
import { getCurrencyCodeFromSymbol, parsePrice } from '@/helpers/currency';
import { findElementWithText } from '@/helpers/dom';
import { parseQuantity } from '@/helpers/quantity';
import { createDOM } from '@/helpers/request';
import { getUserLocation, mapDefined, tryParseJson } from '@/helpers/utils';
import { ProductBuilder } from '@/utils/ProductBuilder';
import { SupplierBase } from './SupplierBase';
import { getErrorMessage } from '@/helpers/exceptions';
 
export interface SearchItem {
  id: string;
  productUrl: string;
  title: string;
  currency: CurrencyCode;
  price: number;
  originalPrice: number;
  starRating: number;
  totalRatings: number;
  apiUrl: string;
}
 
export interface SearchResult {
  metadata: {
    totalResults: number;
    thisPageResults: number;
    page: number;
    query: string;
  };
  pagination: {
    nextPage: string | null;
    prevPage: string | null;
  };
  results: SearchItem[];
}
 
export type AmazonListing = Pick<
  Product,
  'id' | 'title' | 'url' | 'price' | 'currencySymbol' | 'availability' | 'sku'
>;
 
const amazonDomains: CountryDomainMap = {
  US: 'https://www.amazon.com', // United States (default)
  UK: 'https://www.amazon.co.uk', // United Kingdom
  DE: 'https://www.amazon.de', // Germany
  JP: 'https://www.amazon.co.jp', // Japan
  CA: 'https://www.amazon.ca', // Canada
  FR: 'https://www.amazon.fr', // France
  AU: 'https://www.amazon.com.au', // Australia
  CN: 'https://www.amazon.cn', // China
  ES: 'https://www.amazon.es', // Spain
  IT: 'https://www.amazon.it', // Italy
  IN: 'https://www.amazon.in', // India
  NL: 'https://www.amazon.nl', // Netherlands
  PL: 'https://www.amazon.pl', // Poland
  PT: 'https://www.amazon.pt', // Portugal
  SE: 'https://www.amazon.se', // Sweden
  SG: 'https://www.amazon.com.sg', // Singapore
  MX: 'https://www.amazon.com.mx', // Mexico
  AE: 'https://www.amazon.ae', // United Arab Emirates
  BR: 'https://www.amazon.com.br', // Brazil
  TR: 'https://www.amazon.com.tr', // Turkey
  SA: 'https://www.amazon.sa', // Saudi Arabia
  AR: 'https://www.amazon.com.ar', // Argentina
  BE: 'https://www.amazon.com.be', // Belgium
  EG: 'https://www.amazon.eg', // Egypt
  IE: 'https://www.amazon.ie', // Ireland
  ZA: 'https://www.amazon.co.za', // South Africa
};
 
const userCountry = getUserLocation();
 
/**
 * Base class for Amazon suppliers
 *
 * @remarks
 * This class is used to query products from Amazon.
 *
 * @source
 */
export abstract class SupplierBaseAmazon
  extends SupplierBase<Product, Product>
  implements ISupplier
{
  /**
   * The base URL of Amazon - This is determined by the users locale (eg: using output of
   * getUserLocation() from /src/helpers/utils.ts) and a lookup table. Defaults to "US" if
   * the user's country is not found in the lookup table.
   * @source
   */
  public static readonly baseURL: string = amazonDomains[userCountry] || amazonDomains['US'];
 
  /**
   * Terms found in the listing - An array of strings, at least one of which must be
   * foud in the initial listing on the product search results page.
   * @source
   */
  protected termsFoundInListing?: string[];
 
  /**
   * Extra parameters to add to the query.url
   * @source
   */
  protected extraParams?: string;
 
  /**
   * Prefix to add to the query (ie: brand name or seller name)
   * @source
   */
  protected readonly queryPrefix?: string;
 
  /**
   * Derives the unique product key from an Amazon listing: its `data-uuid`
   * (parsed onto `id`), which is stable per product. Falls back to the ASIN
   * (`sku`) and then the product URL when the uuid is absent, so the key is
   * always non-empty.
   * @param data - The raw Amazon listing
   * @returns The listing's uuid, or its ASIN / product URL as a fallback
   * @example
   * ```typescript
   * this.getUniqueProductKey(item); // "b8f3…-uuid"
   * ```
   * @source
   */
  protected getUniqueProductKey(data: AmazonListing): string {
    return String(data.id ?? data.sku ?? this.href(String(data.url)));
  }
 
  /**
   * Queries products from Amazon
   * @param query - The query to search for
   * @param limit - The maximum number of products to return
   * @returns The products from Amazon
   * @source
   */
  protected async queryProducts(
    query: string,
    limit: number = this.limit,
  ): Promise<ProductBuilder<Product>[] | void> {
    const queryPagination = async (paginationQuery: string, page: number = 1) => {
      const response = await this.httpPost({
        path: `/s?k=${paginationQuery}&page=${page}&${this.extraParams || ''}`,
        body: {
          'page-content-type': 'atf',
          'prefetch-type': 'rq',
          'customer-action': 'pagination',
        },
        headers: {
          'Accept-Language': 'en-US,en;q=0.6',
          Referrerpolicy: 'strict-origin-when-cross-origin',
          Cookie: 'i18n-prefs=USD; lc-main=en_US',
        },
      });
      if (!response) {
        this.logger.error('Search request returned no response', { response });
        return;
      }
 
      const responseText = await response.text();
      this.logger.debug('Search response length before removing the search term', {
        length: responseText.length,
        responseText,
      });
      const responseTextWithoutSearchTerm = responseText.replaceAll(paginationQuery, '');
      this.logger.debug('Search response length after removing the search term', {
        length: responseTextWithoutSearchTerm.length,
        responseTextWithoutSearchTerm,
      });
      return this.parseResponse(String(responseTextWithoutSearchTerm));
    };
 
    const resultPages: (unknown | void)[] = await Promise.all(
      Array.from({ length: Math.ceil(limit / 16) }, (_, i) =>
        queryPagination(`${this.queryPrefix ?? this.supplierName}+${query}`, i + 1),
      ),
    );
 
    this.logger.debug('Fetched search result pages', { query, resultPages });
    if (!resultPages || !Array.isArray(resultPages) || resultPages.length === 0) {
      throw new Error('Result pages not found');
    }
 
    const searchTerm = `${this.queryPrefix ?? this.supplierName}+${query}`;
 
    const results = resultPages.flatMap((resultPage) => {
      if (!resultPage) return [];
 
      // New format: response is an HTML string
      if (typeof resultPage === 'string') {
        const htmlWithoutSearchTerm = resultPage.replaceAll(searchTerm, '');
        const doc = createDOM(htmlWithoutSearchTerm);
        // const resultElements = doc.querySelectorAll(
        //   '[data-component-type="s-search-result"][data-asin]',
        // );
        const resultElements = Array.from(
          doc.querySelectorAll('[data-component-type="s-search-result"][data-asin]'),
        ).filter(
          (li) =>
            li instanceof HTMLElement &&
            li.checkVisibility() &&
            li.getAttribute('data-asin') &&
            li.getAttribute('data-uuid'),
        );
 
        return mapDefined(resultElements, (el) =>
          this.parseSearchResult(el.outerHTML, this.baseURL),
        );
      }
 
      // Old format: response is an array of ["dispatch", "data-main-slot:search-result-N", {html}]
      if (Array.isArray(resultPage)) {
        return mapDefined(resultPage, (page: unknown) => {
          if (!page) return;
          if (!Array.isArray(page)) return;
          if (page.length !== 3) return;
          if (page[0] !== 'dispatch') return;
          if (!page[1].startsWith('data-main-slot:search-result-')) return;
          return this.parseSearchResult(page[2].html.replaceAll(searchTerm, ''), this.baseURL);
        });
      }
 
      return [];
    });
 
    this.logger.debug('Parsed search results', { query, results });
 
    const fuzzedResults = this.fuzzyFilterAst(results, 40);
    this.logger.debug('Applied fuzzy filter to search results', { query, results, fuzzedResults });
 
    return this.initProductBuilders(fuzzedResults);
  }
 
  /**
   * Checks if the listing meets the requirements
   * @param result - The listing to check
   * @returns True if the listing meets the requirements, false otherwise
   * @source
   */
  protected checkRequirementsForListing(result: HTMLElement): boolean {
    const resultText = result.textContent?.toLowerCase() ?? '';
    const searchList = [...(this.termsFoundInListing ?? []), this.supplierName];
 
    const matchedString = searchList.some((term) => {
      const found = resultText.toLowerCase().includes(term.toLowerCase());
      if (found) {
        this.logger.debug(`Term "${term}" FOUND in listing`, {
          term,
          resultText,
        });
      }
      return found;
    });
 
    if (!matchedString) {
      this.logger.debug('Did not find any of the specified strings in the product listing', {
        matchedString,
        searchList,
        resultText,
        result,
      });
    }
 
    return matchedString;
  }
 
  private findQID(doc: Document): Maybe<string> {
    // const link = Array.from(doc.querySelectorAll("a")).find((a: HTMLAnchorElement) =>
    //   a.href.includes("qid="),
    // );
    const xpath = ".//a[contains(@href, 'qid=')]";
 
    const nodes = document.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
 
    const link = nodes.singleNodeValue;
    if (!(link instanceof HTMLAnchorElement)) {
      this.logger.warn('No QID found', { doc });
      return;
    }
    this.logger.debug('Found QID in listing link', { qid: link.href.split('qid=').at(1) });
    return link.href.split('qid=').at(1);
  }
 
  /**
   * Parses the search result from Amazon
   * @param raw - The raw HTML of the search result
   * @param amazonBase - The base URL of Amazon
   * @returns The parsed search result
   * @source
   */
  private parseSearchResult(raw: string, amazonBase: string): Maybe<AmazonListing> {
    try {
      // To help ensure the products are from the requested supplier, run a quick check for the suppliers name.
      // That's usually included in the listing somewhere.
      // Note: To exclude any false positives from matching with any hyperlinks that have the current search
      // term (which would include the suppliers name), the exact search term (supplier+query) is removed from
      // the raw HTML before this method is called.
      if (!raw.toLowerCase().includes(this.supplierName.toLowerCase())) {
        this.logger.debug('This item does not contain the suppliers name anywhere, removing', {
          raw,
        });
        return;
      }
 
      // Sometimes those sponsored listings can sneak through... Just outright delete anything that has the
      // word "sponsored" in the raw HTML.
      if (raw.toLowerCase().includes('sponsored')) {
        this.logger.debug('This item is a sponsored listing, removing', {
          raw,
        });
        return;
      }
 
      const listingDocument = createDOM(`<html><body>${raw}</body></html>`);
      this.logger.debug('Parsed product listing document', { raw, listingDocument });
 
      const documentBody = listingDocument.body;
      const productElement = documentBody.querySelector('[data-asin]');
      if (!productElement) {
        this.logger.warn('No product element found', { raw, documentBody });
        return;
      }
      const asin = productElement.getAttribute('data-asin');
      const productId = productElement.getAttribute('data-uuid');
 
      if (!asin || !productId) {
        this.logger.warn('No ASIN or product ID found', { raw, documentBody, productElement });
        return;
      }
 
      this.logger.debug('Extracted product page body', {
        raw,
        documentBody,
        productElement,
        asin,
        productId,
      });
 
      const qid = this.findQID(listingDocument);
      if (!qid) {
        this.logger.warn('No QID found', { raw, listingDocument });
      } else {
        this.logger.debug('Resolved listing QID', { raw, listingDocument, qid });
      }
 
      // Check if the listing meets the requirements. Use textContent because many of the hyperlinks
      // will have the search term saved in the href attribute.
      if (!this.checkRequirementsForListing(documentBody)) {
        return;
      }
 
      if (!documentBody) {
        throw new Error('Document body not found');
      }
 
      const stockElement = findElementWithText(documentBody, 'left in stock', 'span');
      if (stockElement) {
        this.logger.debug('Found stock availability element', { stockElement });
      }
 
      // Extracting the title
      const titleElement = documentBody.querySelector('a h2 span');
      const title = titleElement ? titleElement.textContent?.trim() : null;
 
      // Extracting the price
      const priceElement = documentBody.querySelector('span.a-price span.a-price-whole');
      let price = priceElement ? priceElement.textContent?.trim() : null;
 
      // Extracting the currency
      const currencyElement = documentBody.querySelector('span.a-price-symbol');
      let currency = currencyElement ? currencyElement.textContent?.trim() : null;
 
      // Extracting the original price
      const originalPriceElement = documentBody.querySelector('span.a-text-price span.a-offscreen');
      let originalPrice = originalPriceElement ? originalPriceElement.textContent?.trim() : null;
 
      // This is a fallback for when the price and currency are not found in the expected locations.
      if (!price || !currency) {
        const priceAndCurrency = Array.from(documentBody.querySelectorAll('span, div'))
          .map((element) => element.textContent)
          .find((text) => !!text && /^\$\d+\.\d+$/.test(text));
 
        if (priceAndCurrency) {
          const parsedPrice = parsePrice(priceAndCurrency);
          if (!price) price = String(parsedPrice?.price ?? '');
          if (!currency) currency = parsedPrice?.currencySymbol;
          if (!originalPrice) originalPrice = priceAndCurrency;
        }
      }
 
      // Extracting the product ID (ASIN)
      // const productElement = documentBody.querySelector("[data-asin]");
      // const sku = productElement ? productElement.getAttribute("data-asin") : null;
      // const productId = productElement ? productElement.getAttribute("data-uuid") : null;
 
      this.logger.debug('Matched product details from listing', {
        productElement,
        productId,
        asin,
        title,
        originalPrice,
        price,
        currency,
      });
 
      if (!productId || !title || !price || !currency) {
        this.logger.warn('Missing required fields', {
          productElement,
          productId,
          title,
          asin,
          price,
          currency,
        });
        return;
      }
 
      // Extracting the star rating
      //const starRatingElement = documentBody.querySelector("span.a-icon-alt");
      //const starRating = starRatingElement ? Number(starRatingElement.textContent?.split(" ")[0] || "0") : 0;
 
      // Extracting the total ratings
      //const totalRatingsElement = documentBody.querySelector("span.a-size-base");
      //const totalRatings = totalRatingsElement ? Number(totalRatingsElement.textContent || "0") : 0;
 
      return {
        id: productId,
        sku: asin,
        availability: stockElement?.textContent?.toLowerCase().includes('order soon')
          ? AVAILABILITY.LIMITED_STOCK
          : AVAILABILITY.IN_STOCK,
        url: `${amazonBase}/dp/${asin}`,
        title,
        currencySymbol: currency,
        price: Number(price),
      };
    } catch (error) {
      this.logger.error(`Error parsing search result: ${getErrorMessage(error)}`, {
        error,
        raw,
        amazonBase,
      });
      return;
    }
  }
 
  /**
   * Parses the response from Amazon
   * @param response - The response from Amazon
   * @returns The parsed response
   * @source
   */
  protected parseResponse(response: string): unknown {
    try {
      return JSON.parse(response);
    } catch {
      try {
        const splitted = response.split('\n&&&\n');
        if (splitted.length < 3) throw new Error();
 
        return mapDefined(splitted, tryParseJson);
      } catch {
        return String(response ?? '');
      }
    }
  }
 
  /**
   * Initializes product builders from Amazon listings
   * @param results - The Amazon listings to initialize product builders from
   * @returns An array of product builders
   * @source
   */
  protected initProductBuilders(results: AmazonListing[]): ProductBuilder<Product>[] {
    return mapDefined(results, (item) => {
      const builder = new ProductBuilder(this.baseURL);
      builder
        .setBasicInfo(item.title, item.url, this.supplierName)
        .setMatchPercentage(this.matchScoreOf(item))
        .setPricing(item.price, getCurrencyCodeFromSymbol(item.currencySymbol), item.currencySymbol)
        .setAvailability(item.availability ?? AVAILABILITY.UNKNOWN)
        .setVendor('Amazon')
        .setID(item.id)
        .setSku(item.sku)
        .setCacheKey(this.getUniqueProductKey(item));
 
      const quantity = parseQuantity(item.title);
 
      if (!quantity) {
        this.logger.warn('Failed to get quantity from retrieved product title', {
          title: item.title,
          builder,
          item,
        });
        return;
      }
 
      builder.setQuantity(quantity.quantity, quantity.uom);
 
      return builder;
    });
  }
 
  protected async getProductData(
    product: ProductBuilder<Product>,
  ): Promise<ProductBuilder<Product> | void> {
    return product;
  }
 
  /**
   * Selects the title of a product from the search response
   * @param data - Product object from search response
   * @returns - The title of the product
   * @source
   */
  protected titleSelector(data: AmazonListing): string {
    return data.title;
  }
}