scrapfly-sdk 0.11.0 → 0.12.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 (68) hide show
  1. package/README.md +36 -3
  2. package/esm/browserconfig.d.ts +37 -5
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +51 -3
  5. package/esm/client.d.ts +124 -9
  6. package/esm/client.d.ts.map +1 -1
  7. package/esm/client.js +346 -50
  8. package/esm/crawl.d.ts +58 -1
  9. package/esm/crawl.d.ts.map +1 -1
  10. package/esm/crawl.js +55 -0
  11. package/esm/crawlerconfig.d.ts +41 -3
  12. package/esm/crawlerconfig.d.ts.map +1 -1
  13. package/esm/crawlerconfig.js +93 -2
  14. package/esm/crawlerresult.d.ts +335 -2
  15. package/esm/crawlerresult.d.ts.map +1 -1
  16. package/esm/crawlerresult.js +367 -1
  17. package/esm/errors.d.ts +12 -0
  18. package/esm/errors.d.ts.map +1 -1
  19. package/esm/errors.js +11 -0
  20. package/esm/main.d.ts +4 -4
  21. package/esm/main.d.ts.map +1 -1
  22. package/esm/main.js +3 -3
  23. package/esm/scrapeconfig.d.ts +36 -0
  24. package/esm/scrapeconfig.d.ts.map +1 -1
  25. package/esm/scrapeconfig.js +44 -2
  26. package/esm/types.d.ts.map +1 -1
  27. package/esm/webhookserver.d.ts +33 -15
  28. package/esm/webhookserver.d.ts.map +1 -1
  29. package/esm/webhookserver.js +197 -38
  30. package/package.json +1 -1
  31. package/script/browserconfig.d.ts +37 -5
  32. package/script/browserconfig.d.ts.map +1 -1
  33. package/script/browserconfig.js +51 -3
  34. package/script/client.d.ts +124 -9
  35. package/script/client.d.ts.map +1 -1
  36. package/script/client.js +345 -49
  37. package/script/crawl.d.ts +58 -1
  38. package/script/crawl.d.ts.map +1 -1
  39. package/script/crawl.js +55 -0
  40. package/script/crawlerconfig.d.ts +41 -3
  41. package/script/crawlerconfig.d.ts.map +1 -1
  42. package/script/crawlerconfig.js +94 -3
  43. package/script/crawlerresult.d.ts +335 -2
  44. package/script/crawlerresult.d.ts.map +1 -1
  45. package/script/crawlerresult.js +374 -2
  46. package/script/errors.d.ts +12 -0
  47. package/script/errors.d.ts.map +1 -1
  48. package/script/errors.js +12 -1
  49. package/script/main.d.ts +4 -4
  50. package/script/main.d.ts.map +1 -1
  51. package/script/main.js +9 -2
  52. package/script/scrapeconfig.d.ts +36 -0
  53. package/script/scrapeconfig.d.ts.map +1 -1
  54. package/script/scrapeconfig.js +44 -2
  55. package/script/types.d.ts.map +1 -1
  56. package/script/webhookserver.d.ts +33 -15
  57. package/script/webhookserver.d.ts.map +1 -1
  58. package/script/webhookserver.js +197 -38
  59. package/src/browserconfig.ts +52 -4
  60. package/src/client.ts +413 -51
  61. package/src/crawl.ts +74 -0
  62. package/src/crawlerconfig.ts +115 -5
  63. package/src/crawlerresult.ts +566 -3
  64. package/src/errors.ts +12 -0
  65. package/src/main.ts +25 -2
  66. package/src/scrapeconfig.ts +54 -2
  67. package/src/types.ts +0 -1
  68. package/src/webhookserver.ts +235 -39
package/script/client.js CHANGED
@@ -31,9 +31,21 @@ const errors = __importStar(require("./errors.js"));
31
31
  const browserconfig_js_1 = require("./browserconfig.js");
32
32
  const result_js_1 = require("./result.js");
33
33
  const logger_js_1 = require("./logger.js");
34
+ const crawlerconfig_js_1 = require("./crawlerconfig.js");
34
35
  const crawlerresult_js_1 = require("./crawlerresult.js");
