scrapfly-sdk 0.7.3 → 0.10.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.
Files changed (75) hide show
  1. package/esm/browserconfig.d.ts +59 -0
  2. package/esm/browserconfig.d.ts.map +1 -0
  3. package/esm/browserconfig.js +207 -0
  4. package/esm/client.d.ts +209 -1
  5. package/esm/client.d.ts.map +1 -1
  6. package/esm/client.js +902 -5
  7. package/esm/crawl.d.ts +118 -0
  8. package/esm/crawl.d.ts.map +1 -0
  9. package/esm/crawl.js +230 -0
  10. package/esm/crawlerconfig.d.ts +119 -0
  11. package/esm/crawlerconfig.d.ts.map +1 -0
  12. package/esm/crawlerconfig.js +398 -0
  13. package/esm/crawlerresult.d.ts +253 -0
  14. package/esm/crawlerresult.d.ts.map +1 -0
  15. package/esm/crawlerresult.js +327 -0
  16. package/esm/errors.d.ts +4 -0
  17. package/esm/errors.d.ts.map +1 -1
  18. package/esm/errors.js +6 -0
  19. package/esm/extractionconfig.d.ts +2 -0
  20. package/esm/extractionconfig.d.ts.map +1 -1
  21. package/esm/extractionconfig.js +10 -0
  22. package/esm/main.d.ts +9 -1
  23. package/esm/main.d.ts.map +1 -1
  24. package/esm/main.js +6 -1
  25. package/esm/monitoringconfig.d.ts +36 -0
  26. package/esm/monitoringconfig.d.ts.map +1 -0
  27. package/esm/monitoringconfig.js +10 -0
  28. package/esm/polyfill.d.ts +2 -0
  29. package/esm/polyfill.d.ts.map +1 -1
  30. package/esm/polyfill.js +12 -0
  31. package/esm/scrapeconfig.d.ts +27 -0
  32. package/esm/scrapeconfig.d.ts.map +1 -1
  33. package/esm/scrapeconfig.js +44 -1
  34. package/esm/screenshotconfig.d.ts +2 -2
  35. package/esm/screenshotconfig.d.ts.map +1 -1
  36. package/esm/utils.d.ts.map +1 -1
  37. package/esm/utils.js +16 -2
  38. package/package.json +1 -1
  39. package/script/browserconfig.d.ts +59 -0
  40. package/script/browserconfig.d.ts.map +1 -0
  41. package/script/browserconfig.js +211 -0
  42. package/script/client.d.ts +209 -1
  43. package/script/client.d.ts.map +1 -1
  44. package/script/client.js +901 -4
  45. package/script/crawl.d.ts +118 -0
  46. package/script/crawl.d.ts.map +1 -0
  47. package/script/crawl.js +257 -0
  48. package/script/crawlerconfig.d.ts +119 -0
  49. package/script/crawlerconfig.d.ts.map +1 -0
  50. package/script/crawlerconfig.js +402 -0
  51. package/script/crawlerresult.d.ts +253 -0
  52. package/script/crawlerresult.d.ts.map +1 -0
  53. package/script/crawlerresult.js +335 -0
  54. package/script/errors.d.ts +4 -0
  55. package/script/errors.d.ts.map +1 -1
  56. package/script/errors.js +9 -1
  57. package/script/extractionconfig.d.ts +2 -0
  58. package/script/extractionconfig.d.ts.map +1 -1
  59. package/script/extractionconfig.js +10 -0
  60. package/script/main.d.ts +9 -1
  61. package/script/main.d.ts.map +1 -1
  62. package/script/main.js +17 -1
  63. package/script/monitoringconfig.d.ts +36 -0
  64. package/script/monitoringconfig.d.ts.map +1 -0
  65. package/script/monitoringconfig.js +13 -0
  66. package/script/polyfill.d.ts +2 -0
  67. package/script/polyfill.d.ts.map +1 -1
  68. package/script/polyfill.js +14 -1
  69. package/script/scrapeconfig.d.ts +27 -0
  70. package/script/scrapeconfig.d.ts.map +1 -1
  71. package/script/scrapeconfig.js +44 -1
  72. package/script/screenshotconfig.d.ts +2 -2
  73. package/script/screenshotconfig.d.ts.map +1 -1
  74. package/script/utils.d.ts.map +1 -1
  75. package/script/utils.js +16 -2
package/esm/client.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { path } from './deps.js';
2
- import { mkdir, writeFile } from './polyfill.js';
2
+ import { mkdir, writeFile, readFileSync } from './polyfill.js';
3
3
  import { fetchRetry } from './utils.js';
4
4
  import * as errors from './errors.js';
