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.
- package/README.md +36 -3
- package/esm/browserconfig.d.ts +37 -5
- package/esm/browserconfig.d.ts.map +1 -1
- package/esm/browserconfig.js +51 -3
- package/esm/client.d.ts +124 -9
- package/esm/client.d.ts.map +1 -1
- package/esm/client.js +346 -50
- package/esm/crawl.d.ts +58 -1
- package/esm/crawl.d.ts.map +1 -1
- package/esm/crawl.js +55 -0
- package/esm/crawlerconfig.d.ts +41 -3
- package/esm/crawlerconfig.d.ts.map +1 -1
- package/esm/crawlerconfig.js +93 -2
- package/esm/crawlerresult.d.ts +335 -2
- package/esm/crawlerresult.d.ts.map +1 -1
- package/esm/crawlerresult.js +367 -1
- package/esm/errors.d.ts +12 -0
- package/esm/errors.d.ts.map +1 -1
- package/esm/errors.js +11 -0
- package/esm/main.d.ts +4 -4
- package/esm/main.d.ts.map +1 -1
- package/esm/main.js +3 -3
- package/esm/scrapeconfig.d.ts +36 -0
- package/esm/scrapeconfig.d.ts.map +1 -1
- package/esm/scrapeconfig.js +44 -2
- package/esm/types.d.ts.map +1 -1
- package/esm/webhookserver.d.ts +33 -15
- package/esm/webhookserver.d.ts.map +1 -1
- package/esm/webhookserver.js +197 -38
- package/package.json +1 -1
- package/script/browserconfig.d.ts +37 -5
- package/script/browserconfig.d.ts.map +1 -1
- package/script/browserconfig.js +51 -3
- package/script/client.d.ts +124 -9
- package/script/client.d.ts.map +1 -1
- package/script/client.js +345 -49
- package/script/crawl.d.ts +58 -1
- package/script/crawl.d.ts.map +1 -1
- package/script/crawl.js +55 -0
- package/script/crawlerconfig.d.ts +41 -3
- package/script/crawlerconfig.d.ts.map +1 -1
- package/script/crawlerconfig.js +94 -3
- package/script/crawlerresult.d.ts +335 -2
- package/script/crawlerresult.d.ts.map +1 -1
- package/script/crawlerresult.js +374 -2
- package/script/errors.d.ts +12 -0
- package/script/errors.d.ts.map +1 -1
- package/script/errors.js +12 -1
- package/script/main.d.ts +4 -4
- package/script/main.d.ts.map +1 -1
- package/script/main.js +9 -2
- package/script/scrapeconfig.d.ts +36 -0
- package/script/scrapeconfig.d.ts.map +1 -1
- package/script/scrapeconfig.js +44 -2
- package/script/types.d.ts.map +1 -1
- package/script/webhookserver.d.ts +33 -15
- package/script/webhookserver.d.ts.map +1 -1
- package/script/webhookserver.js +197 -38
- package/src/browserconfig.ts +52 -4
- package/src/client.ts +413 -51
- package/src/crawl.ts +74 -0
- package/src/crawlerconfig.ts +115 -5
- package/src/crawlerresult.ts +566 -3
- package/src/errors.ts +12 -0
- package/src/main.ts +25 -2
- package/src/scrapeconfig.ts +54 -2
- package/src/types.ts +0 -1
- package/src/webhookserver.ts +235 -39
package/src/client.ts
CHANGED
|
@@ -10,7 +10,21 @@ import { type AccountData, type ClassifyOptions, type ClassifyResult, Extraction
|
|
|
10
10
|
import { log } from './logger.js';
|
|
11
11
|
import type { Rec, Vault, VaultItem, VaultItemCreate, VaultSecret } from './types.js';
|
|
12
12
|
import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
|
|
13
|
-
import {
|
|
13
|
+
import { REFRESH_MAX_INTERVAL, REFRESH_MIN_INTERVAL } from './crawlerconfig.js';
|
|
14
|
+
import {
|
|
15
|
+
CrawlerArtifact,
|
|
16
|
+
type CrawlerArtifactType,
|
|
17
|
+
CrawlerContents,
|
|
18
|
+
type CrawlerPromptEvent,
|
|
19
|
+
type CrawlerRefreshEntry,
|
|
20
|
+
type CrawlerRefreshState,
|
|
21
|
+
type CrawlerSearchMode,
|
|
22
|
+
CrawlerSearchResponse,
|
|
23
|
+
CrawlerStatus,
|
|
24
|
+
CrawlerUrls,
|
|
25
|
+
parseCrawlerPromptStream,
|
|
26
|
+
parseCrawlerRefreshState,
|
|
27
|
+
} from './crawlerresult.js';
|
|
14
28
|
import {
|
|
15
29
|
formatMonitoringDate,
|
|
16
30
|
type CloudBrowserMonitoringOptions,
|
|
@@ -25,6 +39,18 @@ import {
|
|
|
25
39
|
type UpdateScheduleRequest,
|
|
26
40
|
} from './schedule.js';
|
|
27
41
|
|
|
42
|
+
/** ERR::<RESOURCE>::* → error-class taxonomy. */
|
|
43
|
+
const RESOURCE_TO_ERROR: Record<string, new (message: string, args: Record<string, any>) => errors.ScrapflyError> = {
|
|
44
|
+
SCRAPE: errors.ScrapflyScrapeError,
|
|
45
|
+
WEBHOOK: errors.ScrapflyWebhookError,
|
|
46
|
+
PROXY: errors.ScrapflyProxyError,
|
|
47
|
+
SCHEDULE: errors.ScrapflyScheduleError,
|
|
48
|
+
ASP: errors.ScrapflyAspError,
|
|
49
|
+
SESSION: errors.ScrapflySessionError,
|
|
50
|
+
THROTTLE: errors.ScrapflyThrottleError,
|
|
51
|
+
CRAWLER: errors.ScrapflyCrawlerError,
|
|
52
|
+
};
|
|
53
|
+
|
|
28
54
|
/**
|
|
29
55
|
* Main entry point for the Scrapfly SDK.
|
|
30
56
|
*
|
|
@@ -101,21 +127,9 @@ export class ScrapflyClient {
|
|
|
101
127
|
case 429:
|
|
102
128
|
return new errors.TooManyRequests(message, args);
|
|
103
129
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
case 'WEBHOOK':
|
|
108
|
-
return new errors.ScrapflyWebhookError(message, args);
|
|
109
|
-
case 'PROXY':
|
|
110
|
-
return new errors.ScrapflyProxyError(message, args);
|
|
111
|
-
case 'SCHEDULE':
|
|
112
|
-
return new errors.ScrapflyScheduleError(message, args);
|
|
113
|
-
case 'ASP':
|
|
114
|
-
return new errors.ScrapflyAspError(message, args);
|
|
115
|
-
case 'SESSION':
|
|
116
|
-
return new errors.ScrapflySessionError(message, args);
|
|
117
|
-
case 'CRAWLER':
|
|
118
|
-
return new errors.ScrapflyCrawlerError(message, args);
|
|
130
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
131
|
+
if (ResourceError) {
|
|
132
|
+
return new ResourceError(message, args);
|
|
119
133
|
}
|
|
120
134
|
if (args.resource) {
|
|
121
135
|
return new errors.ApiHttpClientError(message, args);
|
|
@@ -129,26 +143,58 @@ export class ScrapflyClient {
|
|
|
129
143
|
return new errors.UpstreamHttpServerError(message, args);
|
|
130
144
|
}
|
|
131
145
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
case 'WEBHOOK':
|
|
136
|
-
return new errors.ScrapflyWebhookError(message, args);
|
|
137
|
-
case 'PROXY':
|
|
138
|
-
return new errors.ScrapflyProxyError(message, args);
|
|
139
|
-
case 'SCHEDULE':
|
|
140
|
-
return new errors.ScrapflyScheduleError(message, args);
|
|
141
|
-
case 'ASP':
|
|
142
|
-
return new errors.ScrapflyAspError(message, args);
|
|
143
|
-
case 'SESSION':
|
|
144
|
-
return new errors.ScrapflySessionError(message, args);
|
|
145
|
-
case 'CRAWLER':
|
|
146
|
-
return new errors.ScrapflyCrawlerError(message, args);
|
|
146
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
147
|
+
if (ResourceError) {
|
|
148
|
+
return new ResourceError(message, args);
|
|
147
149
|
}
|
|
148
150
|
}
|
|
149
151
|
return new errors.ScrapflyError(message, args);
|
|
150
152
|
}
|
|
151
153
|
|
|
154
|
+
/** Build the typed per-part error for an API-generated batch error body. */
|
|
155
|
+
private batchApiErrorPartToError(
|
|
156
|
+
parsed: Record<string, unknown>,
|
|
157
|
+
partHeaders: Record<string, string>,
|
|
158
|
+
): errors.ScrapflyError {
|
|
159
|
+
const code = typeof parsed.code === 'string' ? parsed.code : '';
|
|
160
|
+
const message = String(parsed.message ?? parsed.reason ?? 'API error');
|
|
161
|
+
const httpStatusCode =
|
|
162
|
+
typeof parsed.http_code === 'number'
|
|
163
|
+
? parsed.http_code
|
|
164
|
+
: parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
|
|
165
|
+
const isRetryable = parsed.retryable === true;
|
|
166
|
+
|
|
167
|
+
let documentationUrl: string | undefined;
|
|
168
|
+
if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
|
|
169
|
+
const values = Object.values(parsed.links as Record<string, string>);
|
|
170
|
+
if (values.length) documentationUrl = values[0];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const args = {
|
|
174
|
+
code,
|
|
175
|
+
http_status_code: httpStatusCode,
|
|
176
|
+
is_retryable: isRetryable,
|
|
177
|
+
resource: code ? code.split('::')[1] : null,
|
|
178
|
+
documentation_url: documentationUrl,
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
182
|
+
if (ResourceError) {
|
|
183
|
+
return new ResourceError(message, args);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
switch (httpStatusCode) {
|
|
187
|
+
case 401:
|
|
188
|
+
return new errors.BadApiKeyError(message, args);
|
|
189
|
+
case 429:
|
|
190
|
+
return new errors.TooManyRequests(message, args);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return httpStatusCode >= 500
|
|
194
|
+
? new errors.ApiHttpServerError(message, args)
|
|
195
|
+
: new errors.ApiHttpClientError(message, args);
|
|
196
|
+
}
|
|
197
|
+
|
|
152
198
|
/**
|
|
153
199
|
* Handle clob and blob large objects
|
|
154
200
|
*/
|
|
@@ -739,6 +785,21 @@ export class ScrapflyClient {
|
|
|
739
785
|
continue;
|
|
740
786
|
}
|
|
741
787
|
|
|
788
|
+
// API-generated error parts carry status >= 400 and an error body
|
|
789
|
+
// instead of the scrape envelope — surface them as typed errors.
|
|
790
|
+
const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
|
|
791
|
+
if (
|
|
792
|
+
partStatus >= 400 &&
|
|
793
|
+
parsed &&
|
|
794
|
+
typeof parsed === 'object' &&
|
|
795
|
+
!Array.isArray(parsed) &&
|
|
796
|
+
!('result' in parsed) &&
|
|
797
|
+
!('config' in parsed)
|
|
798
|
+
) {
|
|
799
|
+
yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
|
|
742
803
|
try {
|
|
743
804
|
const result = new ScrapeResult({
|
|
744
805
|
config: (parsed as any).config,
|
|
@@ -949,7 +1010,7 @@ export class ScrapflyClient {
|
|
|
949
1010
|
if (urlList !== undefined) {
|
|
950
1011
|
// Strip url_list from the JSON config — the URLs go through the
|
|
951
1012
|
// 'urls' multipart part instead, which the API gateway streams
|
|
952
|
-
// straight through to the
|
|
1013
|
+
// straight through to the scraping backend.
|
|
953
1014
|
delete params.url_list;
|
|
954
1015
|
const form = new FormData();
|
|
955
1016
|
const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
|
|
@@ -1340,6 +1401,292 @@ export class ScrapflyClient {
|
|
|
1340
1401
|
}
|
|
1341
1402
|
return response.ok;
|
|
1342
1403
|
}
|
|
1404
|
+
|
|
1405
|
+
/**
|
|
1406
|
+
* Run one refresh of an existing crawl immediately, without waiting for the
|
|
1407
|
+
* next scheduled period.
|
|
1408
|
+
*
|
|
1409
|
+
* `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
|
|
1410
|
+
* same `crawler_uuid`, same artifacts, same search index. Only pages whose
|
|
1411
|
+
* content actually changed are re-indexed and pages that disappeared are
|
|
1412
|
+
* dropped, so everything already pointing at this crawl keeps working.
|
|
1413
|
+
*
|
|
1414
|
+
* A refresh bills the pages it re-scrapes, exactly like the original crawl.
|
|
1415
|
+
* What unchanged pages save is the embedding and the index write.
|
|
1416
|
+
*
|
|
1417
|
+
* The call returns as soon as the run is accepted; poll `crawlStatus` or
|
|
1418
|
+
* `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
|
|
1419
|
+
* starts a second re-scrape of the whole site.
|
|
1420
|
+
*/
|
|
1421
|
+
async crawlRefreshNow(uuid: string): Promise<CrawlerRefreshState> {
|
|
1422
|
+
if (!uuid) {
|
|
1423
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1424
|
+
}
|
|
1425
|
+
let response: Response;
|
|
1426
|
+
try {
|
|
1427
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1428
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1429
|
+
// One attempt: the server may have accepted the billable refresh even
|
|
1430
|
+
// when its response is lost or replaced by a gateway error.
|
|
1431
|
+
response = await this.fetch(
|
|
1432
|
+
{
|
|
1433
|
+
url: url.toString(),
|
|
1434
|
+
method: 'POST',
|
|
1435
|
+
headers: {
|
|
1436
|
+
'user-agent': this.ua,
|
|
1437
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1438
|
+
accept: 'application/json',
|
|
1439
|
+
},
|
|
1440
|
+
},
|
|
1441
|
+
1,
|
|
1442
|
+
);
|
|
1443
|
+
} catch (e) {
|
|
1444
|
+
log.error('error', e);
|
|
1445
|
+
throw e;
|
|
1446
|
+
}
|
|
1447
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1448
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1449
|
+
this.throwCrawlerError(response, data);
|
|
1450
|
+
}
|
|
1451
|
+
return parseCrawlerRefreshState(data);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/**
|
|
1455
|
+
* Change the refresh schedule of an existing crawl.
|
|
1456
|
+
*
|
|
1457
|
+
* `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
|
|
1458
|
+
* turning a crawl off keeps its interval for when it is turned back on.
|
|
1459
|
+
*
|
|
1460
|
+
* Turning refresh on for a crawl started without it is allowed: the crawl
|
|
1461
|
+
* already holds the URL index a refresh walks.
|
|
1462
|
+
*/
|
|
1463
|
+
async crawlRefreshSettings(
|
|
1464
|
+
uuid: string,
|
|
1465
|
+
settings: { enabled?: boolean; interval_seconds?: number },
|
|
1466
|
+
): Promise<CrawlerRefreshState> {
|
|
1467
|
+
if (!uuid) {
|
|
1468
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1469
|
+
}
|
|
1470
|
+
if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
|
|
1471
|
+
throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
|
|
1472
|
+
}
|
|
1473
|
+
if (
|
|
1474
|
+
settings.interval_seconds !== undefined &&
|
|
1475
|
+
(settings.interval_seconds < REFRESH_MIN_INTERVAL || settings.interval_seconds > REFRESH_MAX_INTERVAL)
|
|
1476
|
+
) {
|
|
1477
|
+
throw new errors.ScrapflyCrawlerError(
|
|
1478
|
+
`interval_seconds must be between ${REFRESH_MIN_INTERVAL} and ${REFRESH_MAX_INTERVAL} seconds`,
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// Wire keys are the ones POST /crawl already takes, so a crawl body and a
|
|
1483
|
+
// later PATCH name the same things. The enabled/interval_seconds spelling
|
|
1484
|
+
// belongs to the state block this call answers with, not to its request;
|
|
1485
|
+
// the API decodes the body with unknown fields rejected.
|
|
1486
|
+
const payload: Rec<any> = {};
|
|
1487
|
+
if (settings.enabled !== undefined) payload.refresh = settings.enabled;
|
|
1488
|
+
if (settings.interval_seconds !== undefined) payload.refresh_interval = settings.interval_seconds;
|
|
1489
|
+
|
|
1490
|
+
let response: Response;
|
|
1491
|
+
try {
|
|
1492
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1493
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1494
|
+
response = await this.fetch({
|
|
1495
|
+
url: url.toString(),
|
|
1496
|
+
method: 'PATCH',
|
|
1497
|
+
headers: {
|
|
1498
|
+
'user-agent': this.ua,
|
|
1499
|
+
'content-type': 'application/json',
|
|
1500
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1501
|
+
accept: 'application/json',
|
|
1502
|
+
},
|
|
1503
|
+
body: JSON.stringify(payload),
|
|
1504
|
+
});
|
|
1505
|
+
} catch (e) {
|
|
1506
|
+
log.error('error', e);
|
|
1507
|
+
throw e;
|
|
1508
|
+
}
|
|
1509
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1510
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1511
|
+
this.throwCrawlerError(response, data);
|
|
1512
|
+
}
|
|
1513
|
+
return parseCrawlerRefreshState(data);
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* Read a crawl's refresh timeline, newest last.
|
|
1518
|
+
*
|
|
1519
|
+
* `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
|
|
1520
|
+
* runs; older rows are trimmed rather than paged, because the timeline
|
|
1521
|
+
* exists to show recent activity.
|
|
1522
|
+
*/
|
|
1523
|
+
async crawlRefreshHistory(uuid: string, opts?: { limit?: number }): Promise<CrawlerRefreshEntry[]> {
|
|
1524
|
+
if (!uuid) {
|
|
1525
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1526
|
+
}
|
|
1527
|
+
let response: Response;
|
|
1528
|
+
try {
|
|
1529
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
|
|
1530
|
+
const params: Rec<string> = { key: this.key };
|
|
1531
|
+
if (opts?.limit !== undefined) params.limit = String(opts.limit);
|
|
1532
|
+
url.search = new URLSearchParams(params).toString();
|
|
1533
|
+
response = await this.fetch({
|
|
1534
|
+
url: url.toString(),
|
|
1535
|
+
method: 'GET',
|
|
1536
|
+
headers: {
|
|
1537
|
+
'user-agent': this.ua,
|
|
1538
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1539
|
+
accept: 'application/json',
|
|
1540
|
+
},
|
|
1541
|
+
});
|
|
1542
|
+
} catch (e) {
|
|
1543
|
+
log.error('error', e);
|
|
1544
|
+
throw e;
|
|
1545
|
+
}
|
|
1546
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1547
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1548
|
+
this.throwCrawlerError(response, data);
|
|
1549
|
+
}
|
|
1550
|
+
return parseCrawlerRefreshState(data).history ?? [];
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
/**
|
|
1554
|
+
* Search across the search indexes of one or more crawls.
|
|
1555
|
+
*
|
|
1556
|
+
* `POST /crawl/search`: the collection endpoint is the real API and
|
|
1557
|
+
* {@link crawl.Crawl.search} is sugar over a one-element list so the two
|
|
1558
|
+
* cannot drift.
|
|
1559
|
+
*
|
|
1560
|
+
* Only crawls started with `search: true` whose index reached `READY` or
|
|
1561
|
+
* `PARTIAL` contribute. The rest come back in `skipped` with a reason and
|
|
1562
|
+
* never fail the call, so inspect `skipped` before concluding a crawl had
|
|
1563
|
+
* no match.
|
|
1564
|
+
*/
|
|
1565
|
+
async crawlSearch(
|
|
1566
|
+
crawlIds: string[],
|
|
1567
|
+
query: string,
|
|
1568
|
+
opts?: {
|
|
1569
|
+
/** 1-50 (server cap). Unset uses the server default. */
|
|
1570
|
+
limit?: number;
|
|
1571
|
+
mode?: CrawlerSearchMode;
|
|
1572
|
+
/**
|
|
1573
|
+
* Flat filter map: `url_prefix`, `host`, `source_format`,
|
|
1574
|
+
* `content_type`, `http_status`, `crawler_uuid`. Filters are pushed down
|
|
1575
|
+
* per crawl before its top-K, so they never cost recall. Unknown keys
|
|
1576
|
+
* are rejected server-side rather than ignored.
|
|
1577
|
+
*/
|
|
1578
|
+
filters?: Rec<any>;
|
|
1579
|
+
/** Next-page token from a previous response. */
|
|
1580
|
+
cursor?: string;
|
|
1581
|
+
},
|
|
1582
|
+
): Promise<CrawlerSearchResponse> {
|
|
1583
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1584
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1585
|
+
}
|
|
1586
|
+
if (!query) {
|
|
1587
|
+
throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
const payload: Rec<any> = { query, crawl_ids: crawlIds };
|
|
1591
|
+
if (opts?.limit !== undefined) payload.limit = opts.limit;
|
|
1592
|
+
if (opts?.mode !== undefined) payload.mode = opts.mode;
|
|
1593
|
+
if (opts?.filters !== undefined) payload.filters = opts.filters;
|
|
1594
|
+
if (opts?.cursor !== undefined) payload.cursor = opts.cursor;
|
|
1595
|
+
|
|
1596
|
+
let response: Response;
|
|
1597
|
+
try {
|
|
1598
|
+
const url = new URL(`${this.HOST}/crawl/search`);
|
|
1599
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1600
|
+
response = await this.fetch({
|
|
1601
|
+
url: url.toString(),
|
|
1602
|
+
method: 'POST',
|
|
1603
|
+
headers: {
|
|
1604
|
+
'user-agent': this.ua,
|
|
1605
|
+
'content-type': 'application/json',
|
|
1606
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1607
|
+
accept: 'application/json',
|
|
1608
|
+
},
|
|
1609
|
+
body: JSON.stringify(payload),
|
|
1610
|
+
});
|
|
1611
|
+
} catch (e) {
|
|
1612
|
+
log.error('error', e);
|
|
1613
|
+
throw e;
|
|
1614
|
+
}
|
|
1615
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1616
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1617
|
+
this.throwCrawlerError(response, data);
|
|
1618
|
+
}
|
|
1619
|
+
return new CrawlerSearchResponse(data);
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/**
|
|
1623
|
+
* Ask a question answered from the content of one or more crawls, streaming
|
|
1624
|
+
* the answer as it is generated.
|
|
1625
|
+
*
|
|
1626
|
+
* `POST /crawl/prompt`: the collection endpoint is the real API and
|
|
1627
|
+
* {@link crawl.Crawl.prompt} is sugar over a one-element list.
|
|
1628
|
+
*
|
|
1629
|
+
* Yields `source` frames, then `token` frames, then one `done`. An
|
|
1630
|
+
* `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
|
|
1631
|
+
* yielded, and can arrive after tokens were already yielded because
|
|
1632
|
+
* generation fails mid-stream.
|
|
1633
|
+
*
|
|
1634
|
+
* Consume with `for await`; abandoning the iterator early cancels the body.
|
|
1635
|
+
*
|
|
1636
|
+
* Do not consume this with `EventSource`: it reconnects on close and would
|
|
1637
|
+
* silently re-run the whole fan-out and generation.
|
|
1638
|
+
*/
|
|
1639
|
+
async *crawlPrompt(
|
|
1640
|
+
crawlIds: string[],
|
|
1641
|
+
prompt: string,
|
|
1642
|
+
opts?: {
|
|
1643
|
+
/** Retrieval overrides. Unset uses the server defaults. */
|
|
1644
|
+
search?: { limit?: number; mode?: CrawlerSearchMode; filters?: Rec<any> };
|
|
1645
|
+
/** Generation model id. Unset uses the server default. */
|
|
1646
|
+
model?: string;
|
|
1647
|
+
},
|
|
1648
|
+
): AsyncGenerator<CrawlerPromptEvent, void, undefined> {
|
|
1649
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1650
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1651
|
+
}
|
|
1652
|
+
if (!prompt) {
|
|
1653
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
const generation: Rec<any> = { stream: true };
|
|
1657
|
+
if (opts?.model !== undefined) generation.model = opts.model;
|
|
1658
|
+
const payload: Rec<any> = { prompt, crawl_ids: crawlIds, generation };
|
|
1659
|
+
if (opts?.search !== undefined) payload.search = opts.search;
|
|
1660
|
+
|
|
1661
|
+
const url = new URL(`${this.HOST}/crawl/prompt`);
|
|
1662
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1663
|
+
// One attempt only: the request runs a fan-out and a generation, both
|
|
1664
|
+
// billable, so a retry doubles the bill.
|
|
1665
|
+
const response = await this.fetch(
|
|
1666
|
+
{
|
|
1667
|
+
url: url.toString(),
|
|
1668
|
+
method: 'POST',
|
|
1669
|
+
headers: {
|
|
1670
|
+
'user-agent': this.ua,
|
|
1671
|
+
'content-type': 'application/json',
|
|
1672
|
+
accept: 'text/event-stream',
|
|
1673
|
+
},
|
|
1674
|
+
body: JSON.stringify(payload),
|
|
1675
|
+
},
|
|
1676
|
+
1,
|
|
1677
|
+
);
|
|
1678
|
+
|
|
1679
|
+
if (!response.ok) {
|
|
1680
|
+
const data: Rec<any> = (await response.json().catch(() => ({}))) as Rec<any>;
|
|
1681
|
+
this.throwCrawlerError(response, data);
|
|
1682
|
+
}
|
|
1683
|
+
if (response.body === null) {
|
|
1684
|
+
throw new errors.ScrapflyCrawlerError('prompt response carried no body');
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
yield* parseCrawlerPromptStream(response.body);
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1343
1690
|
// --- Cloud Browser ---
|
|
1344
1691
|
|
|
1345
1692
|
/**
|
|
@@ -1356,45 +1703,51 @@ export class ScrapflyClient {
|
|
|
1356
1703
|
|
|
1357
1704
|
/**
|
|
1358
1705
|
* Return the deterministic project salt for this client's api_key. Matches
|
|
1359
|
-
* the `X-Browser-Project-Salt` response header returned on
|
|
1360
|
-
* Cloud Browser
|
|
1706
|
+
* the `X-Browser-Project-Salt` response header returned on VNC-enabled
|
|
1707
|
+
* Cloud Browser upgrades, where the salt is also the VNC password prefix.
|
|
1361
1708
|
*/
|
|
1362
1709
|
async cloudBrowserProjectSalt(): Promise<string> {
|
|
1363
1710
|
return BrowserConfig.projectSalt(this.key);
|
|
1364
1711
|
}
|
|
1365
1712
|
|
|
1713
|
+
/**
|
|
1714
|
+
* Return the password a native VNC client must type to attach to a session
|
|
1715
|
+
* created with `config`: `<projectSalt>-<vnc_password>`.
|
|
1716
|
+
*
|
|
1717
|
+
* Copy this value into your VNC client when connecting to the TCP endpoint
|
|
1718
|
+
* (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
|
|
1719
|
+
* `vnc_password` instead.
|
|
1720
|
+
*/
|
|
1721
|
+
async cloudBrowserVncPassword(config: BrowserConfig): Promise<string> {
|
|
1722
|
+
return config.vncClientPassword(this.key);
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1366
1725
|
/**
|
|
1367
1726
|
* Call the Cloud Browser Unblock API.
|
|
1727
|
+
*
|
|
1728
|
+
* Unblock always uses a residential proxy (no proxy pool selection) and
|
|
1729
|
+
* always performs a GET — the endpoint's purpose is to harvest cookies /
|
|
1730
|
+
* clearance tokens via an ASP-bypass navigation, not to proxy arbitrary
|
|
1731
|
+
* HTTP requests.
|
|
1368
1732
|
*/
|
|
1369
1733
|
async cloudBrowserUnblock(options: {
|
|
1370
1734
|
url: string;
|
|
1371
|
-
proxy_pool?: string;
|
|
1372
1735
|
country?: string;
|
|
1373
1736
|
os?: string;
|
|
1374
1737
|
browser_brand?: string;
|
|
1738
|
+
session?: string;
|
|
1375
1739
|
timeout?: number;
|
|
1376
1740
|
browser_timeout?: number;
|
|
1377
|
-
headers?: Record<string, string>;
|
|
1378
|
-
body?: string;
|
|
1379
|
-
method?: string;
|
|
1380
1741
|
enable_mcp?: boolean;
|
|
1381
1742
|
debug?: boolean;
|
|
1382
1743
|
}): Promise<{ ws_url: string; session_id: string; run_id: string; mcp_endpoint?: string }> {
|
|
1383
|
-
const proxyPoolMap: Record<string, string> = {
|
|
1384
|
-
datacenter: 'public_datacenter_pool',
|
|
1385
|
-
residential: 'public_residential_pool',
|
|
1386
|
-
};
|
|
1387
|
-
|
|
1388
1744
|
const jsonBody: Record<string, unknown> = { url: options.url };
|
|
1389
|
-
if (options.proxy_pool) jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
|
|
1390
1745
|
if (options.country) jsonBody.country = options.country;
|
|
1391
1746
|
if (options.os) jsonBody.os = options.os;
|
|
1392
1747
|
if (options.browser_brand) jsonBody.browser_brand = options.browser_brand;
|
|
1748
|
+
if (options.session) jsonBody.session = options.session;
|
|
1393
1749
|
if (options.timeout) jsonBody.timeout = options.timeout;
|
|
1394
1750
|
if (options.browser_timeout) jsonBody.browser_timeout = options.browser_timeout;
|
|
1395
|
-
if (options.headers) jsonBody.headers = options.headers;
|
|
1396
|
-
if (options.body) jsonBody.body = options.body;
|
|
1397
|
-
if (options.method) jsonBody.method = options.method;
|
|
1398
1751
|
if (options.enable_mcp !== undefined) jsonBody.enable_mcp = options.enable_mcp;
|
|
1399
1752
|
if (options.debug !== undefined) jsonBody.debug = options.debug;
|
|
1400
1753
|
|
|
@@ -1556,12 +1909,12 @@ export class ScrapflyClient {
|
|
|
1556
1909
|
}
|
|
1557
1910
|
|
|
1558
1911
|
// ----- Cloud Browser Credential Vault -------------------------------------
|
|
1559
|
-
// Server contract documented
|
|
1912
|
+
// Server contract documented in the Vault API reference.
|
|
1560
1913
|
//
|
|
1561
1914
|
// SECURITY: the vault key is the customer-held secret that decrypts every
|
|
1562
1915
|
// item in the vault. The server emits it ONCE on POST /vault and POST
|
|
1563
1916
|
// /vault/{id}/rotate; never log it, never include it in error messages,
|
|
1564
|
-
// never put it in a breadcrumb
|
|
1917
|
+
// never put it in a breadcrumb, and never echo it back to a caller.
|
|
1565
1918
|
|
|
1566
1919
|
/**
|
|
1567
1920
|
* Create a new Cloud Browser Credential Vault. The response contains a
|
|
@@ -1960,7 +2313,12 @@ export class ScrapflyClient {
|
|
|
1960
2313
|
// -------------------------------------------------------------------------
|
|
1961
2314
|
|
|
1962
2315
|
/** Create a Web Scraping API schedule. `scrape_config` is the same shape
|
|
1963
|
-
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`).
|
|
2316
|
+
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
|
|
2317
|
+
* forwarded to the API verbatim, so its keys are wire keys, not the SDK
|
|
2318
|
+
* option names. The anti-bot bypass may be spelled either way here: the API
|
|
2319
|
+
* folds `unblocker` into `asp` on the STORED config, with the same precedence
|
|
2320
|
+
* the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
|
|
2321
|
+
* absent, `null` or `""`), so both names reach the replayed scrape. */
|
|
1964
2322
|
async createScrapeSchedule(
|
|
1965
2323
|
scrapeConfig: Record<string, unknown>,
|
|
1966
2324
|
request: CreateScheduleRequest,
|
|
@@ -1986,7 +2344,11 @@ export class ScrapflyClient {
|
|
|
1986
2344
|
) as Schedule;
|
|
1987
2345
|
}
|
|
1988
2346
|
|
|
1989
|
-
/** Create a Crawler API schedule.
|
|
2347
|
+
/** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
|
|
2348
|
+
* its keys are wire keys, not the SDK option names. As with
|
|
2349
|
+
* `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
|
|
2350
|
+
* `unblocker`: the API folds the alias into `asp` on the stored config before
|
|
2351
|
+
* it is ever replayed. */
|
|
1990
2352
|
async createCrawlerSchedule(
|
|
1991
2353
|
crawlerConfig: Record<string, unknown>,
|
|
1992
2354
|
request: CreateScheduleRequest,
|
package/src/crawl.ts
CHANGED
|
@@ -6,6 +6,11 @@ import type {
|
|
|
6
6
|
CrawlerArtifact,
|
|
7
7
|
CrawlerArtifactType,
|
|
8
8
|
CrawlerContents,
|
|
9
|
+
CrawlerPromptEvent,
|
|
10
|
+
CrawlerRefreshEntry,
|
|
11
|
+
CrawlerRefreshState,
|
|
12
|
+
CrawlerSearchMode,
|
|
13
|
+
CrawlerSearchResponse,
|
|
9
14
|
CrawlerStatus,
|
|
10
15
|
CrawlerUrls,
|
|
11
16
|
} from './crawlerresult.js';
|
|
@@ -194,6 +199,75 @@ export class Crawl {
|
|
|
194
199
|
return await this.client.crawlUrls(uuid, opts);
|
|
195
200
|
}
|
|
196
201
|
|
|
202
|
+
/**
|
|
203
|
+
* Search this crawl's index.
|
|
204
|
+
*
|
|
205
|
+
* Sugar over `client.crawlSearch([uuid], ...)`. The cross-crawl call is the
|
|
206
|
+
* real endpoint; both share its implementation so single and multi-crawl
|
|
207
|
+
* search cannot drift.
|
|
208
|
+
*
|
|
209
|
+
* Requires the crawl to have been started with `search: true` and its index
|
|
210
|
+
* to have reached `READY`/`PARTIAL`; poll `CrawlerStatus.search` or
|
|
211
|
+
* subscribe to the `crawler_search_ready` webhook. An index that is not
|
|
212
|
+
* ready yet is reported in the response's `skipped` list, not as an error.
|
|
213
|
+
*/
|
|
214
|
+
async search(
|
|
215
|
+
query: string,
|
|
216
|
+
opts?: { limit?: number; mode?: CrawlerSearchMode; filters?: Record<string, any>; cursor?: string },
|
|
217
|
+
): Promise<CrawlerSearchResponse> {
|
|
218
|
+
const uuid = this.requireUuid();
|
|
219
|
+
return await this.client.crawlSearch([uuid], query, opts);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Ask a question answered from this crawl's content.
|
|
224
|
+
*
|
|
225
|
+
* Sugar over `client.crawlPrompt([uuid], ...)`; yields the same frames.
|
|
226
|
+
*/
|
|
227
|
+
prompt(
|
|
228
|
+
prompt: string,
|
|
229
|
+
opts?: {
|
|
230
|
+
search?: { limit?: number; mode?: CrawlerSearchMode; filters?: Record<string, any> };
|
|
231
|
+
model?: string;
|
|
232
|
+
},
|
|
233
|
+
): AsyncGenerator<CrawlerPromptEvent, void, undefined> {
|
|
234
|
+
const uuid = this.requireUuid();
|
|
235
|
+
return this.client.crawlPrompt([uuid], prompt, opts);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Re-scrape this crawl's URLs in place, right now.
|
|
240
|
+
*
|
|
241
|
+
* Sugar over `client.crawlRefreshNow(uuid)`. The crawl keeps its uuid, its
|
|
242
|
+
* artifacts and its search index; only pages whose content changed are
|
|
243
|
+
* re-indexed and pages that disappeared are dropped.
|
|
244
|
+
*/
|
|
245
|
+
async refreshNow(): Promise<CrawlerRefreshState> {
|
|
246
|
+
const uuid = this.requireUuid();
|
|
247
|
+
return await this.client.crawlRefreshNow(uuid);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Change this crawl's refresh schedule.
|
|
252
|
+
*
|
|
253
|
+
* Sugar over `client.crawlRefreshSettings(uuid, ...)`; only what is passed
|
|
254
|
+
* is changed.
|
|
255
|
+
*/
|
|
256
|
+
async refreshSettings(settings: { enabled?: boolean; interval_seconds?: number }): Promise<CrawlerRefreshState> {
|
|
257
|
+
const uuid = this.requireUuid();
|
|
258
|
+
return await this.client.crawlRefreshSettings(uuid, settings);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Read this crawl's refresh timeline, newest last.
|
|
263
|
+
*
|
|
264
|
+
* Sugar over `client.crawlRefreshHistory(uuid, ...)`.
|
|
265
|
+
*/
|
|
266
|
+
async refreshHistory(opts?: { limit?: number }): Promise<CrawlerRefreshEntry[]> {
|
|
267
|
+
const uuid = this.requireUuid();
|
|
268
|
+
return await this.client.crawlRefreshHistory(uuid, opts);
|
|
269
|
+
}
|
|
270
|
+
|
|
197
271
|
/**
|
|
198
272
|
* Read raw content for a single crawled URL using `plain=true` mode.
|
|
199
273
|
*
|