35
36
  const monitoringconfig_js_1 = require("./monitoringconfig.js");
36
37
  const schedule_js_1 = require("./schedule.js");
38
+ /** ERR::<RESOURCE>::* → error-class taxonomy. */
39
+ const RESOURCE_TO_ERROR = {
40
+ SCRAPE: errors.ScrapflyScrapeError,
41
+ WEBHOOK: errors.ScrapflyWebhookError,
42
+ PROXY: errors.ScrapflyProxyError,
43
+ SCHEDULE: errors.ScrapflyScheduleError,
44
+ ASP: errors.ScrapflyAspError,
45
+ SESSION: errors.ScrapflySessionError,
46
+ THROTTLE: errors.ScrapflyThrottleError,
47
+ CRAWLER: errors.ScrapflyCrawlerError,
48
+ };
37
49
  /**
38
50
  * Main entry point for the Scrapfly SDK.
39
51
  *
@@ -148,21 +160,9 @@ class ScrapflyClient {
148
160
  case 429:
149
161
  return new errors.TooManyRequests(message, args);
150
162
  }
151
- switch (args.resource) {
152
- case 'SCRAPE':
153
- return new errors.ScrapflyScrapeError(message, args);
154
- case 'WEBHOOK':
155
- return new errors.ScrapflyWebhookError(message, args);
156
- case 'PROXY':
157
- return new errors.ScrapflyProxyError(message, args);
158
- case 'SCHEDULE':
159
- return new errors.ScrapflyScheduleError(message, args);
160
- case 'ASP':
161
- return new errors.ScrapflyAspError(message, args);
162
- case 'SESSION':
163
- return new errors.ScrapflySessionError(message, args);
164
- case 'CRAWLER':
165
- return new errors.ScrapflyCrawlerError(message, args);
163
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
164
+ if (ResourceError) {
165
+ return new ResourceError(message, args);
166
166
  }
167
167
  if (args.resource) {
168
168
  return new errors.ApiHttpClientError(message, args);
@@ -177,25 +177,48 @@ class ScrapflyClient {
177
177
  return new errors.UpstreamHttpServerError(message, args);
178
178
  }
179
179
  }
180
- switch (args.resource) {
181
- case 'SCRAPE':
182
- return new errors.ScrapflyScrapeError(message, args);
183
- case 'WEBHOOK':
184
- return new errors.ScrapflyWebhookError(message, args);
185
- case 'PROXY':
186
- return new errors.ScrapflyProxyError(message, args);
187
- case 'SCHEDULE':
188
- return new errors.ScrapflyScheduleError(message, args);
189
- case 'ASP':
190
- return new errors.ScrapflyAspError(message, args);
191
- case 'SESSION':
192
- return new errors.ScrapflySessionError(message, args);
193
- case 'CRAWLER':
194
- return new errors.ScrapflyCrawlerError(message, args);
180
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
181
+ if (ResourceError) {
182
+ return new ResourceError(message, args);
195
183
  }
196
184
  }
197
185
  return new errors.ScrapflyError(message, args);
198
186
  }
187
+ /** Build the typed per-part error for an API-generated batch error body. */
188
+ batchApiErrorPartToError(parsed, partHeaders) {
189
+ const code = typeof parsed.code === 'string' ? parsed.code : '';
190
+ const message = String(parsed.message ?? parsed.reason ?? 'API error');
191
+ const httpStatusCode = typeof parsed.http_code === 'number'
192
+ ? parsed.http_code
193
+ : parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
194
+ const isRetryable = parsed.retryable === true;
195
+ let documentationUrl;
196
+ if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
197
+ const values = Object.values(parsed.links);
198
+ if (values.length)
199
+ documentationUrl = values[0];
200
+ }
201
+ const args = {
202
+ code,
203
+ http_status_code: httpStatusCode,
204
+ is_retryable: isRetryable,
205
+ resource: code ? code.split('::')[1] : null,
206
+ documentation_url: documentationUrl,
207
+ };
208
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
209
+ if (ResourceError) {
210
+ return new ResourceError(message, args);
211
+ }
212
+ switch (httpStatusCode) {
213
+ case 401:
214
+ return new errors.BadApiKeyError(message, args);
215
+ case 429:
216
+ return new errors.TooManyRequests(message, args);
217
+ }
218
+ return httpStatusCode >= 500
219
+ ? new errors.ApiHttpServerError(message, args)
220
+ : new errors.ApiHttpClientError(message, args);
221
+ }
199
222
  /**
200
223
  * Handle clob and blob large objects
201
224
  */
