scrapfly-sdk 0.10.4 → 0.10.5

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 (88) hide show
  1. package/esm/browserconfig.d.ts +70 -1
  2. package/esm/browserconfig.d.ts.map +1 -1
  3. package/esm/browserconfig.js +44 -1
  4. package/esm/client.d.ts +33 -0
  5. package/esm/client.d.ts.map +1 -1
  6. package/esm/client.js +33 -5
  7. package/esm/crawl.d.ts +4 -0
  8. package/esm/crawl.d.ts.map +1 -1
  9. package/esm/crawl.js +4 -0
  10. package/esm/crawlerresult.d.ts +7 -0
  11. package/esm/crawlerresult.d.ts.map +1 -1
  12. package/esm/errors.d.ts +43 -0
  13. package/esm/errors.d.ts.map +1 -1
  14. package/esm/errors.js +43 -16
  15. package/esm/extractionconfig.d.ts +54 -9
  16. package/esm/extractionconfig.d.ts.map +1 -1
  17. package/esm/extractionconfig.js +37 -13
  18. package/esm/logger.d.ts +1 -0
  19. package/esm/logger.d.ts.map +1 -1
  20. package/esm/logger.js +1 -0
  21. package/esm/main.d.ts +27 -0
  22. package/esm/main.d.ts.map +1 -1
  23. package/esm/main.js +27 -0
  24. package/esm/monitoringconfig.d.ts +48 -11
  25. package/esm/monitoringconfig.d.ts.map +1 -1
  26. package/esm/monitoringconfig.js +14 -0
  27. package/esm/result.d.ts +2 -0
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/scrapeconfig.d.ts +10 -8
  30. package/esm/scrapeconfig.d.ts.map +1 -1
  31. package/esm/scrapeconfig.js +10 -8
  32. package/esm/screenshotconfig.d.ts +59 -26
  33. package/esm/screenshotconfig.d.ts.map +1 -1
  34. package/esm/screenshotconfig.js +38 -26
  35. package/esm/webhookserver.d.ts +24 -0
  36. package/esm/webhookserver.d.ts.map +1 -1
  37. package/esm/webhookserver.js +24 -0
  38. package/package.json +1 -1
  39. package/script/browserconfig.d.ts +70 -1
  40. package/script/browserconfig.d.ts.map +1 -1
  41. package/script/browserconfig.js +44 -1
  42. package/script/client.d.ts +33 -0
  43. package/script/client.d.ts.map +1 -1
  44. package/script/client.js +33 -5
  45. package/script/crawl.d.ts +4 -0
  46. package/script/crawl.d.ts.map +1 -1
  47. package/script/crawl.js +4 -0
  48. package/script/crawlerresult.d.ts +7 -0
  49. package/script/crawlerresult.d.ts.map +1 -1
  50. package/script/errors.d.ts +43 -0
  51. package/script/errors.d.ts.map +1 -1
  52. package/script/errors.js +43 -16
  53. package/script/extractionconfig.d.ts +54 -9
  54. package/script/extractionconfig.d.ts.map +1 -1
  55. package/script/extractionconfig.js +37 -13
  56. package/script/logger.d.ts +1 -0
  57. package/script/logger.d.ts.map +1 -1
  58. package/script/logger.js +1 -0
  59. package/script/main.d.ts +27 -0
  60. package/script/main.d.ts.map +1 -1
  61. package/script/main.js +27 -0
  62. package/script/monitoringconfig.d.ts +48 -11
  63. package/script/monitoringconfig.d.ts.map +1 -1
  64. package/script/monitoringconfig.js +14 -0
  65. package/script/result.d.ts +2 -0
  66. package/script/result.d.ts.map +1 -1
  67. package/script/scrapeconfig.d.ts +10 -8
  68. package/script/scrapeconfig.d.ts.map +1 -1
  69. package/script/scrapeconfig.js +10 -8
  70. package/script/screenshotconfig.d.ts +59 -26
  71. package/script/screenshotconfig.d.ts.map +1 -1
  72. package/script/screenshotconfig.js +38 -26
  73. package/script/webhookserver.d.ts +24 -0
  74. package/script/webhookserver.d.ts.map +1 -1
  75. package/script/webhookserver.js +24 -0
  76. package/src/browserconfig.ts +70 -1
  77. package/src/client.ts +34 -6
  78. package/src/crawl.ts +4 -0
  79. package/src/crawlerresult.ts +7 -0
  80. package/src/errors.ts +43 -16
  81. package/src/extractionconfig.ts +58 -16
  82. package/src/logger.ts +2 -0
  83. package/src/main.ts +27 -0
  84. package/src/monitoringconfig.ts +49 -11
  85. package/src/result.ts +2 -0
  86. package/src/scrapeconfig.ts +10 -8
  87. package/src/screenshotconfig.ts +59 -26
  88. package/src/webhookserver.ts +24 -0
