discogs-marketplace-api-nodejs 1.16.9 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.MD +111 -151
  2. package/dist/data/country.data.d.ts +1 -1
  3. package/dist/data/style.data.d.ts +763 -0
  4. package/dist/data/style.data.js +765 -0
  5. package/dist/index.d.ts +4 -1
  6. package/dist/index.js +2 -1
  7. package/dist/interfaces/api/marketplace-search-result.api.interface.d.ts +148 -0
  8. package/dist/interfaces/api/{shop-details-result.api.interface.d.ts → releases-result.api.interface.d.ts} +4 -1
  9. package/dist/interfaces/api/wantlist-result.api.interface.d.ts +109 -0
  10. package/dist/interfaces/search-params.interface.d.ts +76 -156
  11. package/dist/interfaces/search-result.interface.d.ts +21 -19
  12. package/dist/scrapers/browser-context.d.ts +10 -0
  13. package/dist/scrapers/browser-context.js +49 -0
  14. package/dist/scrapers/marketplace.scraper.d.ts +10 -0
  15. package/dist/scrapers/marketplace.scraper.js +300 -0
  16. package/dist/search.d.ts +4 -7
  17. package/dist/search.js +10 -57
  18. package/dist/types/condition.type.d.ts +4 -0
  19. package/dist/types/currency.type.d.ts +1 -1
  20. package/dist/types/format-description.type.d.ts +1 -1
  21. package/dist/types/sort.type.d.ts +1 -1
  22. package/dist/types/style.type.d.ts +2 -1
  23. package/dist/wantlist.d.ts +28 -0
  24. package/dist/wantlist.js +105 -0
  25. package/package.json +14 -16
  26. package/dist/data/currency.data.d.ts +0 -36
  27. package/dist/data/currency.data.js +0 -35
  28. package/dist/interfaces/api/shop-result-error.api.interface.d.ts +0 -8
  29. package/dist/interfaces/api/shop-result.api.interface.d.ts +0 -111
  30. package/dist/scrapers/extractors/legacy.extractor.d.ts +0 -11
  31. package/dist/scrapers/extractors/legacy.extractor.js +0 -138
  32. package/dist/scrapers/legacy.scraper.d.ts +0 -13
  33. package/dist/scrapers/legacy.scraper.js +0 -75
  34. package/dist/scrapers/modern.scraper.d.ts +0 -13
  35. package/dist/scrapers/modern.scraper.js +0 -199
  36. package/dist/scrapers/wantlist.scraper.d.ts +0 -13
  37. package/dist/scrapers/wantlist.scraper.js +0 -66
  38. package/dist/types/api.type.d.ts +0 -4
  39. package/dist/types/api.type.js +0 -2
  40. package/dist/types/lang.type.d.ts +0 -4
  41. package/dist/types/lang.type.js +0 -2
  42. package/dist/types/limit.type.d.ts +0 -4
  43. package/dist/types/limit.type.js +0 -2
  44. /package/dist/interfaces/api/{shop-details-result.api.interface.js → marketplace-search-result.api.interface.js} +0 -0
  45. /package/dist/interfaces/api/{shop-result-error.api.interface.js → releases-result.api.interface.js} +0 -0
  46. /package/dist/interfaces/api/{shop-result.api.interface.js → wantlist-result.api.interface.js} +0 -0
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = getWantlistReleaseIds;
7
+ const browser_context_1 = __importDefault(require("./scrapers/browser-context.js"));
8
+ /** Wants per page of the Discogs API */
9
+ const API_PER_PAGE = 500;
10
+ /** Wants per page of the wantlist page */
11
+ const PAGE_PER_PAGE = 250;
12
+ /**
13
+ * Get the release IDs from every page of a wantlist: the first page tells how many there are, the others are fetched
14
+ * in parallel.
15
+ * @param getPage Get the release IDs of a page, and the total number of pages
16
+ * @returns Release IDs
17
+ */
18
+ async function getAllPages(getPage) {
19
+ const firstPage = await getPage(1);
20
+ const otherPages = await Promise.all(Array.from({ length: firstPage.pages - 1 }, (_, i) => getPage(i + 2)));
21
+ return [...new Set([firstPage, ...otherPages].flatMap(x => x.ids))];
22
+ }
23
+ /**
24
+ * Get the IDs of the releases of a wantlist, from the Discogs API.
25
+ * @param username Username whose wantlist is read
26
+ * @param token Discogs personal access token
27
+ * @returns Release IDs
28
+ */
29
+ function fetchWantlist(username, token) {
30
+ return getAllPages(async (pageNumber) => {
31
+ const response = await fetch(`https://api.discogs.com/users/${encodeURIComponent(username)}/wants?${new URLSearchParams({
32
+ page: pageNumber.toString(),
33
+ per_page: API_PER_PAGE.toString(),
34
+ }).toString()}`, {
35
+ headers: {
36
+ 'User-Agent': `DiscogsMarketplaceApiNodeJS-${username}`,
37
+ ...(token ? { Authorization: `Discogs token=${token}` } : {}),
38
+ },
39
+ });
40
+ const json = (await response.json().catch(() => null));
41
+ if (!response.ok) {
42
+ throw new Error(json?.message ?? `An error ${response.status} occurred.`);
43
+ }
44
+ return {
45
+ ids: json?.wants?.map(x => x.id ?? 0).filter(x => !!x) ?? [],
46
+ pages: json?.pagination?.pages ?? 0,
47
+ };
48
+ });
49
+ }
50
+ /**
51
+ * Get the IDs of the releases of a wantlist that are currently for sale, from the wantlist page.
52
+ * @param username Username whose wantlist is read
53
+ * @param browserContext Patchright browser context
54
+ * @returns Release IDs
55
+ */
56
+ function scrapeWantlist(username, browserContext) {
57
+ return getAllPages(async (pageNumber) => {
58
+ const browserPage = await browserContext.newPage();
59
+ try {
60
+ // The total is read from the English text of the page ("1 – 250 of 1,234")
61
+ await browserPage.setExtraHTTPHeaders({ 'Accept-Language': 'en-US,en;q=0.9' });
62
+ await browserPage.route('**/*', route => (route.request().resourceType() === 'document' ? route.continue() : route.abort()));
63
+ const response = await browserPage.goto(`https://www.discogs.com/wantlist?${new URLSearchParams({
64
+ page: pageNumber.toString(),
65
+ limit: PAGE_PER_PAGE.toString(),
66
+ user: username,
67
+ layout: 'sm',
68
+ }).toString()}`, { waitUntil: 'domcontentloaded' });
69
+ // An unknown user or a private wantlist has nothing for sale
70
+ if (response?.status() === 404) {
71
+ return { ids: [], pages: 0 };
72
+ }
73
+ if (!response?.ok()) {
74
+ const status = response?.status() ?? '?';
75
+ const { 'cf-mitigated': cfMitigated, 'cf-ray': cfRay = '?' } = response?.headers() ?? {};
76
+ throw new Error(cfMitigated
77
+ ? `An error ${status} occurred: blocked by Cloudflare (${cfMitigated}, cf-ray ${cfRay}).`
78
+ : `An error ${status} occurred.`);
79
+ }
80
+ const { total, ids } = await browserPage.evaluate(() => ({
81
+ total: +(document.querySelector('.pagination_total')?.textContent.split(' of ').pop()?.replace(/,/g, '') ?? '0'),
82
+ // The releases for sale are the ones with a link to their listings
83
+ ids: [...document.querySelectorAll('.marketplace_for_sale_count a')].map(x => +(new URL(x.href).pathname.split('/').pop() ?? '0')),
84
+ }));
85
+ return { ids, pages: Math.ceil(total / PAGE_PER_PAGE) };
86
+ }
87
+ finally {
88
+ await browserPage.close();
89
+ }
90
+ });
91
+ }
92
+ /**
93
+ * Gets the IDs of the releases in a user's wantlist, to pass as `releaseIds` to `search`.
94
+ * By default, it reads the public Discogs API (limited to 25 requests per minute without token, 60 with).
95
+ * @param username - Username whose wantlist is read.
96
+ * @param options - Options.
97
+ * @param browserInstance - Optional Patchright browser instance, only used with `onlyForSale`. If provided, you must manage its lifecycle.
98
+ * @returns A promise that resolves to the release IDs.
99
+ */
100
+ async function getWantlistReleaseIds(username, { token, onlyForSale = false } = {}, browserInstance) {
101
+ if (onlyForSale) {
102
+ return (0, browser_context_1.default)(browserInstance, browserContext => scrapeWantlist(username, browserContext));
103
+ }
104
+ return fetchWantlist(username, token);
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.16.9",
3
+ "version": "1.17.1",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",
@@ -40,30 +40,28 @@
40
40
  }