@@ -716,6 +739,18 @@ class ScrapflyClient {
716
739
  ];
717
740
  continue;
718
741
  }
742
+ // API-generated error parts carry status >= 400 and an error body
743
+ // instead of the scrape envelope — surface them as typed errors.
744
+ const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
745
+ if (partStatus >= 400 &&
746
+ parsed &&
747
+ typeof parsed === 'object' &&
748
+ !Array.isArray(parsed) &&
749
+ !('result' in parsed) &&
750
+ !('config' in parsed)) {
751
+ yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
752
+ continue;
753
+ }
719
754
  try {
720
755
  const result = new result_js_1.ScrapeResult({
721
756
  config: parsed.config,
@@ -916,7 +951,7 @@ class ScrapflyClient {
916
951
  if (urlList !== undefined) {
917
952
  // Strip url_list from the JSON config — the URLs go through the
918
953
  // 'urls' multipart part instead, which the API gateway streams
919
- // straight through to the scrape engine.
954
+ // straight through to the scraping backend.
920
955
  delete params.url_list;
921
956
  const form = new FormData();
922
957
  const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
@@ -1283,6 +1318,252 @@ class ScrapflyClient {
1283
1318
  }
1284
1319
  return response.ok;
1285
1320
  }
1321
+ /**
1322
+ * Run one refresh of an existing crawl immediately, without waiting for the
1323
+ * next scheduled period.
1324
+ *
1325
+ * `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
1326
+ * same `crawler_uuid`, same artifacts, same search index. Only pages whose
1327
+ * content actually changed are re-indexed and pages that disappeared are
1328
+ * dropped, so everything already pointing at this crawl keeps working.
1329
+ *
1330
+ * A refresh bills the pages it re-scrapes, exactly like the original crawl.
1331
+ * What unchanged pages save is the embedding and the index write.
1332
+ *
1333
+ * The call returns as soon as the run is accepted; poll `crawlStatus` or
1334
+ * `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
1335
+ * starts a second re-scrape of the whole site.
1336
+ */
1337
+ async crawlRefreshNow(uuid) {
1338
+ if (!uuid) {
1339
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1340
+ }
1341
+ let response;
1342
+ try {
1343
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1344
+ url.search = new URLSearchParams({ key: this.key }).toString();
1345
+ // One attempt: the server may have accepted the billable refresh even
1346
+ // when its response is lost or replaced by a gateway error.
1347
+ response = await this.fetch({
1348
+ url: url.toString(),
1349
+ method: 'POST',
1350
+ headers: {
1351
+ 'user-agent': this.ua,
1352
+ 'accept-encoding': 'gzip, deflate, br',
1353
+ accept: 'application/json',
1354
+ },
1355
+ }, 1);
1356
+ }
1357
+ catch (e) {
1358
+ logger_js_1.log.error('error', e);
1359
+ throw e;
1360
+ }
1361
+ const data = (await response.json());
1362
+ if ('error_id' in data || data.http_code !== undefined) {
1363
+ this.throwCrawlerError(response, data);
1364
+ }
1365
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data);
1366
+ }
1367
+ /**
1368
+ * Change the refresh schedule of an existing crawl.
1369
+ *
1370
+ * `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
1371
+ * turning a crawl off keeps its interval for when it is turned back on.
1372
+ *
1373
+ * Turning refresh on for a crawl started without it is allowed: the crawl
1374
+ * already holds the URL index a refresh walks.
1375
+ */
1376
+ async crawlRefreshSettings(uuid, settings) {
1377
+ if (!uuid) {
1378
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1379
+ }
1380
+ if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
1381
+ throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
1382
+ }
1383
+ if (settings.interval_seconds !== undefined &&
1384
+ (settings.interval_seconds < crawlerconfig_js_1.REFRESH_MIN_INTERVAL || settings.interval_seconds > crawlerconfig_js_1.REFRESH_MAX_INTERVAL)) {
1385
+ throw new errors.ScrapflyCrawlerError(`interval_seconds must be between ${crawlerconfig_js_1.REFRESH_MIN_INTERVAL} and ${crawlerconfig_js_1.REFRESH_MAX_INTERVAL} seconds`);
1386
+ }
1387
+ // Wire keys are the ones POST /crawl already takes, so a crawl body and a
1388
+ // later PATCH name the same things. The enabled/interval_seconds spelling
1389
+ // belongs to the state block this call answers with, not to its request;
1390
+ // the API decodes the body with unknown fields rejected.
1391
+ const payload = {};
1392
+ if (settings.enabled !== undefined)
1393
+ payload.refresh = settings.enabled;
1394
+ if (settings.interval_seconds !== undefined)
1395
+ payload.refresh_interval = settings.interval_seconds;
1396
+ let response;
1397
+ try {
1398
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1399
+ url.search = new URLSearchParams({ key: this.key }).toString();
1400
+ response = await this.fetch({
1401
+ url: url.toString(),
1402
+ method: 'PATCH',
1403
+ headers: {
1404
+ 'user-agent': this.ua,
1405
+ 'content-type': 'application/json',
1406
+ 'accept-encoding': 'gzip, deflate, br',
1407
+ accept: 'application/json',
1408
+ },
1409
+ body: JSON.stringify(payload),
1410
+ });
1411
+ }
1412
+ catch (e) {
1413
+ logger_js_1.log.error('error', e);
1414
+ throw e;
1415
+ }
1416
+ const data = (await response.json());
1417
+ if ('error_id' in data || data.http_code !== undefined) {
1418
+ this.throwCrawlerError(response, data);
1419
+ }
1420
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data);
1421
+ }
1422
+ /**
1423
+ * Read a crawl's refresh timeline, newest last.
1424
+ *
1425
+ * `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
1426
+ * runs; older rows are trimmed rather than paged, because the timeline
1427
+ * exists to show recent activity.
1428
+ */
1429
+ async crawlRefreshHistory(uuid, opts) {
1430
+ if (!uuid) {
1431
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1432
+ }
1433
+ let response;
1434
+ try {
1435
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
1436
+ const params = { key: this.key };
1437
+ if (opts?.limit !== undefined)
1438
+ params.limit = String(opts.limit);
1439
+ url.search = new URLSearchParams(params).toString();
1440
+ response = await this.fetch({
1441
+ url: url.toString(),
1442
+ method: 'GET',
1443
+ headers: {
1444
+ 'user-agent': this.ua,
1445
+ 'accept-encoding': 'gzip, deflate, br',
1446
+ accept: 'application/json',
1447
+ },
1448
+ });
1449
+ }
1450
+ catch (e) {
1451
+ logger_js_1.log.error('error', e);
1452
+ throw e;
1453
+ }
1454
+ const data = (await response.json());
1455
+ if ('error_id' in data || data.http_code !== undefined) {
1456
+ this.throwCrawlerError(response, data);
1457
+ }
1458
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data).history ?? [];
1459
+ }
1460
+ /**
1461
+ * Search across the search indexes of one or more crawls.
1462
+ *
1463
+ * `POST /crawl/search`: the collection endpoint is the real API and
1464
+ * {@link crawl.Crawl.search} is sugar over a one-element list so the two
1465
+ * cannot drift.
1466
+ *
1467
+ * Only crawls started with `search: true` whose index reached `READY` or
1468
+ * `PARTIAL` contribute. The rest come back in `skipped` with a reason and
1469
+ * never fail the call, so inspect `skipped` before concluding a crawl had
1470
+ * no match.
1471
+ */
1472
+ async crawlSearch(crawlIds, query, opts) {
1473
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1474
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1475
+ }
1476
+ if (!query) {
1477
+ throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
1478
+ }
1479
+ const payload = { query, crawl_ids: crawlIds };
1480
+ if (opts?.limit !== undefined)
1481
+ payload.limit = opts.limit;
1482
+ if (opts?.mode !== undefined)
1483
+ payload.mode = opts.mode;
1484
+ if (opts?.filters !== undefined)
1485
+ payload.filters = opts.filters;
1486
+ if (opts?.cursor !== undefined)
1487
+ payload.cursor = opts.cursor;
1488
+ let response;
1489
+ try {
1490
+ const url = new URL(`${this.HOST}/crawl/search`);
1491
+ url.search = new URLSearchParams({ key: this.key }).toString();
1492
+ response = await this.fetch({
1493
+ url: url.toString(),
1494
+ method: 'POST',
1495
+ headers: {
1496
+ 'user-agent': this.ua,
1497
+ 'content-type': 'application/json',
1498
+ 'accept-encoding': 'gzip, deflate, br',
1499
+ accept: 'application/json',
1500
+ },
1501
+ body: JSON.stringify(payload),
1502
+ });
1503
+ }
1504
+ catch (e) {
1505
+ logger_js_1.log.error('error', e);
1506
+ throw e;
1507
+ }
1508
+ const data = (await response.json());
1509
+ if ('error_id' in data || data.http_code !== undefined) {
1510
+ this.throwCrawlerError(response, data);
1511
+ }
1512
+ return new crawlerresult_js_1.CrawlerSearchResponse(data);
1513
+ }
1514
+ /**
1515
+ * Ask a question answered from the content of one or more crawls, streaming
1516
+ * the answer as it is generated.
1517
+ *
1518
+ * `POST /crawl/prompt`: the collection endpoint is the real API and
1519
+ * {@link crawl.Crawl.prompt} is sugar over a one-element list.
1520
+ *
1521
+ * Yields `source` frames, then `token` frames, then one `done`. An
1522
+ * `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
1523
+ * yielded, and can arrive after tokens were already yielded because
1524
+ * generation fails mid-stream.
1525
+ *
1526
+ * Consume with `for await`; abandoning the iterator early cancels the body.
1527
+ *
1528
+ * Do not consume this with `EventSource`: it reconnects on close and would
1529
+ * silently re-run the whole fan-out and generation.
1530
+ */
1531
+ async *crawlPrompt(crawlIds, prompt, opts) {
1532
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1533
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1534
+ }
1535
+ if (!prompt) {
1536
+ throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
1537
+ }
1538
+ const generation = { stream: true };
1539
+ if (opts?.model !== undefined)
1540
+ generation.model = opts.model;
1541
+ const payload = { prompt, crawl_ids: crawlIds, generation };
1542
+ if (opts?.search !== undefined)
1543
+ payload.search = opts.search;
1544
+ const url = new URL(`${this.HOST}/crawl/prompt`);
1545
+ url.search = new URLSearchParams({ key: this.key }).toString();
1546
+ // One attempt only: the request runs a fan-out and a generation, both
1547
+ // billable, so a retry doubles the bill.
1548
+ const response = await this.fetch({
1549
+ url: url.toString(),
1550
+ method: 'POST',
1551
+ headers: {
1552
+ 'user-agent': this.ua,
1553
+ 'content-type': 'application/json',
1554
+ accept: 'text/event-stream',
1555
+ },
1556
+ body: JSON.stringify(payload),
1557
+ }, 1);
1558
+ if (!response.ok) {
1559
+ const data = (await response.json().catch(() => ({})));
1560
+ this.throwCrawlerError(response, data);
1561
+ }
1562
+ if (response.body === null) {
1563
+ throw new errors.ScrapflyCrawlerError('prompt response carried no body');
1564
+ }
1565
+ yield* (0, crawlerresult_js_1.parseCrawlerPromptStream)(response.body);
1566
+ }
1286
1567
  // --- Cloud Browser ---
