scrapfly-sdk 0.7.3 → 0.9.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 (69) 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 +193 -1
  5. package/esm/client.d.ts.map +1 -1
  6. package/esm/client.js +786 -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 +8 -1
  23. package/esm/main.d.ts.map +1 -1
  24. package/esm/main.js +6 -1
  25. package/esm/polyfill.d.ts +2 -0
  26. package/esm/polyfill.d.ts.map +1 -1
  27. package/esm/polyfill.js +12 -0
  28. package/esm/scrapeconfig.d.ts +27 -0
  29. package/esm/scrapeconfig.d.ts.map +1 -1
  30. package/esm/scrapeconfig.js +44 -1
  31. package/esm/screenshotconfig.d.ts +2 -2
  32. package/esm/screenshotconfig.d.ts.map +1 -1
  33. package/esm/utils.d.ts.map +1 -1
  34. package/esm/utils.js +16 -2
  35. package/package.json +1 -1
  36. package/script/browserconfig.d.ts +59 -0
  37. package/script/browserconfig.d.ts.map +1 -0
  38. package/script/browserconfig.js +211 -0
  39. package/script/client.d.ts +193 -1
  40. package/script/client.d.ts.map +1 -1
  41. package/script/client.js +785 -4
  42. package/script/crawl.d.ts +118 -0
  43. package/script/crawl.d.ts.map +1 -0
  44. package/script/crawl.js +257 -0
  45. package/script/crawlerconfig.d.ts +119 -0
  46. package/script/crawlerconfig.d.ts.map +1 -0
  47. package/script/crawlerconfig.js +402 -0
  48. package/script/crawlerresult.d.ts +253 -0
  49. package/script/crawlerresult.d.ts.map +1 -0
  50. package/script/crawlerresult.js +335 -0
  51. package/script/errors.d.ts +4 -0
  52. package/script/errors.d.ts.map +1 -1
  53. package/script/errors.js +9 -1
  54. package/script/extractionconfig.d.ts +2 -0
  55. package/script/extractionconfig.d.ts.map +1 -1
  56. package/script/extractionconfig.js +10 -0
  57. package/script/main.d.ts +8 -1
  58. package/script/main.d.ts.map +1 -1
  59. package/script/main.js +17 -1
  60. package/script/polyfill.d.ts +2 -0
  61. package/script/polyfill.d.ts.map +1 -1
  62. package/script/polyfill.js +14 -1
  63. package/script/scrapeconfig.d.ts +27 -0
  64. package/script/scrapeconfig.d.ts.map +1 -1
  65. package/script/scrapeconfig.js +44 -1
  66. package/script/screenshotconfig.d.ts +2 -2
  67. package/script/screenshotconfig.d.ts.map +1 -1
  68. package/script/utils.d.ts.map +1 -1
  69. package/script/utils.js +16 -2