41
41
  ],
42
42
  "dependencies": {
43
- "playwright-chromium": "^1.62.1",
44
- "playwright-extra": "^4.3.6",
45
- "puppeteer-extra-plugin-stealth": "^2.11.2"
43
+ "patchright": "^1.63.0"
46
44
  },
47
45
  "devDependencies": {
48
46
  "@eslint/js": "^9.39.5",
49
- "@types/node": "^24.13.3",
50
- "@typescript-eslint/eslint-plugin": "^8.67.0",
51
- "@typescript-eslint/parser": "^8.67.0",
52
- "cspell": "^10.0.1",
47
+ "@types/node": "^24.13.6",
48
+ "@typescript-eslint/eslint-plugin": "^8.70.0",
49
+ "@typescript-eslint/parser": "^8.70.0",
50
+ "cspell": "^10.3.3",
53
51
  "eslint": "^9.39.5",
54
52
  "eslint-config-prettier": "^10.1.8",
55
53
  "eslint-import-resolver-typescript": "^4.4.5",
56
54
  "eslint-plugin-import": "^2.32.0",
57
- "eslint-plugin-jsdoc": "^63.3.3",
58
- "globals": "^17.11.0",
55
+ "eslint-plugin-jsdoc": "^64.5.4",
56
+ "globals": "^17.12.0",
59
57
  "husky": "^9.1.7",
60
- "knip": "^6.32.2",
61
- "lint-staged": "^17.3.0",
62
- "prettier": "^3.9.6",
58
+ "knip": "^6.37.0",
59
+ "lint-staged": "^17.5.1",
60
+ "prettier": "^3.9.8",
63
61
  "rimraf": "^6.1.3",
64
- "tsc-alias": "^1.9.1",
65
- "tsx": "^4.23.12",
62
+ "tsc-alias": "^1.9.5",
63
+ "tsx": "^4.23.15",
66
64
  "typescript": "^6.0.3",
67
- "typescript-eslint": "^8.67.0"
65
+ "typescript-eslint": "^8.70.0"
68
66
  }