@@ -1,61 +1,124 @@
1
+ /** Proxy pool to use for the Cloud Browser session. */
1
2
  export enum ProxyPool {
3
+ /** Datacenter proxies — fast and cheap; best for non-protected targets. */
2
4
  DATACENTER = 'datacenter',
5
+ /** Residential proxies — real ISP IPs; required by most anti-bot protections. */
3
6
  RESIDENTIAL = 'residential',
4
7
  }
5
8
 
9
+ /** Operating system to emulate for the Cloud Browser session fingerprint. */
6
10
  export enum OperatingSystem {
11
+ /** Emulate a Linux browser fingerprint. */
7
12
  LINUX = 'linux',
13
+ /** Emulate a Windows browser fingerprint. */
8
14
  WINDOWS = 'windows',
15
+ /** Emulate a macOS browser fingerprint. */
9
16
  MACOS = 'macos',
10
17
  }
11
18
 
19
+ /**
20
+ * User-facing options accepted by {@link BrowserConfig}. All fields are
21
+ * optional; any field left undefined falls back to the Scrapfly Cloud
22
+ * Browser defaults.
23
+ */
12
24
  export type BrowserConfigOptions = {
25
+ /** Proxy pool to route the session through. */
13
26
  proxy_pool?: ProxyPool | string;
27
+ /** Operating system fingerprint to emulate. */
14
28
  os?: OperatingSystem | string;
29
+ /** Session ID for sticky sessions (IP + cookies reused across scrapes). */
15
30
  session?: string;
31
+ /** ISO country code for geo-targeting. */
16
32
  country?: string;
33
+ /** Close the browser automatically when the connection drops. */
17
34
  auto_close?: boolean;
35
+ /** Session timeout in seconds (max 1800 = 30 minutes). */
18
36
  timeout?: number;
37
+ /** Enable debug trace for the session. */
19
38
  debug?: boolean;
39
+ /** Browser extensions to load (by ID). */
20
40
  extensions?: string[];
41
+ /** Block image requests to speed up navigation. */
21
42
  block_images?: boolean;
43
+ /** Block stylesheet requests. */
22
44
  block_styles?: boolean;
45
+ /** Block font requests. */
23
46
  block_fonts?: boolean;
47
+ /** Block media (video/audio) requests. */
24
48
  block_media?: boolean;
49
+ /** Capture a screenshot at session end. */
25
50
  screenshot?: boolean;
51
+ /** Viewport resolution, formatted as "widthxheight" (e.g. "1920x1080"). */
26
52
  resolution?: string;
53
+ /** URL to navigate to after session start. */
27
54
  target_url?: string;
55
+ /** Reuse cached responses where possible. */
28
56
  cache?: boolean;
57
+ /** Apply Scrapfly's abuse blacklist. */
29
58
  blacklist?: boolean;
59
+ /** Enable anti-scraping-protection bypass. */
30
60
  unblock?: boolean;
61
+ /** Timeout in seconds for the unblock step. */
31
62
  unblock_timeout?: number;
63
+ /** Browser brand to emulate (e.g. "chrome", "firefox"). */
32
64
  browser_brand?: string;
65
+ /** Enable the MCP (Model Context Protocol) bridge. */
33
66
  enable_mcp?: boolean;
34
67
  };
35
68
 