1287
1568
  /**
1288
1569
  * Get the WebSocket URL for a Cloud Browser session.
@@ -1297,39 +1578,45 @@ class ScrapflyClient {
1297
1578
  }
1298
1579
  /**
1299
1580
  * Return the deterministic project salt for this client's api_key. Matches
1300
- * the `X-Browser-Project-Salt` response header returned on a successful
1301
- * Cloud Browser WebSocket upgrade.
1581
+ * the `X-Browser-Project-Salt` response header returned on VNC-enabled
1582
+ * Cloud Browser upgrades, where the salt is also the VNC password prefix.
1302
1583
  */
1303
1584
  async cloudBrowserProjectSalt() {
1304
1585
  return browserconfig_js_1.BrowserConfig.projectSalt(this.key);
1305
1586
  }
1587
+ /**
1588
+ * Return the password a native VNC client must type to attach to a session
1589
+ * created with `config`: `<projectSalt>-<vnc_password>`.
1590
+ *
1591
+ * Copy this value into your VNC client when connecting to the TCP endpoint
1592
+ * (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
1593
+ * `vnc_password` instead.
1594
+ */
1595
+ async cloudBrowserVncPassword(config) {
1596
+ return config.vncClientPassword(this.key);
1597
+ }
1306
1598
  /**
1307
1599
  * Call the Cloud Browser Unblock API.
1600
+ *
1601
+ * Unblock always uses a residential proxy (no proxy pool selection) and
1602
+ * always performs a GET — the endpoint's purpose is to harvest cookies /
1603
+ * clearance tokens via an ASP-bypass navigation, not to proxy arbitrary
1604
+ * HTTP requests.
1308
1605
  */
