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