69
+ /**
70
+ * Configuration for a Scrapfly Cloud Browser session. Builds the
71
+ * WebSocket URL that clients such as Puppeteer or Playwright can
72
+ * connect to via CDP.
73
+ */
36
74
  export class BrowserConfig {
75
+ /** See {@link BrowserConfigOptions.proxy_pool}. */
37
76
  proxy_pool?: string;
77
+ /** See {@link BrowserConfigOptions.os}. */
38
78
  os?: string;
79
+ /** See {@link BrowserConfigOptions.session}. */
39
80
  session?: string;
81
+ /** See {@link BrowserConfigOptions.country}. */
40
82
  country?: string;
83
+ /** See {@link BrowserConfigOptions.auto_close}. */
41
84
  auto_close?: boolean;
85
+ /** See {@link BrowserConfigOptions.timeout}. */
42
86
  timeout?: number;
87
+ /** See {@link BrowserConfigOptions.debug}. */
43
88
  debug?: boolean;
89
+ /** See {@link BrowserConfigOptions.extensions}. */
44
90
  extensions?: string[];
91
+ /** See {@link BrowserConfigOptions.block_images}. */
45
92
  block_images?: boolean;
93
+ /** See {@link BrowserConfigOptions.block_styles}. */
46
94
  block_styles?: boolean;
95
+ /** See {@link BrowserConfigOptions.block_fonts}. */
47
96
  block_fonts?: boolean;
97
+ /** See {@link BrowserConfigOptions.block_media}. */
48
98
  block_media?: boolean;
99
+ /** See {@link BrowserConfigOptions.screenshot}. */
49
100
  screenshot?: boolean;
101
+ /** See {@link BrowserConfigOptions.resolution}. */
50
102
  resolution?: string;
103
+ /** See {@link BrowserConfigOptions.target_url}. */
51
104
  target_url?: string;
105
+ /** See {@link BrowserConfigOptions.cache}. */
52
106
  cache?: boolean;
107
+ /** See {@link BrowserConfigOptions.blacklist}. */
53
108
  blacklist?: boolean;
109
+ /** See {@link BrowserConfigOptions.unblock}. */
54
110
  unblock?: boolean;
111
+ /** See {@link BrowserConfigOptions.unblock_timeout}. */
55
112
  unblock_timeout?: number;
113
+ /** See {@link BrowserConfigOptions.browser_brand}. */
56
114
  browser_brand?: string;
115
+ /** See {@link BrowserConfigOptions.enable_mcp}. */
57
116
  enable_mcp?: boolean;
58
117
 
118
+ /**
119
+ * @param options Session options. See {@link BrowserConfigOptions}.
120
+ * @throws `Error` if `timeout` exceeds the upper bound of 1800 seconds.
121
+ */
59
122
  constructor(options: BrowserConfigOptions = {}) {
60
123
  if (options.timeout !== undefined && options.timeout > 1800) {
61
124
  throw new Error('timeout cannot exceed 1800 seconds (30 minutes)');
@@ -84,7 +147,13 @@ export class BrowserConfig {
84
147
  }
85
148
 
86
149
  /**
87
- * Generate the WebSocket URL for a Cloud Browser session.
150
+ * Build the WebSocket URL clients use to connect to the Cloud Browser
151
+ * session (compatible with Puppeteer `browserWSEndpoint` and the
152
+ * Playwright `connectOverCDP` API).
153
+ *
154
+ * @param apiKey Scrapfly API key.
155
+ * @param host Optional override for the Cloud Browser host (defaults to `wss://browser.scrapfly.io`).
156
+ * @returns A fully-qualified `wss://…` URL with all options encoded as query parameters.
88
157
  */
89
158
  websocketUrl(apiKey: string, host?: string): string {
90
159
  const params = new URLSearchParams();
package/src/client.ts CHANGED
@@ -18,16 +18,35 @@ import {
18
18
  type MonitoringTargetMetricsOptions,
19
19
  } from './monitoringconfig.js';
20
20
 
21
+ /**
22
+ * Main entry point for the Scrapfly SDK.
23
+ *
24
+ * A single `ScrapflyClient` can be used to call every Scrapfly API
25
+ * (scrape, screenshot, extraction, crawler, monitoring, cloud browser).
26
+ * It is safe to share one instance across concurrent calls.
27
+ */
21
28
  export class ScrapflyClient {
29
+ /** Base URL of the Scrapfly REST API. */
22
30
  public HOST = 'https://api.scrapfly.io';
31
+ /** Default Cloud Browser WebSocket host. */
23
32
  public CLOUD_BROWSER_HOST = 'wss://browser.scrapfly.io';
33
+ /** Default Cloud Browser REST host (derived from the WS host). */
24
34
  public CLOUD_BROWSER_API_HOST = 'https://browser.scrapfly.io';
25
35
  private key: string;
26
36
  private ua: string;
27
37
  private cloudBrowserHost: string;
28
38
  private cloudBrowserApiHost: string;
29
- fetch = fetchRetry;
39
+ /** `fetch` implementation used by the client. Override for custom retries/tracing. */
40
+ fetch: typeof fetchRetry = fetchRetry;
30
41
 
42
+ /**
43
+ * Create a Scrapfly client.
44
+ *
45
+ * @param options.key Scrapfly API key.
46
+ * @param options.host Optional override for the REST API host.
47
+ * @param options.cloudBrowserHost Optional override for the Cloud Browser WS host.
48
+ * @throws {@link errors.BadApiKeyError} if `options.key` is not a non-empty string.
49
+ */
31
50
  constructor(options: { key: string; host?: string; cloudBrowserHost?: string }) {
32
51
  if (typeof options.key !== 'string' || options.key.trim() === '') {
33
52
  throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
@@ -284,6 +303,7 @@ export class ScrapflyClient {
284
303
  // Cloud Browser is session-based and exposes a distinct shape.
285
304
  // See https://scrapfly.io/docs/monitoring#api
286
305
 
306
+ /** Dispatch an HTTP GET against a Monitoring API path with the given query params, parsing errors. */
287
307
  private async monitoringRequest(path: string, params: Rec<string>): Promise<Rec<any>> {
288
308
  const url = new URL(this.HOST + path);
289
309
  url.search = new URLSearchParams(params).toString();
@@ -306,6 +326,7 @@ export class ScrapflyClient {
306
326
  return data;
307
327
  }
308
328
 
329
+ /** Build the query string for a request-based Monitoring API metrics endpoint. */
309
330
  private buildMetricsParams(options: MonitoringMetricsOptions): Rec<string> {
310
331
  const params: Rec<string> = {
311
332
  key: this.key,
@@ -319,6 +340,7 @@ export class ScrapflyClient {
319
340
  return params;
320
341
  }
321
342
 
343
+ /** Build the query string for a per-target Monitoring API endpoint. */
322
344
  private buildTargetParams(options: MonitoringTargetMetricsOptions): Rec<string> {
323
345
  if ((options.start && !options.end) || (!options.start && options.end)) {
324
346
  throw new Error('You must provide both start and end date');
@@ -340,55 +362,61 @@ export class ScrapflyClient {
340
362
  return params;
341
363
  }
342
364
 
343
- // ── Web Scraping API (existing — kept for backward compat) ──────
365
+ /** Fetch Web Scraping API monitoring metrics (aggregate). */
344
366
  async getMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
345
367
  return this.monitoringRequest('/scrape/monitoring/metrics', this.buildMetricsParams(options));
346
368
  }
347
369
 
370
+ /** Fetch Web Scraping API monitoring metrics for a single target domain. */
348
371
  async getMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
349
372
  return this.monitoringRequest('/scrape/monitoring/metrics/target', this.buildTargetParams(options));
350
373
  }
351
374
 
352
- // ── Screenshot API ───────────────────────────────────────────────
375
+ /** Fetch Screenshot API monitoring metrics (aggregate). */
353
376
  async getScreenshotMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
354
377
  return this.monitoringRequest('/screenshot/monitoring/metrics', this.buildMetricsParams(options));
355
378
  }
356
379
 
380
+ /** Fetch Screenshot API monitoring metrics for a single target domain. */
357
381
  async getScreenshotMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
358
382
  return this.monitoringRequest('/screenshot/monitoring/metrics/target', this.buildTargetParams(options));
359
383
  }
360
384
 
361
- // ── Extraction API ───────────────────────────────────────────────
385
+ /** Fetch Extraction API monitoring metrics (aggregate). */
362
386
  async getExtractionMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
363
387
  return this.monitoringRequest('/extraction/monitoring/metrics', this.buildMetricsParams(options));
364
388
  }
365
389
 
390
+ /** Fetch Extraction API monitoring metrics for a single target domain. */
366
391
  async getExtractionMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
367
392
  return this.monitoringRequest('/extraction/monitoring/metrics/target', this.buildTargetParams(options));
368
393
  }
369
394
 
370
- // ── Crawler API ──────────────────────────────────────────────────
395
+ /** Fetch Crawler API monitoring metrics (aggregate). */
371
396
  async getCrawlerMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
372
397
  return this.monitoringRequest('/crawl/monitoring/metrics', this.buildMetricsParams(options));
373
398
  }
374
399
 
400
+ /** Fetch Crawler API monitoring metrics for a single target domain. */
375
401
  async getCrawlerMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
376
402
  return this.monitoringRequest('/crawl/monitoring/metrics/target', this.buildTargetParams(options));
377
403
  }
378
404
 
379
- // ── Cloud Browser API (session-based, distinct shape) ────────────
405
+ /** Fetch Cloud Browser monitoring metrics (session-based aggregate). */
380
406
  async getBrowserMonitoringMetrics(
381
407
  options: CloudBrowserMonitoringOptions = {},
382
408
  ): Promise<Rec<any>> {
383
409
  return this.monitoringRequest('/browser/monitoring/metrics', this.buildBrowserParams(options));
384
410
  }
385
411
 
412
+ /** Fetch Cloud Browser monitoring timeseries (per-minute session usage). */
386
413
  async getBrowserMonitoringTimeseries(
387
414
  options: CloudBrowserMonitoringOptions = {},
388
415
  ): Promise<Rec<any>> {
389
416
  return this.monitoringRequest('/browser/monitoring/metrics/timeseries', this.buildBrowserParams(options));
390
417
  }
391
418
 
419
+ /** Build the query string for the session-based Cloud Browser Monitoring endpoints. */
392
420
  private buildBrowserParams(options: CloudBrowserMonitoringOptions): Rec<string> {
393
421
  if ((options.start && !options.end) || (!options.start && options.end)) {
394
422
  throw new Error('You must provide both start and end date');
package/src/crawl.ts CHANGED
@@ -46,6 +46,10 @@ export class Crawl {
46
46
  private _status?: CrawlerStatus;
47
47
  private readonly _artifactCache: Map<CrawlerArtifactType, CrawlerArtifact> = new Map();
48
48
 
49
+ /**
50
+ * @param client Configured {@link ScrapflyClient} that performs the HTTP calls.
51
+ * @param config Crawler configuration to submit on {@link Crawl.start}.
52
+ */
49
53
  constructor(private readonly client: ScrapflyClient, private readonly config: CrawlerConfig) {}
50
54
 
51
55
  /** The crawler UUID returned by the API after `start()`, or undefined before. */
@@ -82,12 +82,19 @@ export type CrawlerStopReason =
82
82
  * `duration` is always a number (0 when nothing has happened yet).
83
83
  */
84
84
  export interface CrawlerState {
85
+ /** Number of URLs the crawler has fetched. */
85
86
  urls_visited: number;
87
+ /** Number of URLs from which content or links were extracted. */
86
88
  urls_extracted: number;
89
+ /** Number of URLs that failed to fetch. */
87
90
  urls_failed: number;
91
+ /** Number of URLs skipped (filtered out, duplicate, limit hit, ...). */
88
92
  urls_skipped: number;
93
+ /** Number of URLs queued for future fetch. */
89
94
  urls_to_crawl: number;
95
+ /** API credits consumed so far. */
90
96
  api_credit_used: number;
97
+ /** Elapsed time in seconds since the crawl started (0 while PENDING). */
91
98
  duration: number;
92
99
  /** `null` until the crawler stops. */
93
100
  stop_reason: CrawlerStopReason | null;
package/src/errors.ts CHANGED
@@ -1,55 +1,82 @@
1
+ /**
2
+ * Base class for every error thrown by the Scrapfly SDK.
3
+ *
4
+ * Concrete subclasses distinguish config-level, HTTP-level, and
5
+ * API-specific failures so callers can catch the exact category they
6
+ * care about without string-matching on error messages.
7
+ */
1
8
  export class ScrapflyError extends Error {
9
+ /** Extra context carried alongside the error message (response body, request params, etc.). */
2
10
  args: Record<string, any>;
3
11
 
12
+ /**
13
+ * @param message Human-readable description of the failure.
14
+ * @param args Optional structured context to attach to the error.
15
+ */
4
16
  constructor(message: string, args: Record<string, any> = {}) {
5
17
  super(message);
6
18
  this.args = args;
7
19
  }
8
20
  }
9
21
 
10
- // raised when scrape config is invalid
22
+ /** Raised when a ScrapeConfig is constructed with invalid parameters. */
11
23
  export class ScrapeConfigError extends ScrapflyError {}
12
- // raised when screenshot config is invalid
24
+ /** Raised when a ScreenshotConfig is constructed with invalid parameters. */
13
25
  export class ScreenshotConfigError extends ScrapflyError {}
14
- // raised when extraction config is invalid
26
+ /** Raised when an ExtractionConfig is constructed with invalid parameters. */
15
27
  export class ExtractionConfigError extends ScrapflyError {}
16
- // raised when crawler config is invalid
28
+ /** Raised when a CrawlerConfig is constructed with invalid parameters. */
17
29
  export class CrawlerConfigError extends ScrapflyError {}
18
30
 
19
- // raised when scrape parameters cannot be encoded
31
+ /** Raised when scrape parameters cannot be encoded into a request. */
20
32
  export class EncodeError extends ScrapflyError {}
33
+ /** Raised when a response carries an unexpected or unsupported Content-Type. */
21
34
  export class ContentTypeError extends ScrapflyError {}
22
35
 
23
- // Base error for all http related operations
36
+ /** Base error for every HTTP-level failure surfaced by the SDK. */
24
37
  export class HttpError extends ScrapflyError {}
38
+ /** Raised when the upstream target returned an error to Scrapfly. */
25
39
  export class UpstreamHttpError extends HttpError {}
40
+ /** Raised when the upstream target returned a 4xx client error. */
26
41
  export class UpstreamHttpClientError extends UpstreamHttpError {}
42
+ /** Raised when the upstream target returned a 5xx server error. */
27
43
  export class UpstreamHttpServerError extends UpstreamHttpClientError {}
28
44
 
45
+ /** Raised when the Scrapfly API itself returned a 4xx client error. */
29
46
  export class ApiHttpClientError extends HttpError {}
30
- // raised when API key provided to client is not valid or not existant
47
+ /** Raised when the API key provided to the client is missing, invalid, or revoked. */
31
48
  export class BadApiKeyError extends ApiHttpClientError {}
32
49
 
50
+ /** Raised when the request is rate-limited (HTTP 429). */
33
51
  export class TooManyRequests extends HttpError {}
52
+ /** Raised when the Scrapfly API returned a 5xx server error. */
34
53
  export class ApiHttpServerError extends HttpError {}
54
+ /** Raised when a scrape call fails for a reason not captured by a more specific subclass. */
35
55
  export class ScrapflyScrapeError extends HttpError {}
36
- // raised when proxy settings don't match available proxies (e.g. invalid proxy pool, country setting)
56
+ /** Raised when proxy settings do not match an available proxy (invalid pool, unsupported country, ...). */
37
57
  export class ScrapflyProxyError extends HttpError {}
58
+ /** Raised when the request is throttled by Scrapfly (e.g. burst limits). */
38
59
  export class ScrapflyThrottleError extends HttpError {}
39
- // raised when ScrapFly fails to bypass anti-scraping protection
60
+ /** Raised when Scrapfly failed to bypass anti-scraping protection on the target. */
40
61
  export class ScrapflyAspError extends HttpError {}
62
+ /** Raised when a scheduled scrape cannot be created or fulfilled. */
41
63
  export class ScrapflyScheduleError extends HttpError {}
42
- // raised when Webhook is invalid or cannot be fulfilled (i.e. full queue)
64
+ /** Raised when a webhook is invalid or cannot be delivered (e.g. full queue). */
43
65
  export class ScrapflyWebhookError extends HttpError {}
44
- // raised when session is access concurrently
66
+ /** Raised when a session is accessed concurrently in a way that violates session semantics. */
45
67
  export class ScrapflySessionError extends HttpError {}
46
- // raised when concurrent requests exceed account limits
68
+ /** Raised when concurrent requests exceed the account's concurrency limit. */
47
69
  export class TooManyConcurrentRequests extends HttpError {}
48
- // raised when account is out of scrape credits
70
+ /** Raised when the account is out of scrape credits. */
49
71
  export class QuotaLimitReached extends HttpError {}
50
- // raised with Scrapfly screenshot API related errors
72
+ /** Raised for screenshot-API-specific failures. */
51
73
  export class ScreenshotApiError extends ApiHttpClientError {}
52
- // raised with Scrapfly extraction API related errors
74
+ /** Raised for extraction-API-specific failures. */
53
75
  export class ExtractionApiError extends ApiHttpClientError {}
54
- // raised with Scrapfly crawler API related errors (job lifecycle: ALREADY_STARTED, NOT_STARTED, FAILED, CANCELLED, TIMEOUT, etc.)
76
+ /**
77
+ * Raised for crawler-API-specific failures.
78
+ *
79
+ * Covers crawler job lifecycle errors such as ALREADY_STARTED,
80
+ * NOT_STARTED, FAILED, CANCELLED, TIMEOUT, etc.
81
+ */
55
82
  export class ScrapflyCrawlerError extends HttpError {}
@@ -2,58 +2,93 @@ import * as errors from './errors.js';
2
2
  import { urlsafe_b64encode } from './utils.js';
3
3
  import { ExtractionConfigError } from './errors.js';
4
4
 
5
+ /** Compression format declared for documents submitted to the Extraction API. */
5
6
  export enum CompressionFormat {
6
- /**
7
- Document compression format.
8
-
9
- Attributes:
10
- GZIP: gzip format.
11
- ZSTD: zstd format.
12
- DEFLATE: deflate.
13
- """
14
- */
7
+ /** gzip compression. */
15
8
  GZIP = 'gzip',
9
+ /** zstd compression. */
16
10
  ZSTD = 'zstd',
11
+ /** DEFLATE compression. */
17
12
  DEFLATE = 'deflate',
18
13
  }
19
14
 
15
+ /**
16
+ * User-facing options accepted by {@link ExtractionConfig}. See the
17
+ * [Extraction API reference](https://scrapfly.io/docs/extraction-api)
18
+ * for the authoritative list of valid values.
19
+ */
20
20
  type ExtractionConfigOptions = {
21
+ /** Document body to extract from. */
21
22
  body: string;
23
+ /** Content-Type of the body (e.g. "text/html"). */
22
24
  content_type: string;
25
+ /** URL associated with the document (used for link resolution). */
23
26
  url?: string;
27
+ /** Character set of the document. */
24
28
  charset?: string;
25
- extraction_template?: string; // saved template name
26
- extraction_ephemeral_template?: object; // ephemeraly declared json template
29
+ /** Name of a saved extraction template. */
30
+ extraction_template?: string;
31
+ /** Inline extraction template, used instead of a saved one. */
32
+ extraction_ephemeral_template?: object;
33
+ /** Natural-language prompt for LLM-based extraction. */
27
34
  extraction_prompt?: string;
35
+ /** Override the LLM model used for prompt-based extraction. */
28
36
  extraction_model?: string;
37
+ /** Whether the provided body is already compressed. */
29
38
  is_document_compressed?: boolean;
39
+ /** Compression format of the body. See {@link CompressionFormat}. */
30
40
  document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
41
+ /** Webhook name to notify when extraction completes. */
31
42
  webhook?: string;
43
+ /** Request timeout in milliseconds. */
32
44
  timeout?: number;
33
45
 
34
- // deprecated options
46
+ /** @deprecated Use {@link extraction_template} instead. */
35
47
  template?: string;
48
+ /** @deprecated Use {@link extraction_ephemeral_template} instead. */
36
49
  ephemeral_template?: object;
37
50
  };
38
51
 
52
+ /**
53
+ * Configuration for an Extraction API call. Holds the document to
54
+ * extract from and the template/prompt/model that should drive the
55
+ * extraction.
56
+ */
39
57
  export class ExtractionConfig {
58
+ /** Document body. */
40
59
  body: string | Uint8Array;
60
+ /** Content-Type of the body. */
41
61
  content_type: string;
62
+ /** URL associated with the document. */
42
63
  url?: string;
64
+ /** Character set of the document. */
43
65
  charset?: string;
44
- extraction_template?: string; // saved template name
45
- extraction_ephemeral_template?: object; // ephemeraly declared json template
66
+ /** Saved extraction template name. */
67
+ extraction_template?: string;
68
+ /** Inline extraction template. */
69
+ extraction_ephemeral_template?: object;
70
+ /** Natural-language extraction prompt. */
46
71
  extraction_prompt?: string;
72
+ /** LLM model override for prompt-based extraction. */
47
73
  extraction_model?: string;
74
+ /** Whether the body is pre-compressed. */
48
75
  is_document_compressed?: boolean;
76
+ /** Compression format of the body. */
49
77
  document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
78
+ /** Webhook name to notify on completion. */
50
79
  webhook?: string;
80
+ /** Request timeout in milliseconds. */
51
81
  timeout?: number;
52
82
 
53
- // // deprecated options
83
+ /** @deprecated Use {@link extraction_template} instead. */
54
84
  template?: string;
85
+ /** @deprecated Use {@link extraction_ephemeral_template} instead. */
55
86
  ephemeral_template?: object;
56
87
 
88
+ /**
89
+ * @param options See {@link ExtractionConfigOptions}.
90
+ * @throws {@link errors.ExtractionConfigError} if an unknown option is supplied.
91
+ */
57
92
  constructor(options: ExtractionConfigOptions) {
58
93
  this.validateOptions(options);
59
94
  if (options.template) {
@@ -104,11 +139,18 @@ export class ExtractionConfig {
104
139
  }
105
140
  }
106
141
 
142
+ /**
143
+ * Encode this config as the query-string parameters sent to the
144
+ * Extraction API.
145
+ *
146
+ * @param options.key Scrapfly API key.
147
+ * @returns A record suitable for `URLSearchParams` construction.
148
+ * @throws {@link ExtractionConfigError} on conflicting or incompatible options.
149
+ */
107
150
  toApiParams(options: { key: string }): Record<string, any> {
108
151
  const params: Record<string, any> = {
109
152
  key: options.key,
110
153
  };
111
- // params.body = this.body;
112
154
  params.content_type = this.content_type;
113
155
 
114
156
  if (this.url) {
package/src/logger.ts CHANGED
@@ -48,4 +48,6 @@ class Logger {
48
48
  }
49
49
 
50
50
  export default Logger;
51
+
52
+ /** Shared logger instance used by the SDK. Callers can set its log level to silence or unmute output. */
51
53
  export const log: Logger = new Logger('scrapfly');
package/src/main.ts CHANGED
@@ -1,3 +1,29 @@
1
+ /**
2
+ * # Scrapfly SDK for TypeScript / JavaScript
3
+ *
4
+ * Official client library for the [Scrapfly](https://scrapfly.io) web
5
+ * scraping API. Provides typed wrappers around the Scrape, Screenshot,
6
+ * Extraction, Crawler, Monitoring, and Cloud Browser APIs.
7
+ *
8
+ * ## Quick start
9
+ *
10
+ * ```ts
11
+ * import { ScrapflyClient, ScrapeConfig } from '@scrapfly/scrapfly-sdk';
12
+ *
13
+ * const client = new ScrapflyClient({ key: 'your-api-key' });
14
+ * const result = await client.scrape(new ScrapeConfig({
15
+ * url: 'https://web-scraping.dev/products',
16
+ * render_js: true,
17
+ * asp: true,
18
+ * }));
19
+ * console.log(result.content);
20
+ * ```
21
+ *
22
+ * See the [Scrapfly docs](https://scrapfly.io/docs) for the full API
23
+ * reference.
24
+ *
25
+ * @module
26
+ */
1
27
  export { ScrapflyClient } from './client.js';
2
28
  export {
3
29
  Format as ScrapeFormat,
@@ -14,6 +40,7 @@ export {
14
40
  export { ExtractionConfig } from './extractionconfig.js';
15
41
  export { BrowserConfig, ProxyPool, OperatingSystem } from './browserconfig.js';
16
42
  export type { BrowserConfigOptions } from './browserconfig.js';
43
+ /** Namespace of every error class the SDK can throw. See {@link ScrapflyError}. */
17
44
  export * as errors from './errors.js';
18
45
 
19
46
  export { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';