1309
1606
  async cloudBrowserUnblock(options) {
1310
- const proxyPoolMap = {
1311
- datacenter: 'public_datacenter_pool',
1312
- residential: 'public_residential_pool',
1313
- };
1314
1607
  const jsonBody = { url: options.url };
1315
- if (options.proxy_pool)
1316
- jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
1317
1608
  if (options.country)
1318
1609
  jsonBody.country = options.country;
1319
1610
  if (options.os)
1320
1611
  jsonBody.os = options.os;
1321
1612
  if (options.browser_brand)
1322
1613
  jsonBody.browser_brand = options.browser_brand;
1614
+ if (options.session)
1615
+ jsonBody.session = options.session;
1323
1616
  if (options.timeout)
1324
1617
  jsonBody.timeout = options.timeout;
1325
1618
  if (options.browser_timeout)
1326
1619
  jsonBody.browser_timeout = options.browser_timeout;
1327
- if (options.headers)
1328
- jsonBody.headers = options.headers;
1329
- if (options.body)
1330
- jsonBody.body = options.body;
1331
- if (options.method)
1332
- jsonBody.method = options.method;
1333
1620
  if (options.enable_mcp !== undefined)
1334
1621
  jsonBody.enable_mcp = options.enable_mcp;
1335
1622
  if (options.debug !== undefined)
@@ -1466,12 +1753,12 @@ class ScrapflyClient {
1466
1753
  return await response.json();
1467
1754
  }
1468
1755
  // ----- Cloud Browser Credential Vault -------------------------------------
1469
- // Server contract documented at apps/scrapfly/api/scrapfly-api/pkg/vault/.
1756
+ // Server contract documented in the Vault API reference.
1470
1757
  //
1471
1758
  // SECURITY: the vault key is the customer-held secret that decrypts every
1472
1759
  // item in the vault. The server emits it ONCE on POST /vault and POST
1473
1760
  // /vault/{id}/rotate; never log it, never include it in error messages,
1474
- // never put it in a breadcrumb. See agent_secret_tokenization_boundary.md.
1761
+ // never put it in a breadcrumb, and never echo it back to a caller.
1475
1762
  /**
1476
1763
  * Create a new Cloud Browser Credential Vault. The response contains a
1477
1764
  * one-time `key` that the caller MUST save locally — the server cannot
@@ -1790,7 +2077,12 @@ class ScrapflyClient {
1790
2077
  // pause/resume/execute methods work regardless of kind.
1791
2078
  // -------------------------------------------------------------------------
1792
2079
  /** Create a Web Scraping API schedule. `scrape_config` is the same shape
1793
- * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). */
2080
+ * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
2081
+ * forwarded to the API verbatim, so its keys are wire keys, not the SDK
2082
+ * option names. The anti-bot bypass may be spelled either way here: the API
2083
+ * folds `unblocker` into `asp` on the STORED config, with the same precedence
2084
+ * the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
2085
+ * absent, `null` or `""`), so both names reach the replayed scrape. */
1794
2086
  async createScrapeSchedule(scrapeConfig, request) {
1795
2087
  return await this.scheduleRequest('POST', '/scrape/schedules', undefined, this.buildCreateBody('scrape_config', scrapeConfig, request));
1796
2088
  }