69
67
  }
@@ -1,36 +0,0 @@
1
- declare const Currency: {
2
- readonly $US: "USD";
3
- readonly US$: "USD";
4
- readonly USD: "USD";
5
- readonly '\u00A3GB': "GBP";
6
- readonly GBP: "GBP";
7
- readonly $CA: "CAD";
8
- readonly CA$: "CAD";
9
- readonly CAD: "CAD";
10
- readonly $AU: "AUD";
11
- readonly AU$: "AUD";
12
- readonly AUD: "AUD";
13
- readonly JPY: "JPY";
14
- readonly CHF: "CHF";
15
- readonly MX$: "MXN";
16
- readonly $MX: "MXN";
17
- readonly MXN: "MXN";
18
- readonly $NZ: "NZD";
19
- readonly NZ$: "NZD";
20
- readonly NZD: "NZD";
21
- readonly SEK: "SEK";
22
- readonly ZAR: "ZAR";
23
- readonly BRL: "BRL";
24
- readonly DKK: "DKK";
25
- readonly A$: "AUD";
26
- readonly R$: "BRL";
27
- readonly EUR: "EUR";
28
- readonly '\u20AC': "EUR";
29
- readonly $: "USD";
30
- readonly '\u00A3': "GBP";
31
- readonly '\u00A5': "JPY";
32
- };
33
- export type CurrencyType = typeof Currency;
34
- export type CurrencyKeys = keyof CurrencyType;
35
- export type CurrencyValues = CurrencyType[CurrencyKeys];
36
- export default Currency;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const Currency = {
4
- $US: 'USD',
5
- US$: 'USD',
6
- USD: 'USD',
7
- '£GB': 'GBP',
8
- GBP: 'GBP',
9
- $CA: 'CAD',
10
- CA$: 'CAD',
11
- CAD: 'CAD',
12
- $AU: 'AUD',
13
- AU$: 'AUD',
14
- AUD: 'AUD',
15
- JPY: 'JPY',
16
- CHF: 'CHF',
17
- MX$: 'MXN',
18
- $MX: 'MXN',
19
- MXN: 'MXN',
20
- $NZ: 'NZD',
21
- NZ$: 'NZD',
22
- NZD: 'NZD',
23
- SEK: 'SEK',
24
- ZAR: 'ZAR',
25
- BRL: 'BRL',
26
- DKK: 'DKK',
27
- A$: 'AUD',
28
- R$: 'BRL',
29
- EUR: 'EUR',
30
- '€': 'EUR',
31
- $: 'USD',
32
- '£': 'GBP',
33
- '¥': 'JPY',
34
- };
35
- exports.default = Currency;
@@ -1,8 +0,0 @@
1
- export default interface ShopResultErrorApi {
2
- /** Success */
3
- success: false;
4
- /** Code */
5
- code: number;
6
- /** Detail */
7
- detail: string;
8
- }
@@ -1,111 +0,0 @@
1
- export default interface ShopResultApi {
2
- /** Items */
3
- items?: Array<{
4
- /** ItemId */
5
- itemId?: number;
6
- /** AllowsOffers */
7
- allowsOffers?: boolean;
8
- /** Comments */
9
- comments?: string;
10
- /** ImageUrl */
11
- imageUrl?: string;
12
- /** InCart */
13
- inCart?: boolean;
14
- /** ListedDate */
15
- listedDate?: string;
16
- /** MediaCondition */
17
- mediaCondition?: string;
18
- /** PreviousPrice */
19
- previousPrice?: string;
20
- /** Price */
21
- price?: {
22
- /** Amount */
23
- amount?: number;
24
- /** AmountUsd */
25
- amountUsd?: number;
26
- /** CurrencyCode */
27
- currencyCode?: string;
28
- /** BuyerItemPrice */
29
- buyerItemPrice?: string;
30
- /** BuyerCurrencyCode */
31
- buyerCurrencyCode?: string;
32
- };
33
- /** Release */
34
- release?: {
35
- /** ReleaseId */
36
- releaseId?: number;
37
- /** Artists */
38
- artists?: Array<{
39
- /** ArtistId */
40
- artistId?: number;
41
- /** Name */
42
- name?: string;
43
- }>;
44
- /** Country */
45
- country?: string;
46
- /** FormatNames */
47
- formatNames?: Array<string>;
48
- /** Genres */
49
- genres?: Array<{
50
- /** GenreId */
51
- genreId?: number;
52
- /** Name */
53
- name?: string;
54
- }>;
55
- /** Labels */
56
- labels?: Array<{
57
- /** LabelId */
58
- labelId?: number;
59
- /** Name */
60
- name?: string;
61
- }>;
62
- /** MajorFormat */
63
- majorFormat?: string;
64
- /** Rating */
65
- rating?: number;
66
- /** Title */
67
- title?: string;
68
- /** Year */
69
- year?: number;
70
- };
71
- /** Seller */
72
- seller?: {
73
- /** Uid */
74
- uid?: number;
75
- /** Name */
76
- name?: string;
77
- /** Rating */
78
- rating?: number;
79
- /** RatingCount */
80
- ratingCount?: number;
81
- /** ShipsFrom */
82
- shipsFrom?: string;
83
- /** MinBuyerRating */
84
- minBuyerRating?: number;
85
- /** IndependentSeller */
86
- independentSeller?: boolean;
87
- };
88
- /** Shipping */
89
- shipping?: {
90
- /** ShippingPrice */
91
- shippingPrice?: number;
92
- /** BuyerShippingPrice */
93
- buyerShippingPrice?: number;
94
- /** FreeShippingMin */
95
- freeShippingMin?: number;
96
- };
97
- /** SleeveCondition */
98
- sleeveCondition?: string;
99
- }>;
100
- /** TotalCount */
101
- totalCount?: number;
102
- /** CompleteLookup */
103
- completeLookup?: {
104
- /** Artists */
105
- artists?: string;
106
- /** Sellers */
107
- sellers?: string;
108
- /** Releases */
109
- releases?: Record<string, string>;
110
- };
111
- }
@@ -1,11 +0,0 @@
1
- import type SearchResult from '../../interfaces/search-result.interface.js';
2
- /**
3
- * Parses the page and returns the items found.
4
- * @returns Items found and total
5
- */
6
- export default function extractLegacy(): {
7
- /** Items */
8
- items: SearchResult['items'];
9
- /** Total */
10
- total: number;
11
- };
@@ -1,138 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = extractLegacy;
4
- // These variables are injected by the browser context when the page is loaded.
5
- const { Country, Currency } = globalThis;
6
- /**
7
- * Parses the page and returns the items found.
8
- * @returns Items found and total
9
- */
10
- function extractLegacy() {
11
- /**
12
- * Converts a currency string to a standardized format.
13
- * @param value String to clean
14
- * @returns Cleaned-up string
15
- */
16
- const convertCurrency = (value) => {
17
- if (!value) {
18
- return null;
19
- }
20
- const currencyFound = Object.keys(Currency).find(key => value.includes(key));
21
- if (!currencyFound) {
22
- return null;
23
- }
24
- const currencyClean = Currency[currencyFound];
25
- const amount = value
26
- .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
27
- .replace(currencyFound, '') // Remove original currency
28
- .replace(/\s\s+/g, ''); // Remove spaces
29
- const amountParsed = currencyClean === 'JPY' ? Number.parseInt(amount) : Number.parseFloat(amount);
30
- if (Number.isNaN(amountParsed)) {
31
- return null;
32
- }
33
- return currencyClean === 'JPY' ? `${amountParsed} ${currencyClean}` : `${amountParsed.toFixed(2)} ${currencyClean}`;
34
- };
35
- /**
36
- * Safely parses a number from a string.
37
- * @param value String to parse
38
- * @returns Parsed number or 0 if invalid
39
- */
40
- const safeParseInt = (value) => {
41
- const parsed = Number.parseInt(value ?? '', 10);
42
- return Number.isNaN(parsed) ? 0 : parsed;
43
- };
44
- /**
45
- * Extracts and cleans text content from an element.
46
- * @param selector CSS selector
47
- * @param context Parent element to query from
48
- * @returns Cleaned text content or an empty string
49
- */
50
- const getTextContent = (selector, context = document) => context.querySelector(selector)?.textContent.trim() ?? '';
51
- const total = safeParseInt(getTextContent('.pagination_total')
52
- .split(' ')
53
- .filter(x => x)
54
- .pop()
55
- ?.replace(/(,|\.|\s)/g, ''));
56
- const items = [...document.querySelectorAll('table.table_block tbody tr')].map(el => {
57
- const itemHref = el.querySelector('a.item_description_title')?.getAttribute('href') ?? '';
58
- const mediaCondition = getTextContent('.item_condition span:nth-child(3)', el).split('\n')[0] ?? '';
59
- const sleeveCondition = getTextContent('.item_condition span.item_sleeve_condition', el);
60
- const countryName = getTextContent('.seller_info li:nth-child(3)', el).split(':').pop() ?? '';
61
- const originalTitle = getTextContent('a.item_description_title', el);
62
- const firstIndexOfDash = originalTitle.indexOf(' - ');
63
- const lastIndexOfParenthesis = originalTitle.lastIndexOf(' (');
64
- const releaseHref = el.querySelector('a.item_release_link')?.getAttribute('href') ?? '';
65
- return {
66
- id: safeParseInt(itemHref.split('/').pop()),
67
- title: originalTitle,
68
- artists: [
69
- {
70
- id: null,
71
- name: firstIndexOfDash > -1 ? originalTitle.substring(0, firstIndexOfDash) : '',
72
- url: null,
73
- },
74
- ],
75
- release: {
76
- id: safeParseInt(releaseHref.split('release/').pop()?.split('-').shift()),
77
- name: firstIndexOfDash > -1 && lastIndexOfParenthesis > -1
78
- ? originalTitle.substring(firstIndexOfDash + 3, lastIndexOfParenthesis)
79
- : '',
80
- url: `https://www.discogs.com${releaseHref}`,
81
- },
82
- formats: lastIndexOfParenthesis > -1
83
- ? originalTitle
84
- .substring(lastIndexOfParenthesis + 2, originalTitle.length - 1)
85
- .split(', ')
86
- .filter(x => x)
87
- : [],
88
- labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
89
- .map(x => ({
90
- id: safeParseInt(x.getAttribute('href')?.split('label/').pop()?.split('-').shift()),
91
- name: x.textContent.trim(),
92
- url: `https://www.discogs.com${x.getAttribute('href') ?? ''}`,
93
- }))
94
- .filter((value, index, self) => self.findIndex(v => v.name === value.name) === index),
95
- url: `https://www.discogs.com${itemHref}`,
96
- listedAt: null,
97
- catnos: getTextContent('.label_and_cat .item_catno', el) // cspell:disable-line
98
- .split(', ')
99
- .filter(x => x !== 'none'),
100
- imageUrl: el.querySelector('.marketplace_image')?.getAttribute('data-src') ?? null,
101
- description: getTextContent('.item_condition + *', el) || null,
102
- isAcceptingOffer: getTextContent('.item_add_to_cart p a strong', el).split('/').length > 1,
103
- isAvailable: !el.classList.contains('unavailable'),
104
- condition: {
105
- media: {
106
- full: mediaCondition,
107
- short: /\(([^)]+)\)/.exec(mediaCondition)?.[1] ?? '',
108
- },
109
- sleeve: {
110
- full: sleeveCondition || null,
111
- short: /\(([^)]+)\)/.exec(sleeveCondition)?.[1] ?? null,
112
- },
113
- },
114
- seller: {
115
- name: getTextContent('.seller_info a', el),
116
- url: `https://www.discogs.com${el.querySelector('.seller_info a')?.getAttribute('href') ?? ''}`,
117
- score: getTextContent('.seller_info li:nth-child(2) strong', el) || null,
118
- notes: safeParseInt(getTextContent('.seller_info li:nth-child(2) .section_link', el)) || null,
119
- },
120
- price: {
121
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
122
- base: convertCurrency(getTextContent('.price', el).replace(/,/, '.')),
123
- shipping: convertCurrency(getTextContent('.item_shipping', el)
124
- .replace(/(\s+|\+)/g, ' ')
125
- .replace(',', '.')),
126
- },
127
- country: {
128
- name: countryName,
129
- code: Country[countryName],
130
- },
131
- community: {
132
- have: safeParseInt(getTextContent('.community_summary .community_result:nth-child(1) .community_number', el)),
133
- want: safeParseInt(getTextContent('.community_summary .community_result:nth-child(2) .community_number', el)),
134
- },
135
- };
136
- });
137
- return { items, total };
138
- }
@@ -1,13 +0,0 @@
1
- import type SearchResult from '../interfaces/search-result.interface.js';
2
- import type { SearchParamsLegacy } from '../interfaces/search-params.interface.js';
3
- import type { BrowserContext } from 'playwright-chromium';
4
- /**
5
- * Parses the page and returns the items found.
6
- * @param url Url to scrape
7
- * @param browserContext Playwright browser context
8
- * @returns Items found and total
9
- */
10
- export default function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly, from, sort, limit, page, seller, lang, masterId, labelId, artistId, releaseId, user, query, }: SearchParamsLegacy, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
11
- /** Total items found */
12
- total: SearchResult['result']['total'];
13
- }>;
@@ -1,75 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = scrapeLegacy;
7
- const currency_data_1 = __importDefault(require("../data/currency.data.js"));
8
- const country_data_1 = __importDefault(require("../data/country.data.js"));
9
- const search_1 = require("../search.js");
10
- const legacy_extractor_1 = __importDefault(require("./extractors/legacy.extractor.js"));
11
- /**
12
- * Generate URL to be parsed
13
- * @returns Url
14
- */
15
- function generateUrl({ seller, lang, user, }) {
16
- const baseUrl = `https://www.discogs.com/${lang}`;
17
- if (seller) {
18
- const path = user ? 'mywants' : 'profile';
19
- return `${baseUrl}/seller/${seller}/${path}`;
20
- }
21
- else {
22
- return `${baseUrl}/sell/list`;
23
- }
24
- }
25
- /**
26
- * Parses the page and returns the items found.
27
- * @param url Url to scrape
28
- * @param browserContext Playwright browser context
29
- * @returns Items found and total
30
- */
31
- async function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, seller, lang = 'en', masterId, labelId, artistId, releaseId, user, query, }, browserContext) {
32
- /** Url to be called by the browser */
33
- const urlGenerated = [
34
- generateUrl({ seller, lang, user }),
35
- new URLSearchParams([
36
- ['master_id', masterId?.toString() ?? ''],
37
- ['label_id', labelId?.toString() ?? ''],
38
- ['artist_id', artistId?.toString() ?? ''],
39
- ['release_id', releaseId?.toString() ?? ''],
40
- ['user', user?.toString() ?? ''],
41
- ['q', query ?? ''],
42
- ['currency', currency ?? ''],
43
- ['genre', genre ?? ''],
44
- ...(styles?.map(s => ['style', s]) ?? []),
45
- ...(formats?.map(f => ['format', f]) ?? []),
46
- ...(formatDescriptions?.map(fd => ['format_desc', fd]) ?? []),
47
- ['condition', condition ?? ''],
48
- ['year1', years?.min ? years.min.toString() : ''],
49
- ['year2', years?.max ? years.max.toString() : ''],
50
- ['offers', isMakeAnOfferOnly ? '1' : ''],
51
- ['ships_from', Object.keys(country_data_1.default).find(key => from === country_data_1.default[key]) ?? ''],
52
- ['limit', limit.toString()],
53
- ['page', page.toString()],
54
- ['sort', sort],
55
- ].filter(([, p]) => !!p)).toString(),
56
- ].join('?');
57
- const browserPage = await browserContext.newPage();
58
- await browserPage.route('**/*', route => (route.request().resourceType() === 'document' ? route.continue() : route.abort()));
59
- // Inject some globals to the page, so we can use them in the scraping function
60
- await browserPage.addInitScript(g => Object.assign(globalThis, g), { Country: country_data_1.default, Currency: currency_data_1.default });
61
- const response = await browserPage.goto(urlGenerated);
62
- // See current issue: https://github.com/evanw/esbuild/issues/2605
63
- await browserPage.evaluate(() => (window.__name ??= (func) => func)); // eslint-disable-line
64
- if (!response?.ok()) {
65
- const errorMessage =
66
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
67
- (await browserPage.evaluate(() => document.querySelector('h1 + p')?.innerHTML.trim())) ||
68
- `An error ${response?.status() ?? '?'} occurred.`;
69
- await browserPage.close();
70
- throw new Error(errorMessage);
71
- }
72
- const { items, total } = await browserPage.evaluate(legacy_extractor_1.default);
73
- await browserPage.close();
74
- return { total, items, urlGenerated };
75
- }
@@ -1,13 +0,0 @@
1
- import type SearchResult from '../interfaces/search-result.interface.js';
2
- import type { SearchParamsModern } from '../interfaces/search-params.interface.js';
3
- import type { BrowserContext } from 'playwright-chromium';
4
- /**
5
- * Parses the page and returns the items found.
6
- * @param SearchParams Search parameters
7
- * @param browserContext Playwright browser context
8
- * @returns Items found and total
9
- */
10
- export default function scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly, from, sort, limit, page, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin, hideGenericSleeves, hideSleevelessMedia, showUnavailable, sellerRatingCountMin, }: SearchParamsModern, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
11
- /** Total items found */
12
- total: SearchResult['result']['total'];
13
- }>;