discogs-marketplace-api-nodejs 1.17.0 → 1.18.0

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.
package/README.MD CHANGED
@@ -16,14 +16,16 @@ npm install discogs-marketplace-api-nodejs
16
16
 
17
17
  The searches go through the API of the Discogs shop (`https://www.discogs.com/shop/list`), from a headless browser.
18
18
 
19
- You can also pass your own [Patchright](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright) browser as second parameter of `search`. You then manage its lifecycle.
19
+ You can also pass your own [Patchright](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright) browser context as second parameter of
20
+ `search`, used as is: it keeps the clearance of Cloudflare (`cf_clearance` cookie) from one search to another. You then
21
+ manage its lifecycle.
20
22
 
21
23
  ```ts
22
24
  import { chromium } from 'patchright'
23
25
 
24
- const browser = await chromium.launch({ headless: true })
25
- const result = await DiscogsMarketplace.search({ artistIds: [244819] }, browser)
26
- await browser.close()
26
+ const context = await chromium.launchPersistentContext('./profile', { channel: 'chrome', headless: false, viewport: null })
27
+ const result = await DiscogsMarketplace.search({ artistIds: [244819] }, context)
28
+ await context.close()
27
29
  ```
28
30
 
29
31
  ## ⚡ Quick Start
@@ -148,7 +150,7 @@ const result = await DiscogsMarketplace.search({
148
150
 
149
151
  ## 🧩 API Reference
150
152
 
151
- ### `DiscogsMarketplace.search(searchParams, browserInstance?)`
153
+ ### `DiscogsMarketplace.search(searchParams, browserContext?)`
152
154
 
153
155
  | Field | Type | Description | Example | Default |
154
156
  |-------------------------|-----------------------|------------------------------------------------|-----------------------------------|-----------------|
@@ -1,9 +1,10 @@
1
- import type { Browser, BrowserContext } from 'patchright';
1
+ import type { BrowserContext } from 'patchright';
2
2
  /**
3
- * Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
4
- * JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
5
- * @param browserInstance Browser to use, launched and closed here when not provided
3
+ * Run a function in a browser context suited to call Discogs, closing what it opened afterwards.
4
+ * It looks like a regular Chrome with JavaScript enabled, which Cloudflare lets through more often than the User-Agent
5
+ * of the Discogs apps without JavaScript, especially from datacenter IPs.
6
+ * @param browserContext Browser context to use as is, launched and closed here when not provided
6
7
  * @param fn Function to run
7
8
  * @returns Result of the function
8
9
  */
9
- export default function withBrowserContext<T>(browserInstance: Browser | undefined, fn: (browserContext: BrowserContext) => Promise<T>): Promise<T>;
10
+ export default function withBrowserContext<T>(browserContext: BrowserContext | undefined, fn: (browserContext: BrowserContext) => Promise<T>): Promise<T>;
@@ -3,26 +3,42 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = withBrowserContext;
4
4
  const patchright_1 = require("patchright");
5
5
  /**
6
- * Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
7
- * JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
8
- * @param browserInstance Browser to use, launched and closed here when not provided
6
+ * Get the browser options of a regular Chrome of the same version as the browser, as its default User-Agent and
7
+ * `sec-ch-ua` header give away the headless mode ("HeadlessChrome").
8
+ * @param browser Browser
9
+ * @returns User-Agent, in the reduced form of Chrome ("Chrome/153.0.0.0"), and `sec-ch-ua` header
10
+ */
11
+ async function getChromeIdentity(browser) {
12
+ const session = await browser.newBrowserCDPSession();
13
+ try {
14
+ const { userAgent } = await session.send('Browser.getVersion');
15
+ const [major] = browser.version().split('.');
16
+ return {
17
+ userAgent: userAgent.replace(/HeadlessChrome\/[\d.]+/, `Chrome/${major ?? ''}.0.0.0`),
18
+ extraHTTPHeaders: { 'sec-ch-ua': `"Google Chrome";v="${major ?? ''}", "Not_A Brand";v="8", "Chromium";v="${major ?? ''}"` },
19
+ };
20
+ }
21
+ finally {
22
+ await session.detach();
23
+ }
24
+ }
25
+ /**
26
+ * Run a function in a browser context suited to call Discogs, closing what it opened afterwards.
27
+ * It looks like a regular Chrome with JavaScript enabled, which Cloudflare lets through more often than the User-Agent
28
+ * of the Discogs apps without JavaScript, especially from datacenter IPs.
29
+ * @param browserContext Browser context to use as is, launched and closed here when not provided
9
30
  * @param fn Function to run
10
31
  * @returns Result of the function
11
32
  */
12
- async function withBrowserContext(browserInstance, fn) {
13
- const browser = browserInstance ?? (await patchright_1.chromium.launch({ headless: true, chromiumSandbox: false }));
33
+ async function withBrowserContext(browserContext, fn) {
34
+ if (browserContext) {
35
+ return fn(browserContext);
36
+ }
37
+ const browser = await patchright_1.chromium.launch({ headless: true, chromiumSandbox: false });
14
38
  try {
15
- const browserContext = await browser.newContext({ javaScriptEnabled: false, userAgent: 'Discogs' });
16
- try {
17
- return await fn(browserContext);
18
- }
19
- finally {
20
- await browserContext.close();
21
- }
39
+ return await fn(await browser.newContext(await getChromeIdentity(browser)));
22
40
  }
23
41
  finally {
24
- if (!browserInstance) {
25
- await browser.close();
26
- }
42
+ await browser.close();
27
43
  }
28
44
  }
@@ -49,6 +49,19 @@ const CONDITIONS = {
49
49
  NOT_GRADED: 'Not Graded',
50
50
  NO_COVER: 'No Cover',
51
51
  };
52
+ /**
53
+ * Get a new clearance of Cloudflare (`cf_clearance` cookie), the page staying on the Discogs origin
54
+ * @param page Page
55
+ */
56
+ async function renewClearance(page) {
57
+ const hasClearance = async () => (await page.context().cookies('https://www.discogs.com')).some(x => x.name === 'cf_clearance');
58
+ // Only an HTML page gets it, without one already, sometimes after its load
59
+ await page.context().clearCookies({ name: 'cf_clearance', domain: '.discogs.com' });
60
+ await page.goto('https://www.discogs.com/shop/list', { waitUntil: 'commit' });
61
+ for (let i = 0; i < 100 && !(await hasClearance()); i++) {
62
+ await page.waitForTimeout(100);
63
+ }
64
+ }
52
65
  /**
53
66
  * Run a GraphQL query of the Discogs shop from the page, which must be on the Discogs origin.
54
67
  * @param page Page
@@ -57,15 +70,30 @@ const CONDITIONS = {
57
70
  * @returns Response
58
71
  */
59
72
  async function queryGraphql(page, operationName, variables) {
60
- const { status, json } = await page.evaluate(async (body) => {
73
+ const run = () => page.evaluate(async (body) => {
61
74
  const res = await fetch('/graphql', {
62
75
  method: 'POST',
63
76
  headers: { 'Content-Type': 'application/json' },
64
77
  body: JSON.stringify(body),
65
78
  });
66
- return { status: res.status, json: (await res.json().catch(() => null)) };
79
+ return {
80
+ status: res.status,
81
+ cfMitigated: res.headers.get('cf-mitigated'),
82
+ cfRay: res.headers.get('cf-ray'),
83
+ json: (await res.json().catch(() => null)),
84
+ };
67
85
  }, { operationName, variables, extensions: { persistedQuery: { version: 1, sha256Hash: HASHES[operationName] } } });
86
+ let response = await run();
87
+ // Without a clearance of Cloudflare, or a refused one (new IP…)
88
+ if (response.cfMitigated) {
89
+ await renewClearance(page);
90
+ response = await run();
91
+ }
92
+ const { status, cfMitigated, cfRay, json } = response;
68
93
  const result = json;
94
+ if (cfMitigated) {
95
+ throw new Error(`An error ${status} occurred: blocked by Cloudflare (${cfMitigated}, cf-ray ${cfRay ?? '?'}).`);
96
+ }
69
97
  if (!result?.data) {
70
98
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
71
99
  throw new Error(result?.errors?.map(x => x.message).join(', ') || `An error ${status} occurred.`);
package/dist/search.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { SearchParams } from './interfaces/search-params.interface.js';
2
2
  import type SearchResult from './interfaces/search-result.interface.js';
3
- import type { Browser } from 'patchright';
3
+ import type { BrowserContext } from 'patchright';
4
4
  /**
5
5
  * Performs a search on the Discogs marketplace using the provided parameters.
6
6
  * @param searchParams - The search parameters, including query, pagination, and filters.
7
- * @param browserInstance - Optional Patchright browser instance. If provided, you must manage its lifecycle.
7
+ * @param browserContext - Optional Patchright browser context, which keeps the clearance of Cloudflare from one search to another.
8
+ * If provided, you must manage its lifecycle.
8
9
  * @returns A promise that resolves to the search results, including items, total, next cursor and the generated URL.
9
10
  */
10
- export default function search(searchParams: SearchParams, browserInstance?: Browser): Promise<SearchResult>;
11
+ export default function search(searchParams: SearchParams, browserContext?: BrowserContext): Promise<SearchResult>;
package/dist/search.js CHANGED
@@ -11,12 +11,13 @@ const MAX_RELEASE_IDS = 2000;
11
11
  /**
12
12
  * Performs a search on the Discogs marketplace using the provided parameters.
13
13
  * @param searchParams - The search parameters, including query, pagination, and filters.
14
- * @param browserInstance - Optional Patchright browser instance. If provided, you must manage its lifecycle.
14
+ * @param browserContext - Optional Patchright browser context, which keeps the clearance of Cloudflare from one search to another.
15
+ * If provided, you must manage its lifecycle.
15
16
  * @returns A promise that resolves to the search results, including items, total, next cursor and the generated URL.
16
17
  */
17
- async function search(searchParams, browserInstance) {
18
+ async function search(searchParams, browserContext) {
18
19
  if ((searchParams.releaseIds?.length ?? 0) > MAX_RELEASE_IDS) {
19
20
  throw new Error(`At most ${MAX_RELEASE_IDS} release IDs are supported.`);
20
21
  }
21
- return (0, browser_context_1.default)(browserInstance, browserContext => (0, marketplace_scraper_1.default)(searchParams, browserContext));
22
+ return (0, browser_context_1.default)(browserContext, x => (0, marketplace_scraper_1.default)(searchParams, x));
22
23
  }
@@ -1,4 +1,4 @@
1
- import type { Browser } from 'patchright';
1
+ import type { BrowserContext } from 'patchright';
2
2
  /**
3
3
  * Options to get the releases of a wantlist: either from the Discogs API, possibly with a token, or only the ones for sale
4
4
  */
@@ -22,7 +22,7 @@ export type WantlistOptions = {
22
22
  * By default, it reads the public Discogs API (limited to 25 requests per minute without token, 60 with).
23
23
  * @param username - Username whose wantlist is read.
24
24
  * @param options - Options.
25
- * @param browserInstance - Optional Patchright browser instance, only used with `onlyForSale`. If provided, you must manage its lifecycle.
25
+ * @param browserContext - Optional Patchright browser context, only used with `onlyForSale`. If provided, you must manage its lifecycle.
26
26
  * @returns A promise that resolves to the release IDs.
27
27
  */
28
- export default function getWantlistReleaseIds(username: string, { token, onlyForSale }?: WantlistOptions, browserInstance?: Browser): Promise<Array<number>>;
28
+ export default function getWantlistReleaseIds(username: string, { token, onlyForSale }?: WantlistOptions, browserContext?: BrowserContext): Promise<Array<number>>;
package/dist/wantlist.js CHANGED
@@ -71,7 +71,11 @@ function scrapeWantlist(username, browserContext) {
71
71
  return { ids: [], pages: 0 };
72
72
  }
73
73
  if (!response?.ok()) {
74
- throw new Error(`An error ${response?.status() ?? '?'} occurred.`);
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.`);
75
79
  }
76
80
  const { total, ids } = await browserPage.evaluate(() => ({
77
81
  total: +(document.querySelector('.pagination_total')?.textContent.split(' of ').pop()?.replace(/,/g, '') ?? '0'),
@@ -90,12 +94,12 @@ function scrapeWantlist(username, browserContext) {
90
94
  * By default, it reads the public Discogs API (limited to 25 requests per minute without token, 60 with).
91
95
  * @param username - Username whose wantlist is read.
92
96
  * @param options - Options.
93
- * @param browserInstance - Optional Patchright browser instance, only used with `onlyForSale`. If provided, you must manage its lifecycle.
97
+ * @param browserContext - Optional Patchright browser context, only used with `onlyForSale`. If provided, you must manage its lifecycle.
94
98
  * @returns A promise that resolves to the release IDs.
95
99
  */
96
- async function getWantlistReleaseIds(username, { token, onlyForSale = false } = {}, browserInstance) {
100
+ async function getWantlistReleaseIds(username, { token, onlyForSale = false } = {}, browserContext) {
97
101
  if (onlyForSale) {
98
- return (0, browser_context_1.default)(browserInstance, browserContext => scrapeWantlist(username, browserContext));
102
+ return (0, browser_context_1.default)(browserContext, x => scrapeWantlist(username, x));
99
103
  }
100
104
  return fetchWantlist(username, token);
101
105
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",