@@ -1798,7 +2090,11 @@ class ScrapflyClient {
1798
2090
  async createScreenshotSchedule(screenshotConfig, request) {
1799
2091
  return await this.scheduleRequest('POST', '/screenshot/schedules', undefined, this.buildCreateBody('screenshot_config', screenshotConfig, request));
1800
2092
  }
1801
- /** Create a Crawler API schedule. */
2093
+ /** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
2094
+ * its keys are wire keys, not the SDK option names. As with
2095
+ * `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
2096
+ * `unblocker`: the API folds the alias into `asp` on the stored config before
2097
+ * it is ever replayed. */
1802
2098
  async createCrawlerSchedule(crawlerConfig, request) {
1803
2099
  return await this.scheduleRequest('POST', '/crawl/schedules', undefined, this.buildCreateBody('crawler_config', crawlerConfig, request));
1804
2100
  }
package/script/crawl.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ScrapflyClient } from './client.js';
2
2
  import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
3
- import type { CrawlerArtifact, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
3
+ import type { CrawlerArtifact, CrawlerPromptEvent, CrawlerRefreshEntry, CrawlerRefreshState, CrawlerSearchMode, CrawlerSearchResponse, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
4
4
  /**
5
5
  * High-level fluent wrapper around a single crawler job lifecycle.
6
6
  *
@@ -96,6 +96,63 @@ export declare class Crawl {
96
96
  page?: number;
97
97
  per_page?: number;
98
98
  }): Promise<CrawlerUrls>;
99
+ /**
100
+ * Search this crawl's index.
101
+ *
102
+ * Sugar over `client.crawlSearch([uuid], ...)`. The cross-crawl call is the
103
+ * real endpoint; both share its implementation so single and multi-crawl
104
+ * search cannot drift.
105
+ *
106
+ * Requires the crawl to have been started with `search: true` and its index
107
+ * to have reached `READY`/`PARTIAL`; poll `CrawlerStatus.search` or
108
+ * subscribe to the `crawler_search_ready` webhook. An index that is not
109
+ * ready yet is reported in the response's `skipped` list, not as an error.
110
+ */
111
+ search(query: string, opts?: {
112
+ limit?: number;
113
+ mode?: CrawlerSearchMode;
114
+ filters?: Record<string, any>;
115
+ cursor?: string;
116
+ }): Promise<CrawlerSearchResponse>;
117
+ /**
118
+ * Ask a question answered from this crawl's content.
119
+ *
120
+ * Sugar over `client.crawlPrompt([uuid], ...)`; yields the same frames.
121
+ */
122
+ prompt(prompt: string, opts?: {
123
+ search?: {
124
+ limit?: number;
125
+ mode?: CrawlerSearchMode;
126
+ filters?: Record<string, any>;
127
+ };
128
+ model?: string;
129
+ }): AsyncGenerator<CrawlerPromptEvent, void, undefined>;
130
+ /**
131
+ * Re-scrape this crawl's URLs in place, right now.
132
+ *
133
+ * Sugar over `client.crawlRefreshNow(uuid)`. The crawl keeps its uuid, its
134
+ * artifacts and its search index; only pages whose content changed are
135
+ * re-indexed and pages that disappeared are dropped.
136
+ */
137
+ refreshNow(): Promise<CrawlerRefreshState>;
138
+ /**
139
+ * Change this crawl's refresh schedule.
140
+ *
141
+ * Sugar over `client.crawlRefreshSettings(uuid, ...)`; only what is passed
142
+ * is changed.
143
+ */
144
+ refreshSettings(settings: {
145
+ enabled?: boolean;
146
+ interval_seconds?: number;
147
+ }): Promise<CrawlerRefreshState>;
148
+ /**
149
+ * Read this crawl's refresh timeline, newest last.
150
+ *
151
+ * Sugar over `client.crawlRefreshHistory(uuid, ...)`.
152
+ */
153
+ refreshHistory(opts?: {
154
+ limit?: number;
155
+ }): Promise<CrawlerRefreshEntry[]>;
99
156
  /**
100
157
  * Read raw content for a single crawled URL using `plain=true` mode.
101
158
  *
@@ -1 +1 @@
1
- {"version":3,"file":"crawl.d.ts","sourceRoot":"","sources":["../src/crawl.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CA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KAChB,GACA,cAAc,CAAC,kBAAkB,EAAE,IAAI,EAAE,SAAS,CAAC;IAKtD;;;;;;OAMG;IACG,UAAU,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAKhD;;;;;OAKG;IACG,eAAe,CAAC,QAAQ,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAK/G;;;;OAIG;IACG,cAAc,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAK/E;;;;;;OAMG;IACG,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,oBAA6B,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAetF;;;;OAIG;IACG,SAAS,CACb,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,GAAE,oBAAoB,EAAa,GACzC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAKlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,eAAe,CAAC;IAStC;;OAEG;IACG,GAAG,IAAI,OAAO,CAAC,eAAe,CAAC;CAQtC"}
package/script/crawl.js CHANGED
@@ -202,6 +202,61 @@ class Crawl {
202
202
  const uuid = this.requireUuid();
203
203
  return await this.client.crawlUrls(uuid, opts);
204
204
  }
205
+ /**
206
+ * Search this crawl's index.
207
+ *
208
+ * Sugar over `client.crawlSearch([uuid], ...)`. The cross-crawl call is the
209
+ * real endpoint; both share its implementation so single and multi-crawl
210
+ * search cannot drift.
211
+ *
212
+ * Requires the crawl to have been started with `search: true` and its index
213
+ * to have reached `READY`/`PARTIAL`; poll `CrawlerStatus.search` or
214
+ * subscribe to the `crawler_search_ready` webhook. An index that is not
215
+ * ready yet is reported in the response's `skipped` list, not as an error.
216
+ */
217
+ async search(query, opts) {
218
+ const uuid = this.requireUuid();
219
+ return await this.client.crawlSearch([uuid], query, opts);
220
+ }
221
+ /**
222
+ * Ask a question answered from this crawl's content.
223
+ *
224
+ * Sugar over `client.crawlPrompt([uuid], ...)`; yields the same frames.
225
+ */
226
+ prompt(prompt, opts) {
227
+ const uuid = this.requireUuid();
228
+ return this.client.crawlPrompt([uuid], prompt, opts);
229
+ }
230
+ /**
231
+ * Re-scrape this crawl's URLs in place, right now.
232
+ *
233
+ * Sugar over `client.crawlRefreshNow(uuid)`. The crawl keeps its uuid, its
234
+ * artifacts and its search index; only pages whose content changed are
235
+ * re-indexed and pages that disappeared are dropped.
236
+ */
237
+ async refreshNow() {
238
+ const uuid = this.requireUuid();
239
+ return await this.client.crawlRefreshNow(uuid);
240
+ }
241
+ /**
242
+ * Change this crawl's refresh schedule.
243
+ *
244
+ * Sugar over `client.crawlRefreshSettings(uuid, ...)`; only what is passed
245
+ * is changed.
246
+ */
247
+ async refreshSettings(settings) {
248
+ const uuid = this.requireUuid();
249
+ return await this.client.crawlRefreshSettings(uuid, settings);
250
+ }
251
+ /**
252
+ * Read this crawl's refresh timeline, newest last.
253
+ *
254
+ * Sugar over `client.crawlRefreshHistory(uuid, ...)`.
255
+ */
256
+ async refreshHistory(opts) {
257
+ const uuid = this.requireUuid();
258
+ return await this.client.crawlRefreshHistory(uuid, opts);
259
+ }
205
260
  /**
206
261
  * Read raw content for a single crawled URL using `plain=true` mode.
207
262
  *