package/esm/client.js CHANGED
@@ -1,9 +1,11 @@
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';
7
9
  export class ScrapflyClient {
8
10
  constructor(options) {
9
11
  Object.defineProperty(this, "HOST", {
@@ -12,6 +14,18 @@ export class ScrapflyClient {
12
14
  writable: true,
13
15
  value: 'https://api.scrapfly.io'
14
16
  });
17
+ Object.defineProperty(this, "CLOUD_BROWSER_HOST", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: 'wss://browser.scrapfly.io'
22
+ });
23
+ Object.defineProperty(this, "CLOUD_BROWSER_API_HOST", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: 'https://browser.scrapfly.io'
28
+ });
15
29
  Object.defineProperty(this, "key", {
16
30
  enumerable: true,
17
31
  configurable: true,
@@ -24,6 +38,18 @@ export class ScrapflyClient {
24
38
  writable: true,
25
39
  value: void 0
26
40
  });
41
+ Object.defineProperty(this, "cloudBrowserHost", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: void 0
46
+ });
47
+ Object.defineProperty(this, "cloudBrowserApiHost", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: void 0
52
+ });
27
53
  Object.defineProperty(this, "fetch", {
28
54
  enumerable: true,
29
55
  configurable: true,
@@ -34,7 +60,15 @@ export class ScrapflyClient {
34
60
  throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
35
61
  }
36
62
  this.key = options.key;
63
+ if (options.host) {
64
+ // Trim trailing slash so callers can pass either form
65
+ this.HOST = options.host.replace(/\/+$/, '');
66
+ }
37
67
  this.ua = 'Typescript Scrapfly SDK';
68
+ this.cloudBrowserHost = options.cloudBrowserHost || this.CLOUD_BROWSER_HOST;
69
+ this.cloudBrowserApiHost = options.cloudBrowserHost
70
+ ? options.cloudBrowserHost.replace('wss://', 'https://')
71
+ : this.CLOUD_BROWSER_API_HOST;
38
72
  }
39
73
  /**
40
74
  * Raise appropriate error for given response and scrape result
@@ -42,12 +76,18 @@ export class ScrapflyClient {
42
76
  errResult(response, result) {
43
77
  const error = result.result.error;
44
78
  const message = error?.message ?? '';
79
+ // When success=false the authoritative error code lives in result.result.error.code
80
+ // (e.g. "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE"). result.result.status is only "DONE"
81
+ // or a job-level error and does not carry the upstream-failure code.
82
+ const effectiveCode = (result.result.success === false && error?.code)
83
+ ? error.code
84
+ : result.result.status;
45
85
  const args = {
46
- code: result.result.status,
86
+ code: effectiveCode,
47
87
  http_status_code: result.result.status_code,
48
88
  is_retryable: error?.retryable ?? false,
49
89
  api_response: result,
50
- resource: result.result.status ? result.result.status.split('::')[1] : null,
90
+ resource: effectiveCode ? effectiveCode.split('::')[1] : null,
51
91
  retry_delay: error?.retryable ? 5 : response.headers.get('X-Retry') ?? 5,
52
92
  retry_times: 3,
53
93
  documentation_url: error?.doc_url ?? 'https://scrapfly.io/docs/scrape-api/errors#api',
@@ -74,6 +114,8 @@ export class ScrapflyClient {
74
114
  return new errors.ScrapflyAspError(message, args);
75
115
  case 'SESSION':
76
116
  return new errors.ScrapflySessionError(message, args);
117
+ case 'CRAWLER':
118
+ return new errors.ScrapflyCrawlerError(message, args);
77
119
  }
78
120
  if (args.resource) {
79
121
  return new errors.ApiHttpClientError(message, args);
@@ -101,6 +143,8 @@ export class ScrapflyClient {
101
143
  return new errors.ScrapflyAspError(message, args);
102
144
  case 'SESSION':
103
145
  return new errors.ScrapflySessionError(message, args);
146
+ case 'CRAWLER':
147
+ return new errors.ScrapflyCrawlerError(message, args);
104
148
  }
105
149
  }
106
150
  return new errors.ScrapflyError(message, args);
@@ -211,9 +255,66 @@ export class ScrapflyClient {
211
255
  }
212
256
  catch (e) {
213
257
  log.error('error', e);
214
- e.scrapeConfig = config;
258
+ // Attach the scrape config to the thrown error for debuggability.
259
+ // The error is typed as `unknown` since TypeScript 4.4 strict catch
260
+ // clause variables, so we narrow to a mutable object before tagging.
261
+ if (e !== null && typeof e === 'object') {
262
+ e.scrapeConfig = config;
263
+ }
215
264
  throw e;
216
265
  }
266
+ // Proxified mode: the API returns the raw upstream response (target's
267
+ // status, headers, body) instead of the JSON envelope. Return the raw
268
+ // fetch Response so callers can drive it like any HTTP response.
269
+ //
270
+ // DO NOT throw on non-2xx: the response status is the UPSTREAM target's
271
+ // status, not a Scrapfly system error. A 503 from the target is a
272
+ // legitimate proxified response, not an API failure.
273
+ //
274
+ // Callers inspect:
275
+ // response.status — the upstream status
276
+ // response.headers.get("x-scrapfly-reject-code") — Scrapfly error (if any)
277
+ // response.headers.get("x-scrapfly-api-cost") — credits charged
278
+ if (config.proxified_response === true) {
279
+ // Error restoration: if X-Scrapfly-Reject-Code is present, the
280
+ // scrape failed. Reconstruct a typed error from the headers so
281
+ // callers get the same error interface as non-proxified mode.
282
+ const rejectCode = response.headers.get('x-scrapfly-reject-code');
283
+ if (rejectCode) {
284
+ const rejectDesc = response.headers.get('x-scrapfly-reject-description') ?? '';
285
+ const rejectRetryable = response.headers.get('x-scrapfly-reject-retryable') === 'true';
286
+ const retryAfter = rejectRetryable ? parseInt(response.headers.get('retry-after') ?? '0', 10) : 0;
287
+ const err = new errors.ApiHttpClientError(`Proxified scrape error: ${rejectCode} — ${rejectDesc}`);
288
+ err.code = rejectCode;
289
+ err.httpStatusCode = response.status;
290
+ err.retryable = rejectRetryable;
291
+ err.retryAfter = retryAfter;
292
+ err.response = response;
293
+ throw err;
294
+ }
295
+ return response;
296
+ }
297
+ // HEAD responses have no body per HTTP spec — the API returns headers
298
+ // only. Build a ScrapeResult from the HTTP response headers and the
299
+ // local config, mirroring the Python SDK's HEAD handler.
300
+ if (config.method === 'HEAD') {
301
+ const responseHeaders = {};
302
+ response.headers.forEach((v, k) => { responseHeaders[k] = v; });
303
+ return this.handleResponse(response, new ScrapeResult({
304
+ config: config.toApiParams({ key: this.key }),
305
+ context: {},
306
+ result: {
307
+ status_code: response.status,
308
+ content: '',
309
+ format: 'text',
310
+ success: response.status >= 200 && response.status < 300,
311
+ status: 'DONE',
312
+ response_headers: responseHeaders,
313
+ request_headers: {},
314
+ },
315
+ uuid: '',
316
+ }));
317
+ }
217
318
  const data = await response.json();
218
319
  if ('error_id' in data || Object.keys(data).length === 0) {
219
320
  if (data.http_code == 401 || response.status == 401) {
@@ -375,7 +476,7 @@ export class ScrapflyClient {
375
476
  let response;
376
477
  try {
377
478
  const url = new URL(this.HOST + '/extraction');
378
- const params = await config.toApiParams({ key: this.key });
479
+ const params = config.toApiParams({ key: this.key });
379
480
  url.search = new URLSearchParams(params).toString();
380
481
  const headers = {
381
482
  'user-agent': this.ua,
@@ -400,4 +501,684 @@ export class ScrapflyClient {
400
501
  const result = await this.handleExtractionResponse(response);
401
502
  return result;
402
503
  }
504
+ // ---------------------------------------------------------------------------
505
+ // Crawler API
506
+ // ---------------------------------------------------------------------------
507
+ /**
508
+ * Throw a typed error for a crawler JSON error envelope.
509
+ *
510
+ * The crawler endpoints (status, urls, contents, artifact, cancel) return either
511
+ * a clean JSON body on success or an error envelope `{error_id, http_code, message, ...}`.
512
+ * Use this to map the envelope to one of `BadApiKeyError` / `ScrapflyCrawlerError` /
513
+ * `ApiHttpClientError`.
514
+ */
515
+ throwCrawlerError(response, data) {
516
+ const httpCode = data.http_code ?? response.status;
517
+ const code = (data.code ?? '');
518
+ const message = data.message ?? JSON.stringify(data);
519
+ if (httpCode === 401) {
520
+ throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
521
+ }
522
+ if (httpCode === 429) {
523
+ throw new errors.TooManyRequests(message, { http_status_code: httpCode, code, api_response: data });
524
+ }
525
+ // Any ERR::CRAWLER::* code → typed crawler error
526
+ if (typeof code === 'string' && code.includes('::CRAWLER::')) {
527
+ throw new errors.ScrapflyCrawlerError(message, { http_status_code: httpCode, code, api_response: data });
528
+ }
529
+ throw new errors.ApiHttpClientError(message, { http_status_code: httpCode, code, api_response: data });
530
+ }
531
+ /**
532
+ * Schedule a new crawler job.
533
+ *
534
+ * `POST /crawl` — returns `{crawler_uuid, status}` on success. On failure throws
535
+ * `ScrapflyCrawlerError`, `BadApiKeyError`, or `ApiHttpClientError`.
536
+ */
537
+ async crawl(config) {
538
+ log.debug('crawling', { url: config.url });
539
+ let response;
540
+ try {
541
+ const url = new URL(this.HOST + '/crawl');
542
+ url.search = new URLSearchParams({ key: this.key }).toString();
543
+ response = await this.fetch({
544
+ url: url.toString(),
545
+ method: 'POST',
546
+ headers: {
547
+ 'user-agent': this.ua,
548
+ 'content-type': 'application/json',
549
+ 'accept-encoding': 'gzip, deflate, br',
550
+ accept: 'application/json',
551
+ },
552
+ body: JSON.stringify(config.toApiParams()),
553
+ });
554
+ }
555
+ catch (e) {
556
+ log.error('error', e);
557
+ throw e;
558
+ }
559
+ const data = (await response.json());
560
+ if ('error_id' in data || data.http_code !== undefined) {
561
+ this.throwCrawlerError(response, data);
562
+ }
563
+ if (typeof data.uuid !== 'string' && typeof data.crawler_uuid !== 'string') {
564
+ throw new errors.ApiHttpClientError(`Crawler API returned no uuid: ${JSON.stringify(data).slice(0, 500)}`);
565
+ }
566
+ return {
567
+ crawler_uuid: (data.crawler_uuid ?? data.uuid),
568
+ status: (data.status ?? 'PENDING'),
569
+ };
570
+ }
571
+ /**
572
+ * Get the current status of a crawler job.
573
+ *
574
+ * `GET /crawl/{uuid}/status`
575
+ */
576
+ async crawlStatus(uuid) {
577
+ let response;
578
+ try {
579
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/status`);
580
+ url.search = new URLSearchParams({ key: this.key }).toString();
581
+ response = await this.fetch({
582
+ url: url.toString(),
583
+ method: 'GET',
584
+ headers: {
585
+ 'user-agent': this.ua,
586
+ 'accept-encoding': 'gzip, deflate, br',
587
+ accept: 'application/json',
588
+ },
589
+ });
590
+ }
591
+ catch (e) {
592
+ log.error('error', e);
593
+ throw e;
594
+ }
595
+ const data = (await response.json());
596
+ if ('error_id' in data || data.http_code !== undefined) {
597
+ this.throwCrawlerError(response, data);
598
+ }
599
+ return new CrawlerStatus(data);
600
+ }
601
+ /**
602
+ * List crawled URLs for a job, optionally filtered by status and paginated.
603
+ *
604
+ * `GET /crawl/{uuid}/urls?status=<filter>&page=<n>&per_page=<n>`
605
+ *
606
+ * The server streams the response as `text/plain` — one record per line.
607
+ * JSON is intentionally NOT used here because this endpoint is expected to
608
+ * scale to millions of URLs per job, and materialising that as JSON would
609
+ * be prohibitively expensive on both the server and the client. See
610
+ * {@link CrawlerUrls.fromText} for the exact line format.
611
+ *
612
+ * Pagination: the wire protocol carries no global `total`. Request further
613
+ * pages by incrementing `page` until a response contains no records.
614
+ */
615
+ async crawlUrls(uuid, opts) {
616
+ const statusHint = opts?.status ?? 'visited';
617
+ const page = opts?.page ?? 1;
618
+ const perPage = opts?.per_page ?? 100;
619
+ let response;
620
+ try {
621
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/urls`);
622
+ const params = { key: this.key };
623
+ if (opts?.status)
624
+ params.status = opts.status;
625
+ if (opts?.page !== undefined)
626
+ params.page = String(opts.page);
627
+ if (opts?.per_page !== undefined)
628
+ params.per_page = String(opts.per_page);
629
+ url.search = new URLSearchParams(params).toString();
630
+ response = await this.fetch({
631
+ url: url.toString(),
632
+ method: 'GET',
633
+ headers: {
634
+ 'user-agent': this.ua,
635
+ 'accept-encoding': 'gzip, deflate, br',
636
+ // text/plain is the canonical format; we also accept JSON because
637
+ // error envelopes come back as JSON regardless of the success type.
638
+ accept: 'text/plain, application/json',
639
+ },
640
+ });
641
+ }
642
+ catch (e) {
643
+ log.error('error', e);
644
+ throw e;
645
+ }
646
+ // Error envelopes are always JSON, even for text endpoints. Detect by
647
+ // content-type before consuming the body as text.
648
+ const ct = response.headers.get('content-type') ?? '';
649
+ if (ct.includes('application/json')) {
650
+ const data = (await response.json());
651
+ if ('error_id' in data || data.http_code !== undefined) {
652
+ this.throwCrawlerError(response, data);
653
+ }
654
+ // Unexpected: the server sent JSON on a success response for the text
655
+ // endpoint. Surface this as a client error so users see the mismatch
656
+ // instead of getting silent empty results.
657
+ throw new errors.ApiHttpClientError(`crawlUrls expected text/plain, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
658
+ }
659
+ const body = await response.text();
660
+ return CrawlerUrls.fromText(body, statusHint, page, perPage);
661
+ }
662
+ /**
663
+ * Get crawled content from a crawler job.
664
+ *
665
+ * Two modes:
666
+ *
667
+ * 1. **JSON mode** (default, `plain` omitted or false): returns a {@link CrawlerContents}
668
+ * with a `contents` map (URL → format → content) and pagination links. Useful for
669
+ * bulk retrieval. Honors `limit` (max 50, default 10) and `offset`.
670
+ *
671
+ * 2. **Plain mode** (`plain: true`): returns the raw content for a single URL/format
672
+ * as a `string`, with content-type matching the format. Requires `url`. Useful for
673
+ * piping markdown/text directly. **New in this SDK** (not in Python SDK as of 0.8.27).
674
+ *
675
+ * `GET /crawl/{uuid}/contents`
676
+ */
677
+ async crawlContents(uuid, opts) {
678
+ if (opts.plain && !opts.url) {
679
+ throw new errors.CrawlerConfigError('plain=true requires a single `url` argument');
680
+ }
681
+ let response;
682
+ try {
683
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents`);
684
+ // Note: the server query param is `formats` (plural), not `format`. The
685
+ // public docs say `format` but the actual server only accepts `formats`.
686
+ // We expose `format` (singular) as the SDK option since that's what users
687
+ // expect from the docs, and translate it here.
688
+ const params = { key: this.key, formats: opts.format };
689
+ if (opts.url)
690
+ params.url = opts.url;
691
+ if (opts.plain)
692
+ params.plain = 'true';
693
+ if (opts.limit !== undefined)
694
+ params.limit = String(opts.limit);
695
+ if (opts.offset !== undefined)
696
+ params.offset = String(opts.offset);
697
+ url.search = new URLSearchParams(params).toString();
698
+ response = await this.fetch({
699
+ url: url.toString(),
700
+ method: 'GET',
701
+ headers: {
702
+ 'user-agent': this.ua,
703
+ 'accept-encoding': 'gzip, deflate, br',
704
+ // In plain mode the server returns the raw content with a format-matching
705
+ // content-type (text/markdown, text/html, etc.); accept anything.
706
+ accept: opts.plain ? '*/*' : 'application/json',
707
+ },
708
+ });
709
+ }
710
+ catch (e) {
711
+ log.error('error', e);
712
+ throw e;
713
+ }
714
+ if (opts.plain) {
715
+ // Plain mode: server returns raw text. Error envelopes still come back as JSON,
716
+ // so detect that by content-type before reading the body as text.
717
+ const ct = response.headers.get('content-type') ?? '';
718
+ if (ct.includes('application/json')) {
719
+ const data = (await response.json());
720
+ if ('error_id' in data || data.http_code !== undefined) {
721
+ this.throwCrawlerError(response, data);
722
+ }
723
+ // JSON came back without an error envelope — caller asked for plain but server
724
+ // returned JSON anyway (e.g. format=json). Stringify so the return type is stable.
725
+ return JSON.stringify(data);
726
+ }
727
+ return await response.text();
728
+ }
729
+ const data = (await response.json());
730
+ if ('error_id' in data || data.http_code !== undefined) {
731
+ this.throwCrawlerError(response, data);
732
+ }
733
+ return new CrawlerContents(data);
734
+ }
735
+ /**
736
+ * Batch-retrieve crawled content for up to 100 URLs in one round-trip.
737
+ *
738
+ * `POST /crawl/{uuid}/contents/batch`
739
+ *
740
+ * The request body is a newline-separated list of URLs (`text/plain`). The response
741
+ * is a `multipart/related` (RFC 2387) document with one part per found URL. Each
742
+ * part has `Content-Type` (matching the format) and `Content-Location` (the URL).
743
+ *
744
+ * Returns a map of `url → format → content`. Formats not requested for a given URL
745
+ * are simply absent from its inner map.
746
+ */
747
+ async crawlContentsBatch(uuid, urls, formats) {
748
+ if (urls.length === 0) {
749
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one url');
750
+ }
751
+ if (urls.length > 100) {
752
+ throw new errors.CrawlerConfigError('crawlContentsBatch is limited to 100 urls per request');
753
+ }
754
+ if (formats.length === 0) {
755
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one format');
756
+ }
757
+ let response;
758
+ try {
759
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents/batch`);
760
+ url.search = new URLSearchParams({ key: this.key, formats: formats.join(',') }).toString();
761
+ response = await this.fetch({
762
+ url: url.toString(),
763
+ method: 'POST',
764
+ headers: {
765
+ 'user-agent': this.ua,
766
+ 'content-type': 'text/plain',
767
+ 'accept-encoding': 'gzip, deflate, br',
768
+ accept: 'multipart/related, application/json',
769
+ },
770
+ body: urls.join('\n'),
771
+ });
772
+ }
773
+ catch (e) {
774
+ log.error('error', e);
775
+ throw e;
776
+ }
777
+ const ct = response.headers.get('content-type') ?? '';
778
+ if (ct.includes('application/json')) {
779
+ // Error envelope
780
+ const data = (await response.json());
781
+ if ('error_id' in data || data.http_code !== undefined) {
782
+ this.throwCrawlerError(response, data);
783
+ }
784
+ throw new errors.ApiHttpClientError(`crawlContentsBatch expected multipart/related, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
785
+ }
786
+ const text = await response.text();
787
+ return parseMultipartRelated(text, ct, formats);
788
+ }
789
+ /**
790
+ * Download a crawler job's WARC or HAR artifact as raw bytes.
791
+ *
792
+ * `GET /crawl/{uuid}/artifact?type=warc|har`
793
+ *
794
+ * The SDK does NOT bundle WARC/HAR parsers — use a dedicated library (e.g. `warcio`
795
+ * on npm) to walk the records. The returned {@link CrawlerArtifact} provides a
796
+ * `save(path)` helper for the common case of writing the artifact to disk.
797
+ */
798
+ async crawlArtifact(uuid, type = 'warc') {
799
+ let response;
800
+ try {
801
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/artifact`);
802
+ url.search = new URLSearchParams({ key: this.key, type }).toString();
803
+ response = await this.fetch({
804
+ url: url.toString(),
805
+ method: 'GET',
806
+ headers: {
807
+ 'user-agent': this.ua,
808
+ // Accept the artifact's binary content type plus JSON for error envelopes
809
+ accept: type === 'har' ? 'application/json, application/octet-stream' : 'application/gzip, application/octet-stream',
810
+ },
811
+ });
812
+ }
813
+ catch (e) {
814
+ log.error('error', e);
815
+ throw e;
816
+ }
817
+ // Error envelope check (server returns JSON on errors regardless of artifact type)
818
+ const ct = response.headers.get('content-type') ?? '';
819
+ if (ct.includes('application/json') && type !== 'har') {
820
+ // For warc, JSON responses are always errors. For har, JSON IS the artifact —
821
+ // we need to peek at the body to distinguish.
822
+ const data = (await response.json());
823
+ if ('error_id' in data || data.http_code !== undefined) {
824
+ this.throwCrawlerError(response, data);
825
+ }
826
+ // Should not reach here for warc; treat as unexpected JSON.
827
+ throw new errors.ApiHttpClientError(`crawlArtifact(${type}) expected binary, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
828
+ }
829
+ const buf = new Uint8Array(await response.arrayBuffer());
830
+ // For HAR, the body IS JSON — but we still need to detect error envelopes
831
+ // (which set http_code or error_id at the top level of the JSON object).
832
+ if (type === 'har') {
833
+ try {
834
+ const text = new TextDecoder().decode(buf);
835
+ const parsed = JSON.parse(text);
836
+ if ('error_id' in parsed || parsed.http_code !== undefined) {
837
+ this.throwCrawlerError(response, parsed);
838
+ }
839
+ }
840
+ catch (e) {
841
+ // If JSON parse fails, the body is not an error envelope — treat as raw HAR bytes.
842
+ if (e instanceof errors.ScrapflyError)
843
+ throw e;
844
+ }
845
+ }
846
+ return new CrawlerArtifact(type, buf);
847
+ }
848
+ /**
849
+ * Cancel a running crawler job.
850
+ *
851
+ * `POST /crawl/{uuid}/cancel` — returns `true` on success. The endpoint
852
+ * is idempotent: cancelling a crawl that has already finished is a no-op
853
+ * and still returns success.
854
+ *
855
+ * Note: earlier versions of this SDK called `DELETE /crawl/{uuid}`, which
856
+ * is not a valid public route — that path silently 404'd against the
857
+ * public API. Fixed in 0.8.0 to use the correct documented endpoint.
858
+ */
859
+ async crawlCancel(uuid) {
860
+ let response;
861
+ try {
862
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/cancel`);
863
+ url.search = new URLSearchParams({ key: this.key }).toString();
864
+ response = await this.fetch({
865
+ url: url.toString(),
866
+ method: 'POST',
867
+ headers: {
868
+ 'user-agent': this.ua,
869
+ 'accept-encoding': 'gzip, deflate, br',
870
+ accept: 'application/json',
871
+ },
872
+ });
873
+ }
874
+ catch (e) {
875
+ log.error('error', e);
876
+ throw e;
877
+ }
878
+ // Empty body or JSON
879
+ const ct = response.headers.get('content-type') ?? '';
880
+ if (ct.includes('application/json')) {
881
+ const data = (await response.json());
882
+ if ('error_id' in data || data.http_code !== undefined) {
883
+ this.throwCrawlerError(response, data);
884
+ }
885
+ }
886
+ return response.ok;
887
+ }
888
+ // --- Cloud Browser ---
889
+ /**
890
+ * Get the WebSocket URL for a Cloud Browser session.
891
+ */
892
+ cloudBrowser(config) {
893
+ const browserConfig = config || new BrowserConfig();
894
+ return browserConfig.websocketUrl(this.key, this.cloudBrowserHost);
895
+ }
896
+ /**
897
+ * Call the Cloud Browser Unblock API.
898
+ */
899
+ async cloudBrowserUnblock(options) {
900
+ const proxyPoolMap = {
901
+ datacenter: 'public_datacenter_pool',
902
+ residential: 'public_residential_pool',
903
+ };
904
+ const jsonBody = { url: options.url };
905
+ if (options.proxy_pool)
906
+ jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
907
+ if (options.country)
908
+ jsonBody.country = options.country;
909
+ if (options.os)
910
+ jsonBody.os = options.os;
911
+ if (options.timeout)
912
+ jsonBody.timeout = options.timeout;
913
+ if (options.browser_timeout)
914
+ jsonBody.browser_timeout = options.browser_timeout;
915
+ if (options.headers)
916
+ jsonBody.headers = options.headers;
917
+ if (options.body)
918
+ jsonBody.body = options.body;
919
+ if (options.method)
920
+ jsonBody.method = options.method;
921
+ const url = new URL(this.cloudBrowserApiHost + '/unblock');
922
+ url.searchParams.set('key', this.key);
923
+ const response = await this.fetch({
924
+ url: url.toString(),
925
+ method: 'POST',
926
+ headers: {
927
+ 'content-type': 'application/json',
928
+ 'user-agent': this.ua,
929
+ },
930
+ body: JSON.stringify(jsonBody),
931
+ });
932
+ if (!response.ok) {
933
+ throw new Error(`Unblock failed: ${response.status} ${await response.text()}`);
934
+ }
935
+ return await response.json();
936
+ }
937
+ /**
938
+ * Stop a Cloud Browser session.
939
+ */
940
+ async cloudBrowserSessionStop(sessionId) {
941
+ const url = new URL(this.cloudBrowserApiHost + '/session/' + sessionId + '/stop');
942
+ url.searchParams.set('key', this.key);
943
+ const response = await this.fetch({
944
+ url: url.toString(),
945
+ method: 'POST',
946
+ headers: { 'user-agent': this.ua },
947
+ });
948
+ if (!response.ok) {
949
+ throw new Error(`Session stop failed: ${response.status} ${await response.text()}`);
950
+ }
951
+ }
952
+ /**
953
+ * List all browser extensions.
954
+ */
955
+ async cloudBrowserExtensionList() {
956
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
957
+ url.searchParams.set('key', this.key);
958
+ const response = await this.fetch({
959
+ url: url.toString(),
960
+ method: 'GET',
961
+ headers: { 'user-agent': this.ua },
962
+ });
963
+ if (!response.ok) {
964
+ throw new Error(`Extension list failed: ${response.status} ${await response.text()}`);
965
+ }
966
+ return await response.json();
967
+ }
968
+ /**
969
+ * Delete a browser extension.
970
+ */
971
+ async cloudBrowserExtensionDelete(extensionId) {
972
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
973
+ url.searchParams.set('key', this.key);
974
+ const response = await this.fetch({
975
+ url: url.toString(),
976
+ method: 'DELETE',
977
+ headers: { 'user-agent': this.ua },
978
+ });
979
+ if (!response.ok) {
980
+ throw new Error(`Extension delete failed: ${response.status} ${await response.text()}`);
981
+ }
982
+ return await response.json();
983
+ }
984
+ /**
985
+ * Get details of a specific browser extension.
986
+ */
987
+ async cloudBrowserExtensionGet(extensionId) {
988
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
989
+ url.searchParams.set('key', this.key);
990
+ const response = await this.fetch({
991
+ url: url.toString(),
992
+ method: 'GET',
993
+ headers: { 'user-agent': this.ua },
994
+ });
995
+ if (!response.ok) {
996
+ throw new Error(`Extension get failed: ${response.status} ${await response.text()}`);
997
+ }
998
+ return await response.json();
999
+ }
1000
+ /**
1001
+ * Upload a browser extension from a local file (.zip or .crx).
1002
+ * Pass a file path — the file is read and sent as multipart/form-data.
1003
+ */
1004
+ async cloudBrowserExtensionUpload(filePath) {
1005
+ const fileBytes = readFileSync(filePath);
1006
+ const fileName = filePath.split('/').pop() || filePath.split('\\').pop() || 'extension.zip';
1007
+ const boundary = '----ScrapflyBoundary' + Date.now();
1008
+ const encoder = new TextEncoder();
1009
+ const header = encoder.encode(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: application/octet-stream\r\n\r\n`);
1010
+ const footer = encoder.encode(`\r\n--${boundary}--\r\n`);
1011
+ const body = new Uint8Array(header.length + fileBytes.length + footer.length);
1012
+ body.set(header, 0);
1013
+ body.set(fileBytes, header.length);
1014
+ body.set(footer, header.length + fileBytes.length);
1015
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1016
+ url.searchParams.set('key', this.key);
1017
+ const response = await this.fetch({
1018
+ url: url.toString(),
1019
+ method: 'POST',
1020
+ headers: {
1021
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
1022
+ 'user-agent': this.ua,
1023
+ },
1024
+ body: body,
1025
+ });
1026
+ if (!response.ok) {
1027
+ throw new Error(`Extension upload failed: ${response.status} ${await response.text()}`);
1028
+ }
1029
+ return await response.json();
1030
+ }
1031
+ /**
1032
+ * Install a browser extension from a URL (.crx file).
1033
+ * URL-based extensions auto-update on each browser session start.
1034
+ */
1035
+ async cloudBrowserExtensionUploadFromUrl(extensionUrl) {
1036
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1037
+ url.searchParams.set('key', this.key);
1038
+ const response = await this.fetch({
1039
+ url: url.toString(),
1040
+ method: 'POST',
1041
+ headers: {
1042
+ 'content-type': 'application/json',
1043
+ 'user-agent': this.ua,
1044
+ },
1045
+ body: JSON.stringify({ extension_url: extensionUrl }),
1046
+ });
1047
+ if (!response.ok) {
1048
+ throw new Error(`Extension upload from URL failed: ${response.status} ${await response.text()}`);
1049
+ }
1050
+ return await response.json();
1051
+ }
1052
+ /**
1053
+ * Download a debug session recording video.
1054
+ * Returns the video as an ArrayBuffer (stream from server).
1055
+ */
1056
+ async cloudBrowserVideo(runId) {
1057
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/video');
1058
+ url.searchParams.set('key', this.key);
1059
+ const response = await this.fetch({
1060
+ url: url.toString(),
1061
+ method: 'GET',
1062
+ headers: { 'user-agent': this.ua },
1063
+ });
1064
+ if (!response.ok) {
1065
+ throw new Error(`Video download failed: ${response.status} ${await response.text()}`);
1066
+ }
1067
+ const filename = runId + '.webm';
1068
+ return { data: await response.arrayBuffer(), filename };
1069
+ }
1070
+ /**
1071
+ * Get playback info for a debug session recording.
1072
+ */
1073
+ async cloudBrowserPlayback(runId) {
1074
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/playback');
1075
+ url.searchParams.set('key', this.key);
1076
+ const response = await this.fetch({
1077
+ url: url.toString(),
1078
+ method: 'GET',
1079
+ headers: { 'user-agent': this.ua },
1080
+ });
1081
+ if (!response.ok) {
1082
+ throw new Error(`Playback get failed: ${response.status} ${await response.text()}`);
1083
+ }
1084
+ return await response.json();
1085
+ }
1086
+ /**
1087
+ * List all running Cloud Browser sessions.
1088
+ */
1089
+ async cloudBrowserSessions() {
1090
+ const url = new URL(this.cloudBrowserApiHost + '/sessions');
1091
+ url.searchParams.set('key', this.key);
1092
+ const response = await this.fetch({
1093
+ url: url.toString(),
1094
+ method: 'GET',
1095
+ headers: { 'user-agent': this.ua },
1096
+ });
1097
+ if (!response.ok) {
1098
+ throw new Error(`Sessions list failed: ${response.status} ${await response.text()}`);
1099
+ }
1100
+ return await response.json();
1101
+ }
1102
+ }
1103
+ // ---------------------------------------------------------------------------
1104
+ // multipart/related parser
1105
+ // ---------------------------------------------------------------------------
1106
+ //
1107
+ // Tiny inline parser for the response of `POST /crawl/{uuid}/contents/batch`.
1108
+ // Avoids pulling in a multipart npm dep so the SDK stays dependency-free.
1109
+ //
1110
+ // Each part has at minimum a `Content-Location: <url>` header and a body. The
1111
+ // `Content-Type` may also be set, indicating the format. We map URL → format → body
1112
+ // using the `formats` argument as the inferred-format fallback when the part has
1113
+ // no `Content-Type`.
1114
+ function parseMultipartRelated(body, contentType, formats) {
1115
+ const boundaryMatch = contentType.match(/boundary=(?:"([^"]+)"|([^;\s]+))/);
1116
+ if (!boundaryMatch) {
1117
+ throw new errors.ApiHttpClientError(`crawlContentsBatch: response has no multipart boundary in content-type "${contentType}"`);
1118
+ }
1119
+ const boundary = boundaryMatch[1] ?? boundaryMatch[2];
1120
+ const delimiter = `--${boundary}`;
1121
+ const result = {};
1122
+ // Split on the delimiter; first segment is the preamble (ignored), last is the
1123
+ // closing `--` (also ignored).
1124
+ const segments = body.split(delimiter);
1125
+ for (let i = 1; i < segments.length; i++) {
1126
+ let segment = segments[i];
1127
+ // Strip leading CRLF after the boundary
1128
+ if (segment.startsWith('\r\n'))
1129
+ segment = segment.slice(2);
1130
+ else if (segment.startsWith('\n'))
1131
+ segment = segment.slice(1);
1132
+ // The closing boundary is `--{boundary}--`; segment starts with `--` then EOL
1133
+ if (segment.startsWith('--'))
1134
+ break;
1135
+ // Trim trailing CRLF before the next boundary
1136
+ if (segment.endsWith('\r\n'))
1137
+ segment = segment.slice(0, -2);
1138
+ else if (segment.endsWith('\n'))
1139
+ segment = segment.slice(0, -1);
1140
+ // Header/body split: first blank line
1141
+ const headerEnd = segment.indexOf('\r\n\r\n');
1142
+ const altHeaderEnd = headerEnd === -1 ? segment.indexOf('\n\n') : headerEnd;
1143
+ if (altHeaderEnd === -1)
1144
+ continue;
1145
+ const headersRaw = segment.slice(0, altHeaderEnd);
1146
+ const partBody = segment.slice(altHeaderEnd + (headerEnd === -1 ? 2 : 4));
1147
+ // Parse headers
1148
+ let url;
1149
+ let format;
1150
+ for (const line of headersRaw.split(/\r?\n/)) {
1151
+ const colon = line.indexOf(':');
1152
+ if (colon === -1)
1153
+ continue;
1154
+ const name = line.slice(0, colon).trim().toLowerCase();
1155
+ const value = line.slice(colon + 1).trim();
1156
+ if (name === 'content-location')
1157
+ url = value;
1158
+ else if (name === 'content-type')
1159
+ format = inferFormatFromContentType(value);
1160
+ }
1161
+ if (!url)
1162
+ continue;
1163
+ if (!format) {
1164
+ // Fall back to the first requested format if the part has no content-type
1165
+ format = formats[0];
1166
+ }
1167
+ if (!result[url])
1168
+ result[url] = {};
1169
+ result[url][format] = partBody;
1170
+ }
1171
+ return result;
1172
+ }
1173
+ function inferFormatFromContentType(ct) {
1174
+ const lc = ct.toLowerCase().split(';')[0].trim();
1175
+ if (lc === 'text/html')
1176
+ return 'html';
1177
+ if (lc === 'text/markdown')
1178
+ return 'markdown';
1179
+ if (lc === 'text/plain')
1180
+ return 'text';
1181
+ if (lc === 'application/json')
1182
+ return 'json';
1183
+ return undefined;
403
1184
  }