5
+ import { BrowserConfig } from './browserconfig.js';
5
6
  import { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
6
7
  import { log } from './logger.js';
8
+ import { CrawlerArtifact, CrawlerContents, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
9
+ import { formatMonitoringDate, } from './monitoringconfig.js';
7
10
  export class ScrapflyClient {
8
11
  constructor(options) {
9
12
  Object.defineProperty(this, "HOST", {
@@ -12,6 +15,18 @@ export class ScrapflyClient {
12
15
  writable: true,
13
16
  value: 'https://api.scrapfly.io'
14
17
  });
18
+ Object.defineProperty(this, "CLOUD_BROWSER_HOST", {
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: true,
22
+ value: 'wss://browser.scrapfly.io'
23
+ });
24
+ Object.defineProperty(this, "CLOUD_BROWSER_API_HOST", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: 'https://browser.scrapfly.io'
29
+ });
15
30
  Object.defineProperty(this, "key", {
16
31
  enumerable: true,
17
32
  configurable: true,
@@ -24,6 +39,18 @@ export class ScrapflyClient {
24
39
  writable: true,
25
40
  value: void 0
26
41
  });
42
+ Object.defineProperty(this, "cloudBrowserHost", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ Object.defineProperty(this, "cloudBrowserApiHost", {
49
+ enumerable: true,
50
+ configurable: true,
51
+ writable: true,
52
+ value: void 0
53
+ });
27
54
  Object.defineProperty(this, "fetch", {
28
55
  enumerable: true,
29
56
  configurable: true,
@@ -34,7 +61,15 @@ export class ScrapflyClient {
34
61
  throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
35
62
  }
36
63
  this.key = options.key;
64
+ if (options.host) {
65
+ // Trim trailing slash so callers can pass either form
66
+ this.HOST = options.host.replace(/\/+$/, '');
67
+ }
37
68
  this.ua = 'Typescript Scrapfly SDK';
69
+ this.cloudBrowserHost = options.cloudBrowserHost || this.CLOUD_BROWSER_HOST;
70
+ this.cloudBrowserApiHost = options.cloudBrowserHost
71
+ ? options.cloudBrowserHost.replace('wss://', 'https://')
72
+ : this.CLOUD_BROWSER_API_HOST;
38
73
  }
39
74
  /**
40
75
  * Raise appropriate error for given response and scrape result
@@ -42,12 +77,18 @@ export class ScrapflyClient {
42
77
  errResult(response, result) {
43
78
  const error = result.result.error;
44
79
  const message = error?.message ?? '';
80
+ // When success=false the authoritative error code lives in result.result.error.code
81
+ // (e.g. "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE"). result.result.status is only "DONE"
82
+ // or a job-level error and does not carry the upstream-failure code.
83
+ const effectiveCode = (result.result.success === false && error?.code)
84
+ ? error.code
85
+ : result.result.status;
45
86
  const args = {
46
- code: result.result.status,
87
+ code: effectiveCode,
47
88
  http_status_code: result.result.status_code,
48
89
  is_retryable: error?.retryable ?? false,
49
90
  api_response: result,
50
- resource: result.result.status ? result.result.status.split('::')[1] : null,
91
+ resource: effectiveCode ? effectiveCode.split('::')[1] : null,
51
92
  retry_delay: error?.retryable ? 5 : response.headers.get('X-Retry') ?? 5,
52
93
  retry_times: 3,
53
94
  documentation_url: error?.doc_url ?? 'https://scrapfly.io/docs/scrape-api/errors#api',
@@ -74,6 +115,8 @@ export class ScrapflyClient {
74
115
  return new errors.ScrapflyAspError(message, args);
75
116
  case 'SESSION':
76
117
  return new errors.ScrapflySessionError(message, args);
118
+ case 'CRAWLER':
119
+ return new errors.ScrapflyCrawlerError(message, args);
77
120
  }
78
121
  if (args.resource) {
79
122
  return new errors.ApiHttpClientError(message, args);
@@ -101,6 +144,8 @@ export class ScrapflyClient {
101
144
  return new errors.ScrapflyAspError(message, args);
102
145
  case 'SESSION':
103
146
  return new errors.ScrapflySessionError(message, args);
147
+ case 'CRAWLER':
148
+ return new errors.ScrapflyCrawlerError(message, args);
104
149
  }
105
150
  }
106
151
  return new errors.ScrapflyError(message, args);
@@ -185,6 +230,121 @@ export class ScrapflyClient {
185
230
  }
186
231
  return data;
187
232
  }
233
+ // ── Monitoring API (Enterprise+ plan only) ──────────────────────
234
+ // The Monitoring API exposes per-product aggregates and per-target
235
+ // timeseries. Web Scraping / Screenshot / Extraction / Crawler share
236
+ // one shape (request-based) but live under different URL prefixes;
237
+ // Cloud Browser is session-based and exposes a distinct shape.
238
+ // See https://scrapfly.io/docs/monitoring#api
239
+ async monitoringRequest(path, params) {
240
+ const url = new URL(this.HOST + path);
241
+ url.search = new URLSearchParams(params).toString();
242
+ const response = await this.fetch({
243
+ url: url.toString(),
244
+ method: 'GET',
245
+ headers: {
246
+ 'user-agent': this.ua,
247
+ 'accept-encoding': 'gzip, deflate, br',
248
+ accept: 'application/json',
249
+ },
250
+ });
251
+ const data = (await response.json());
252
+ if ('error_id' in data) {
253
+ if (data.http_code == 401 || response.status == 401) {
254
+ throw new errors.BadApiKeyError(JSON.stringify(data));
255
+ }
256
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
257
+ }
258
+ return data;
259
+ }
260
+ buildMetricsParams(options) {
261
+ const params = {
262
+ key: this.key,
263
+ format: options.format ?? 'structured',
264
+ };
265
+ if (options.period !== undefined)
266
+ params.period = options.period;
267
+ if (options.aggregation !== undefined && options.aggregation.length > 0) {
268
+ params.aggregation = options.aggregation.join(',');
269
+ }
270
+ if (options.includeWebhook)
271
+ params.include_webhook = 'true';
272
+ return params;
273
+ }
274
+ buildTargetParams(options) {
275
+ if ((options.start && !options.end) || (!options.start && options.end)) {
276
+ throw new Error('You must provide both start and end date');
277
+ }
278
+ const params = {
279
+ key: this.key,
280
+ domain: options.domain,
281
+ group_subdomain: String(options.groupSubdomain ?? false),
282
+ };
283
+ if (options.start && options.end) {
284
+ params.start = formatMonitoringDate(options.start);
285
+ params.end = formatMonitoringDate(options.end);
286
+ }
287
+ else if (options.period !== undefined) {
288
+ params.period = options.period;
289
+ }
290
+ else {
291
+ params.period = 'last24h';
292
+ }
293
+ if (options.includeWebhook)
294
+ params.include_webhook = 'true';
295
+ return params;
296
+ }
297
+ // ── Web Scraping API (existing — kept for backward compat) ──────
298
+ async getMonitoringMetrics(options = {}) {
299
+ return this.monitoringRequest('/scrape/monitoring/metrics', this.buildMetricsParams(options));
300
+ }
301
+ async getMonitoringTargetMetrics(options) {
302
+ return this.monitoringRequest('/scrape/monitoring/metrics/target', this.buildTargetParams(options));
303
+ }
304
+ // ── Screenshot API ───────────────────────────────────────────────
305
+ async getScreenshotMonitoringMetrics(options = {}) {
306
+ return this.monitoringRequest('/screenshot/monitoring/metrics', this.buildMetricsParams(options));
307
+ }
308
+ async getScreenshotMonitoringTargetMetrics(options) {
309
+ return this.monitoringRequest('/screenshot/monitoring/metrics/target', this.buildTargetParams(options));
310
+ }
311
+ // ── Extraction API ───────────────────────────────────────────────
312
+ async getExtractionMonitoringMetrics(options = {}) {
313
+ return this.monitoringRequest('/extraction/monitoring/metrics', this.buildMetricsParams(options));
314
+ }
315
+ async getExtractionMonitoringTargetMetrics(options) {
316
+ return this.monitoringRequest('/extraction/monitoring/metrics/target', this.buildTargetParams(options));
317
+ }
318
+ // ── Crawler API ──────────────────────────────────────────────────
319
+ async getCrawlerMonitoringMetrics(options = {}) {
320
+ return this.monitoringRequest('/crawl/monitoring/metrics', this.buildMetricsParams(options));
321
+ }
322
+ async getCrawlerMonitoringTargetMetrics(options) {
323
+ return this.monitoringRequest('/crawl/monitoring/metrics/target', this.buildTargetParams(options));
324
+ }
325
+ // ── Cloud Browser API (session-based, distinct shape) ────────────
326
+ async getBrowserMonitoringMetrics(options = {}) {
327
+ return this.monitoringRequest('/browser/monitoring/metrics', this.buildBrowserParams(options));
328
+ }
329
+ async getBrowserMonitoringTimeseries(options = {}) {
330
+ return this.monitoringRequest('/browser/monitoring/metrics/timeseries', this.buildBrowserParams(options));
331
+ }
332
+ buildBrowserParams(options) {
333
+ if ((options.start && !options.end) || (!options.start && options.end)) {
334
+ throw new Error('You must provide both start and end date');
335
+ }
336
+ const params = { key: this.key };
337
+ if (options.start && options.end) {
338
+ params.start = formatMonitoringDate(options.start);
339
+ params.end = formatMonitoringDate(options.end);
340
+ }
341
+ else if (options.period !== undefined) {
342
+ params.period = options.period;
343
+ }
344
+ if (options.proxyPool !== undefined)
345
+ params.proxy_pool = options.proxyPool;
346
+ return params;
347
+ }
188
348
  /**
189
349
  * Issue a single scrape command from a given scrape configuration
190
350
  */
@@ -211,9 +371,66 @@ export class ScrapflyClient {
211
371
  }
212
372
  catch (e) {
213
373
  log.error('error', e);
214
- e.scrapeConfig = config;
374
+ // Attach the scrape config to the thrown error for debuggability.
375
+ // The error is typed as `unknown` since TypeScript 4.4 strict catch
376
+ // clause variables, so we narrow to a mutable object before tagging.
377
+ if (e !== null && typeof e === 'object') {
378
+ e.scrapeConfig = config;
379
+ }
215
380
  throw e;
216
381
  }
382
+ // Proxified mode: the API returns the raw upstream response (target's
383
+ // status, headers, body) instead of the JSON envelope. Return the raw
384
+ // fetch Response so callers can drive it like any HTTP response.
385
+ //
386
+ // DO NOT throw on non-2xx: the response status is the UPSTREAM target's
387
+ // status, not a Scrapfly system error. A 503 from the target is a
388
+ // legitimate proxified response, not an API failure.
389
+ //
390
+ // Callers inspect:
391
+ // response.status — the upstream status
392
+ // response.headers.get("x-scrapfly-reject-code") — Scrapfly error (if any)
393
+ // response.headers.get("x-scrapfly-api-cost") — credits charged
394
+ if (config.proxified_response === true) {
395
+ // Error restoration: if X-Scrapfly-Reject-Code is present, the
396
+ // scrape failed. Reconstruct a typed error from the headers so
397
+ // callers get the same error interface as non-proxified mode.
398
+ const rejectCode = response.headers.get('x-scrapfly-reject-code');
399
+ if (rejectCode) {
400
+ const rejectDesc = response.headers.get('x-scrapfly-reject-description') ?? '';
401
+ const rejectRetryable = response.headers.get('x-scrapfly-reject-retryable') === 'true';
402
+ const retryAfter = rejectRetryable ? parseInt(response.headers.get('retry-after') ?? '0', 10) : 0;
403
+ const err = new errors.ApiHttpClientError(`Proxified scrape error: ${rejectCode} — ${rejectDesc}`);
404
+ err.code = rejectCode;
405
+ err.httpStatusCode = response.status;
406
+ err.retryable = rejectRetryable;
407
+ err.retryAfter = retryAfter;
408
+ err.response = response;
409
+ throw err;
410
+ }
411
+ return response;
412
+ }
413
+ // HEAD responses have no body per HTTP spec — the API returns headers
414
+ // only. Build a ScrapeResult from the HTTP response headers and the
415
+ // local config, mirroring the Python SDK's HEAD handler.
416
+ if (config.method === 'HEAD') {
417
+ const responseHeaders = {};
418
+ response.headers.forEach((v, k) => { responseHeaders[k] = v; });
419
+ return this.handleResponse(response, new ScrapeResult({
420
+ config: config.toApiParams({ key: this.key }),
421
+ context: {},
422
+ result: {
423
+ status_code: response.status,
424
+ content: '',
425
+ format: 'text',
426
+ success: response.status >= 200 && response.status < 300,
427
+ status: 'DONE',
428
+ response_headers: responseHeaders,
429
+ request_headers: {},
430
+ },
431
+ uuid: '',
432
+ }));
433
+ }
217
434
  const data = await response.json();
218
435
  if ('error_id' in data || Object.keys(data).length === 0) {
219
436
  if (data.http_code == 401 || response.status == 401) {
@@ -375,7 +592,7 @@ export class ScrapflyClient {
375
592
  let response;
376
593
  try {
377
594
  const url = new URL(this.HOST + '/extraction');
378
- const params = await config.toApiParams({ key: this.key });
595
+ const params = config.toApiParams({ key: this.key });
379
596
  url.search = new URLSearchParams(params).toString();
380
597
  const headers = {
381
598
  'user-agent': this.ua,
@@ -400,4 +617,684 @@ export class ScrapflyClient {
400
617
  const result = await this.handleExtractionResponse(response);
401
618
  return result;
402
619
  }
620
+ // ---------------------------------------------------------------------------
621
+ // Crawler API
622
+ // ---------------------------------------------------------------------------
623
+ /**
624
+ * Throw a typed error for a crawler JSON error envelope.
625
+ *
626
+ * The crawler endpoints (status, urls, contents, artifact, cancel) return either
627
+ * a clean JSON body on success or an error envelope `{error_id, http_code, message, ...}`.
628
+ * Use this to map the envelope to one of `BadApiKeyError` / `ScrapflyCrawlerError` /
629
+ * `ApiHttpClientError`.
630
+ */
631
+ throwCrawlerError(response, data) {
632
+ const httpCode = data.http_code ?? response.status;
633
+ const code = (data.code ?? '');
634
+ const message = data.message ?? JSON.stringify(data);
635
+ if (httpCode === 401) {
636
+ throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
637
+ }
638
+ if (httpCode === 429) {
639
+ throw new errors.TooManyRequests(message, { http_status_code: httpCode, code, api_response: data });
640
+ }
641
+ // Any ERR::CRAWLER::* code → typed crawler error
642
+ if (typeof code === 'string' && code.includes('::CRAWLER::')) {
643
+ throw new errors.ScrapflyCrawlerError(message, { http_status_code: httpCode, code, api_response: data });
644
+ }
645
+ throw new errors.ApiHttpClientError(message, { http_status_code: httpCode, code, api_response: data });
646
+ }
647
+ /**
648
+ * Schedule a new crawler job.
649
+ *
650
+ * `POST /crawl` — returns `{crawler_uuid, status}` on success. On failure throws
651
+ * `ScrapflyCrawlerError`, `BadApiKeyError`, or `ApiHttpClientError`.
652
+ */
653
+ async crawl(config) {
654
+ log.debug('crawling', { url: config.url });
655
+ let response;
656
+ try {
657
+ const url = new URL(this.HOST + '/crawl');
658
+ url.search = new URLSearchParams({ key: this.key }).toString();
659
+ response = await this.fetch({
660
+ url: url.toString(),
661
+ method: 'POST',
662
+ headers: {
663
+ 'user-agent': this.ua,
664
+ 'content-type': 'application/json',
665
+ 'accept-encoding': 'gzip, deflate, br',
666
+ accept: 'application/json',
667
+ },
668
+ body: JSON.stringify(config.toApiParams()),
669
+ });
670
+ }
671
+ catch (e) {
672
+ log.error('error', e);
673
+ throw e;
674
+ }
675
+ const data = (await response.json());
676
+ if ('error_id' in data || data.http_code !== undefined) {
677
+ this.throwCrawlerError(response, data);
678
+ }
679
+ if (typeof data.uuid !== 'string' && typeof data.crawler_uuid !== 'string') {
680
+ throw new errors.ApiHttpClientError(`Crawler API returned no uuid: ${JSON.stringify(data).slice(0, 500)}`);
681
+ }
682
+ return {
683
+ crawler_uuid: (data.crawler_uuid ?? data.uuid),
684
+ status: (data.status ?? 'PENDING'),
685
+ };
686
+ }
687
+ /**
688
+ * Get the current status of a crawler job.
689
+ *
690
+ * `GET /crawl/{uuid}/status`
691
+ */
692
+ async crawlStatus(uuid) {
693
+ let response;
694
+ try {
695
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/status`);
696
+ url.search = new URLSearchParams({ key: this.key }).toString();
697
+ response = await this.fetch({
698
+ url: url.toString(),
699
+ method: 'GET',
700
+ headers: {
701
+ 'user-agent': this.ua,
702
+ 'accept-encoding': 'gzip, deflate, br',
703
+ accept: 'application/json',
704
+ },
705
+ });
706
+ }
707
+ catch (e) {
708
+ log.error('error', e);
709
+ throw e;
710
+ }
711
+ const data = (await response.json());
712
+ if ('error_id' in data || data.http_code !== undefined) {
713
+ this.throwCrawlerError(response, data);
714
+ }
715
+ return new CrawlerStatus(data);
716
+ }
717
+ /**
718
+ * List crawled URLs for a job, optionally filtered by status and paginated.
719
+ *
720
+ * `GET /crawl/{uuid}/urls?status=<filter>&page=<n>&per_page=<n>`
721
+ *
722
+ * The server streams the response as `text/plain` — one record per line.
723
+ * JSON is intentionally NOT used here because this endpoint is expected to
724
+ * scale to millions of URLs per job, and materialising that as JSON would
725
+ * be prohibitively expensive on both the server and the client. See
726
+ * {@link CrawlerUrls.fromText} for the exact line format.
727
+ *
728
+ * Pagination: the wire protocol carries no global `total`. Request further
729
+ * pages by incrementing `page` until a response contains no records.
730
+ */
731
+ async crawlUrls(uuid, opts) {
732
+ const statusHint = opts?.status ?? 'visited';
733
+ const page = opts?.page ?? 1;
734
+ const perPage = opts?.per_page ?? 100;
735
+ let response;
736
+ try {
737
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/urls`);
738
+ const params = { key: this.key };
739
+ if (opts?.status)
740
+ params.status = opts.status;
741
+ if (opts?.page !== undefined)
742
+ params.page = String(opts.page);
743
+ if (opts?.per_page !== undefined)
744
+ params.per_page = String(opts.per_page);
745
+ url.search = new URLSearchParams(params).toString();
746
+ response = await this.fetch({
747
+ url: url.toString(),
748
+ method: 'GET',
749
+ headers: {
750
+ 'user-agent': this.ua,
751
+ 'accept-encoding': 'gzip, deflate, br',
752
+ // text/plain is the canonical format; we also accept JSON because
753
+ // error envelopes come back as JSON regardless of the success type.
754
+ accept: 'text/plain, application/json',
755
+ },
756
+ });
757
+ }
758
+ catch (e) {
759
+ log.error('error', e);
760
+ throw e;
761
+ }
762
+ // Error envelopes are always JSON, even for text endpoints. Detect by
763
+ // content-type before consuming the body as text.
764
+ const ct = response.headers.get('content-type') ?? '';
765
+ if (ct.includes('application/json')) {
766
+ const data = (await response.json());
767
+ if ('error_id' in data || data.http_code !== undefined) {
768
+ this.throwCrawlerError(response, data);
769
+ }
770
+ // Unexpected: the server sent JSON on a success response for the text
771
+ // endpoint. Surface this as a client error so users see the mismatch
772
+ // instead of getting silent empty results.
773
+ throw new errors.ApiHttpClientError(`crawlUrls expected text/plain, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
774
+ }
775
+ const body = await response.text();
776
+ return CrawlerUrls.fromText(body, statusHint, page, perPage);
777
+ }
778
+ /**
779
+ * Get crawled content from a crawler job.
780
+ *
781
+ * Two modes:
782
+ *
783
+ * 1. **JSON mode** (default, `plain` omitted or false): returns a {@link CrawlerContents}
784
+ * with a `contents` map (URL → format → content) and pagination links. Useful for
785
+ * bulk retrieval. Honors `limit` (max 50, default 10) and `offset`.
786
+ *
787
+ * 2. **Plain mode** (`plain: true`): returns the raw content for a single URL/format
788
+ * as a `string`, with content-type matching the format. Requires `url`. Useful for
789
+ * piping markdown/text directly. **New in this SDK** (not in Python SDK as of 0.8.27).
790
+ *
791
+ * `GET /crawl/{uuid}/contents`
792
+ */
793
+ async crawlContents(uuid, opts) {
794
+ if (opts.plain && !opts.url) {
795
+ throw new errors.CrawlerConfigError('plain=true requires a single `url` argument');
796
+ }
797
+ let response;
798
+ try {
799
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents`);
800
+ // Note: the server query param is `formats` (plural), not `format`. The
801
+ // public docs say `format` but the actual server only accepts `formats`.
802
+ // We expose `format` (singular) as the SDK option since that's what users
803
+ // expect from the docs, and translate it here.
804
+ const params = { key: this.key, formats: opts.format };
805
+ if (opts.url)
806
+ params.url = opts.url;
807
+ if (opts.plain)
808
+ params.plain = 'true';
809
+ if (opts.limit !== undefined)
810
+ params.limit = String(opts.limit);
811
+ if (opts.offset !== undefined)
812
+ params.offset = String(opts.offset);
813
+ url.search = new URLSearchParams(params).toString();
814
+ response = await this.fetch({
815
+ url: url.toString(),
816
+ method: 'GET',
817
+ headers: {
818
+ 'user-agent': this.ua,
819
+ 'accept-encoding': 'gzip, deflate, br',
820
+ // In plain mode the server returns the raw content with a format-matching
821
+ // content-type (text/markdown, text/html, etc.); accept anything.
822
+ accept: opts.plain ? '*/*' : 'application/json',
823
+ },
824
+ });
825
+ }
826
+ catch (e) {
827
+ log.error('error', e);
828
+ throw e;
829
+ }
830
+ if (opts.plain) {
831
+ // Plain mode: server returns raw text. Error envelopes still come back as JSON,
832
+ // so detect that by content-type before reading the body as text.
833
+ const ct = response.headers.get('content-type') ?? '';
834
+ if (ct.includes('application/json')) {
835
+ const data = (await response.json());
836
+ if ('error_id' in data || data.http_code !== undefined) {
837
+ this.throwCrawlerError(response, data);
838
+ }
839
+ // JSON came back without an error envelope — caller asked for plain but server
840
+ // returned JSON anyway (e.g. format=json). Stringify so the return type is stable.
841
+ return JSON.stringify(data);
842
+ }
843
+ return await response.text();
844
+ }
845
+ const data = (await response.json());
846
+ if ('error_id' in data || data.http_code !== undefined) {
847
+ this.throwCrawlerError(response, data);
848
+ }
849
+ return new CrawlerContents(data);
850
+ }
851
+ /**
852
+ * Batch-retrieve crawled content for up to 100 URLs in one round-trip.
853
+ *
854
+ * `POST /crawl/{uuid}/contents/batch`
855
+ *
856
+ * The request body is a newline-separated list of URLs (`text/plain`). The response
857
+ * is a `multipart/related` (RFC 2387) document with one part per found URL. Each
858
+ * part has `Content-Type` (matching the format) and `Content-Location` (the URL).
859
+ *
860
+ * Returns a map of `url → format → content`. Formats not requested for a given URL
861
+ * are simply absent from its inner map.
862
+ */
863
+ async crawlContentsBatch(uuid, urls, formats) {
864
+ if (urls.length === 0) {
865
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one url');
866
+ }
867
+ if (urls.length > 100) {
868
+ throw new errors.CrawlerConfigError('crawlContentsBatch is limited to 100 urls per request');
869
+ }
870
+ if (formats.length === 0) {
871
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one format');
872
+ }
873
+ let response;
874
+ try {
875
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents/batch`);
876
+ url.search = new URLSearchParams({ key: this.key, formats: formats.join(',') }).toString();
877
+ response = await this.fetch({
878
+ url: url.toString(),
879
+ method: 'POST',
880
+ headers: {
881
+ 'user-agent': this.ua,
882
+ 'content-type': 'text/plain',
883
+ 'accept-encoding': 'gzip, deflate, br',
884
+ accept: 'multipart/related, application/json',
885
+ },
886
+ body: urls.join('\n'),
887
+ });
888
+ }
889
+ catch (e) {
890
+ log.error('error', e);
891
+ throw e;
892
+ }
893
+ const ct = response.headers.get('content-type') ?? '';
894
+ if (ct.includes('application/json')) {
895
+ // Error envelope
896
+ const data = (await response.json());
897
+ if ('error_id' in data || data.http_code !== undefined) {
898
+ this.throwCrawlerError(response, data);
899
+ }
900
+ throw new errors.ApiHttpClientError(`crawlContentsBatch expected multipart/related, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
901
+ }
902
+ const text = await response.text();
903
+ return parseMultipartRelated(text, ct, formats);
904
+ }
905
+ /**
906
+ * Download a crawler job's WARC or HAR artifact as raw bytes.
907
+ *
908
+ * `GET /crawl/{uuid}/artifact?type=warc|har`
909
+ *
910
+ * The SDK does NOT bundle WARC/HAR parsers — use a dedicated library (e.g. `warcio`
911
+ * on npm) to walk the records. The returned {@link CrawlerArtifact} provides a
912
+ * `save(path)` helper for the common case of writing the artifact to disk.
913
+ */
914
+ async crawlArtifact(uuid, type = 'warc') {
915
+ let response;
916
+ try {
917
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/artifact`);
918
+ url.search = new URLSearchParams({ key: this.key, type }).toString();
919
+ response = await this.fetch({
920
+ url: url.toString(),
921
+ method: 'GET',
922
+ headers: {
923
+ 'user-agent': this.ua,
924
+ // Accept the artifact's binary content type plus JSON for error envelopes
925
+ accept: type === 'har' ? 'application/json, application/octet-stream' : 'application/gzip, application/octet-stream',
926
+ },
927
+ });
928
+ }
929
+ catch (e) {
930
+ log.error('error', e);
931
+ throw e;
932
+ }
933
+ // Error envelope check (server returns JSON on errors regardless of artifact type)
934
+ const ct = response.headers.get('content-type') ?? '';
935
+ if (ct.includes('application/json') && type !== 'har') {
936
+ // For warc, JSON responses are always errors. For har, JSON IS the artifact —
937
+ // we need to peek at the body to distinguish.
938
+ const data = (await response.json());
939
+ if ('error_id' in data || data.http_code !== undefined) {
940
+ this.throwCrawlerError(response, data);
941
+ }
942
+ // Should not reach here for warc; treat as unexpected JSON.
943
+ throw new errors.ApiHttpClientError(`crawlArtifact(${type}) expected binary, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
944
+ }
945
+ const buf = new Uint8Array(await response.arrayBuffer());
946
+ // For HAR, the body IS JSON — but we still need to detect error envelopes
947
+ // (which set http_code or error_id at the top level of the JSON object).
948
+ if (type === 'har') {
949
+ try {
950
+ const text = new TextDecoder().decode(buf);
951
+ const parsed = JSON.parse(text);
952
+ if ('error_id' in parsed || parsed.http_code !== undefined) {
953
+ this.throwCrawlerError(response, parsed);
954
+ }
955
+ }
956
+ catch (e) {
957
+ // If JSON parse fails, the body is not an error envelope — treat as raw HAR bytes.
958
+ if (e instanceof errors.ScrapflyError)
959
+ throw e;
960
+ }
961
+ }
962
+ return new CrawlerArtifact(type, buf);
963
+ }
964
+ /**
965
+ * Cancel a running crawler job.
966
+ *
967
+ * `POST /crawl/{uuid}/cancel` — returns `true` on success. The endpoint
968
+ * is idempotent: cancelling a crawl that has already finished is a no-op
969
+ * and still returns success.
970
+ *
971
+ * Note: earlier versions of this SDK called `DELETE /crawl/{uuid}`, which
972
+ * is not a valid public route — that path silently 404'd against the
973
+ * public API. Fixed in 0.8.0 to use the correct documented endpoint.
974
+ */
975
+ async crawlCancel(uuid) {
976
+ let response;
977
+ try {
978
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/cancel`);
979
+ url.search = new URLSearchParams({ key: this.key }).toString();
980
+ response = await this.fetch({
981
+ url: url.toString(),
982
+ method: 'POST',
983
+ headers: {
984
+ 'user-agent': this.ua,
985
+ 'accept-encoding': 'gzip, deflate, br',
986
+ accept: 'application/json',
987
+ },
988
+ });
989
+ }
990
+ catch (e) {
991
+ log.error('error', e);
992
+ throw e;
993
+ }
994
+ // Empty body or JSON
995
+ const ct = response.headers.get('content-type') ?? '';
996
+ if (ct.includes('application/json')) {
997
+ const data = (await response.json());
998
+ if ('error_id' in data || data.http_code !== undefined) {
999
+ this.throwCrawlerError(response, data);
1000
+ }
1001
+ }
1002
+ return response.ok;
1003
+ }
1004
+ // --- Cloud Browser ---
1005
+ /**
1006
+ * Get the WebSocket URL for a Cloud Browser session.
1007
+ */
1008
+ cloudBrowser(config) {
1009
+ const browserConfig = config || new BrowserConfig();
1010
+ return browserConfig.websocketUrl(this.key, this.cloudBrowserHost);
1011
+ }
1012
+ /**
1013
+ * Call the Cloud Browser Unblock API.
1014
+ */
1015
+ async cloudBrowserUnblock(options) {
1016
+ const proxyPoolMap = {
1017
+ datacenter: 'public_datacenter_pool',
1018
+ residential: 'public_residential_pool',
1019
+ };
1020
+ const jsonBody = { url: options.url };
1021
+ if (options.proxy_pool)
1022
+ jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
1023
+ if (options.country)
1024
+ jsonBody.country = options.country;
1025
+ if (options.os)
1026
+ jsonBody.os = options.os;
1027
+ if (options.timeout)
1028
+ jsonBody.timeout = options.timeout;
1029
+ if (options.browser_timeout)
1030
+ jsonBody.browser_timeout = options.browser_timeout;
1031
+ if (options.headers)
1032
+ jsonBody.headers = options.headers;
1033
+ if (options.body)
1034
+ jsonBody.body = options.body;
1035
+ if (options.method)
1036
+ jsonBody.method = options.method;
1037
+ const url = new URL(this.cloudBrowserApiHost + '/unblock');
1038
+ url.searchParams.set('key', this.key);
1039
+ const response = await this.fetch({
1040
+ url: url.toString(),
1041
+ method: 'POST',
1042
+ headers: {
1043
+ 'content-type': 'application/json',
1044
+ 'user-agent': this.ua,
1045
+ },
1046
+ body: JSON.stringify(jsonBody),
1047
+ });
1048
+ if (!response.ok) {
1049
+ throw new Error(`Unblock failed: ${response.status} ${await response.text()}`);
1050
+ }
1051
+ return await response.json();
1052
+ }
1053
+ /**
1054
+ * Stop a Cloud Browser session.
1055
+ */
1056
+ async cloudBrowserSessionStop(sessionId) {
1057
+ const url = new URL(this.cloudBrowserApiHost + '/session/' + sessionId + '/stop');
1058
+ url.searchParams.set('key', this.key);
1059
+ const response = await this.fetch({
1060
+ url: url.toString(),
1061
+ method: 'POST',
1062
+ headers: { 'user-agent': this.ua },
1063
+ });
1064
+ if (!response.ok) {
1065
+ throw new Error(`Session stop failed: ${response.status} ${await response.text()}`);
1066
+ }
1067
+ }
1068
+ /**
1069
+ * List all browser extensions.
1070
+ */
1071
+ async cloudBrowserExtensionList() {
1072
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1073
+ url.searchParams.set('key', this.key);
1074
+ const response = await this.fetch({
1075
+ url: url.toString(),
1076
+ method: 'GET',
1077
+ headers: { 'user-agent': this.ua },
1078
+ });
1079
+ if (!response.ok) {
1080
+ throw new Error(`Extension list failed: ${response.status} ${await response.text()}`);
1081
+ }
1082
+ return await response.json();
1083
+ }
1084
+ /**
1085
+ * Delete a browser extension.
1086
+ */
1087
+ async cloudBrowserExtensionDelete(extensionId) {
1088
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
1089
+ url.searchParams.set('key', this.key);
1090
+ const response = await this.fetch({
1091
+ url: url.toString(),
1092
+ method: 'DELETE',
1093
+ headers: { 'user-agent': this.ua },
1094
+ });
1095
+ if (!response.ok) {
1096
+ throw new Error(`Extension delete failed: ${response.status} ${await response.text()}`);
1097
+ }
1098
+ return await response.json();
1099
+ }
1100
+ /**
1101
+ * Get details of a specific browser extension.
1102
+ */
1103
+ async cloudBrowserExtensionGet(extensionId) {
1104
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
1105
+ url.searchParams.set('key', this.key);
1106
+ const response = await this.fetch({
1107
+ url: url.toString(),
1108
+ method: 'GET',
1109
+ headers: { 'user-agent': this.ua },
1110
+ });
1111
+ if (!response.ok) {
1112
+ throw new Error(`Extension get failed: ${response.status} ${await response.text()}`);
1113
+ }
1114
+ return await response.json();
1115
+ }
1116
+ /**
1117
+ * Upload a browser extension from a local file (.zip or .crx).
1118
+ * Pass a file path — the file is read and sent as multipart/form-data.
1119
+ */
1120
+ async cloudBrowserExtensionUpload(filePath) {
1121
+ const fileBytes = readFileSync(filePath);
1122
+ const fileName = filePath.split('/').pop() || filePath.split('\\').pop() || 'extension.zip';
1123
+ const boundary = '----ScrapflyBoundary' + Date.now();
1124
+ const encoder = new TextEncoder();
1125
+ const header = encoder.encode(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: application/octet-stream\r\n\r\n`);
1126
+ const footer = encoder.encode(`\r\n--${boundary}--\r\n`);
1127
+ const body = new Uint8Array(header.length + fileBytes.length + footer.length);
1128
+ body.set(header, 0);
1129
+ body.set(fileBytes, header.length);
1130
+ body.set(footer, header.length + fileBytes.length);
1131
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1132
+ url.searchParams.set('key', this.key);
1133
+ const response = await this.fetch({
1134
+ url: url.toString(),
1135
+ method: 'POST',
1136
+ headers: {
1137
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
1138
+ 'user-agent': this.ua,
1139
+ },
1140
+ body: body,
1141
+ });
1142
+ if (!response.ok) {
1143
+ throw new Error(`Extension upload failed: ${response.status} ${await response.text()}`);
1144
+ }
1145
+ return await response.json();
1146
+ }
1147
+ /**
1148
+ * Install a browser extension from a URL (.crx file).
1149
+ * URL-based extensions auto-update on each browser session start.
1150
+ */
1151
+ async cloudBrowserExtensionUploadFromUrl(extensionUrl) {
1152
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1153
+ url.searchParams.set('key', this.key);
1154
+ const response = await this.fetch({
1155
+ url: url.toString(),
1156
+ method: 'POST',
1157
+ headers: {
1158
+ 'content-type': 'application/json',
1159
+ 'user-agent': this.ua,
1160
+ },
1161
+ body: JSON.stringify({ extension_url: extensionUrl }),
1162
+ });
1163
+ if (!response.ok) {
1164
+ throw new Error(`Extension upload from URL failed: ${response.status} ${await response.text()}`);
1165
+ }
1166
+ return await response.json();
1167
+ }
1168
+ /**
1169
+ * Download a debug session recording video.
1170
+ * Returns the video as an ArrayBuffer (stream from server).
1171
+ */
1172
+ async cloudBrowserVideo(runId) {
1173
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/video');
1174
+ url.searchParams.set('key', this.key);
1175
+ const response = await this.fetch({
1176
+ url: url.toString(),
1177
+ method: 'GET',
1178
+ headers: { 'user-agent': this.ua },
1179
+ });
1180
+ if (!response.ok) {
1181
+ throw new Error(`Video download failed: ${response.status} ${await response.text()}`);
1182
+ }
1183
+ const filename = runId + '.webm';
1184
+ return { data: await response.arrayBuffer(), filename };
1185
+ }
1186
+ /**
1187
+ * Get playback info for a debug session recording.
1188
+ */
1189
+ async cloudBrowserPlayback(runId) {
1190
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/playback');
1191
+ url.searchParams.set('key', this.key);
1192
+ const response = await this.fetch({
1193
+ url: url.toString(),
1194
+ method: 'GET',
1195
+ headers: { 'user-agent': this.ua },
1196
+ });
1197
+ if (!response.ok) {
1198
+ throw new Error(`Playback get failed: ${response.status} ${await response.text()}`);
1199
+ }
1200
+ return await response.json();
1201
+ }
1202
+ /**
1203
+ * List all running Cloud Browser sessions.
1204
+ */
1205
+ async cloudBrowserSessions() {
1206
+ const url = new URL(this.cloudBrowserApiHost + '/sessions');
1207
+ url.searchParams.set('key', this.key);
1208
+ const response = await this.fetch({
1209
+ url: url.toString(),
1210
+ method: 'GET',
1211
+ headers: { 'user-agent': this.ua },
1212
+ });
1213
+ if (!response.ok) {
1214
+ throw new Error(`Sessions list failed: ${response.status} ${await response.text()}`);
1215
+ }
1216
+ return await response.json();
1217
+ }
1218
+ }
1219
+ // ---------------------------------------------------------------------------
1220
+ // multipart/related parser
1221
+ // ---------------------------------------------------------------------------
1222
+ //
1223
+ // Tiny inline parser for the response of `POST /crawl/{uuid}/contents/batch`.
1224
+ // Avoids pulling in a multipart npm dep so the SDK stays dependency-free.
1225
+ //
1226
+ // Each part has at minimum a `Content-Location: <url>` header and a body. The
1227
+ // `Content-Type` may also be set, indicating the format. We map URL → format → body
1228
+ // using the `formats` argument as the inferred-format fallback when the part has
1229
+ // no `Content-Type`.
1230
+ function parseMultipartRelated(body, contentType, formats) {
1231
+ const boundaryMatch = contentType.match(/boundary=(?:"([^"]+)"|([^;\s]+))/);
1232
+ if (!boundaryMatch) {
1233
+ throw new errors.ApiHttpClientError(`crawlContentsBatch: response has no multipart boundary in content-type "${contentType}"`);
1234
+ }
1235
+ const boundary = boundaryMatch[1] ?? boundaryMatch[2];
1236
+ const delimiter = `--${boundary}`;
1237
+ const result = {};
1238
+ // Split on the delimiter; first segment is the preamble (ignored), last is the
1239
+ // closing `--` (also ignored).
1240
+ const segments = body.split(delimiter);
1241
+ for (let i = 1; i < segments.length; i++) {
1242
+ let segment = segments[i];
1243
+ // Strip leading CRLF after the boundary
1244
+ if (segment.startsWith('\r\n'))
1245
+ segment = segment.slice(2);
1246
+ else if (segment.startsWith('\n'))
1247
+ segment = segment.slice(1);
1248
+ // The closing boundary is `--{boundary}--`; segment starts with `--` then EOL
1249
+ if (segment.startsWith('--'))
1250
+ break;
1251
+ // Trim trailing CRLF before the next boundary
1252
+ if (segment.endsWith('\r\n'))
1253
+ segment = segment.slice(0, -2);
1254
+ else if (segment.endsWith('\n'))
1255
+ segment = segment.slice(0, -1);
1256
+ // Header/body split: first blank line
1257
+ const headerEnd = segment.indexOf('\r\n\r\n');
1258
+ const altHeaderEnd = headerEnd === -1 ? segment.indexOf('\n\n') : headerEnd;
1259
+ if (altHeaderEnd === -1)
1260
+ continue;
1261
+ const headersRaw = segment.slice(0, altHeaderEnd);
1262
+ const partBody = segment.slice(altHeaderEnd + (headerEnd === -1 ? 2 : 4));
1263
+ // Parse headers
1264
+ let url;
1265
+ let format;
1266
+ for (const line of headersRaw.split(/\r?\n/)) {
1267
+ const colon = line.indexOf(':');
1268
+ if (colon === -1)
1269
+ continue;
1270
+ const name = line.slice(0, colon).trim().toLowerCase();
1271
+ const value = line.slice(colon + 1).trim();
1272
+ if (name === 'content-location')
1273
+ url = value;
1274
+ else if (name === 'content-type')
1275
+ format = inferFormatFromContentType(value);
1276
+ }
1277
+ if (!url)
1278
+ continue;
1279
+ if (!format) {
1280
+ // Fall back to the first requested format if the part has no content-type
1281
+ format = formats[0];
1282
+ }
1283
+ if (!result[url])
1284
+ result[url] = {};
1285
+ result[url][format] = partBody;
1286
+ }
1287
+ return result;
1288
+ }
1289
+ function inferFormatFromContentType(ct) {
1290
+ const lc = ct.toLowerCase().split(';')[0].trim();
1291
+ if (lc === 'text/html')
1292
+ return 'html';
1293
+ if (lc === 'text/markdown')
1294
+ return 'markdown';
1295
+ if (lc === 'text/plain')
1296
+ return 'text';
1297
+ if (lc === 'application/json')
1298
+ return 'json';
1299
+ return undefined;
403
1300
  }