scrapfly-sdk 0.11.1 → 0.12.1
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 +72 -5
- package/esm/browserconfig.d.ts +57 -9
- package/esm/browserconfig.d.ts.map +1 -1
- package/esm/browserconfig.js +63 -5
- package/esm/browserdownloads.d.ts +70 -0
- package/esm/browserdownloads.d.ts.map +1 -0
- package/esm/browserdownloads.js +215 -0
- package/esm/client.d.ts +224 -8
- package/esm/client.d.ts.map +1 -1
- package/esm/client.js +646 -62
- package/esm/crawl.d.ts +83 -1
- package/esm/crawl.d.ts.map +1 -1
- package/esm/crawl.js +73 -0
- package/esm/crawlerconfig.d.ts +54 -3
- package/esm/crawlerconfig.d.ts.map +1 -1
- package/esm/crawlerconfig.js +96 -2
- package/esm/crawlerresult.d.ts +374 -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 +12 -7
- package/esm/main.d.ts.map +1 -1
- package/esm/main.js +10 -5
- package/esm/monitoringconfig.d.ts +2 -2
- package/esm/result.d.ts +11 -1
- package/esm/result.d.ts.map +1 -1
- package/esm/result.js +14 -5
- package/esm/scrapeconfig.d.ts +65 -1
- package/esm/scrapeconfig.d.ts.map +1 -1
- package/esm/scrapeconfig.js +88 -4
- package/esm/screenshotconfig.d.ts +9 -1
- package/esm/screenshotconfig.d.ts.map +1 -1
- package/esm/screenshotconfig.js +12 -1
- package/esm/types.d.ts +128 -0
- package/esm/types.d.ts.map +1 -1
- package/esm/types.js +22 -1
- package/esm/utils.d.ts.map +1 -1
- package/esm/utils.js +16 -2
- 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 +57 -9
- package/script/browserconfig.d.ts.map +1 -1
- package/script/browserconfig.js +63 -5
- package/script/browserdownloads.d.ts +70 -0
- package/script/browserdownloads.d.ts.map +1 -0
- package/script/browserdownloads.js +221 -0
- package/script/client.d.ts +224 -8
- package/script/client.d.ts.map +1 -1
- package/script/client.js +645 -61
- package/script/crawl.d.ts +83 -1
- package/script/crawl.d.ts.map +1 -1
- package/script/crawl.js +73 -0
- package/script/crawlerconfig.d.ts +54 -3
- package/script/crawlerconfig.d.ts.map +1 -1
- package/script/crawlerconfig.js +97 -3
- package/script/crawlerresult.d.ts +374 -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 +12 -7
- package/script/main.d.ts.map +1 -1
- package/script/main.js +20 -4
- package/script/monitoringconfig.d.ts +2 -2
- package/script/result.d.ts +11 -1
- package/script/result.d.ts.map +1 -1
- package/script/result.js +14 -5
- package/script/scrapeconfig.d.ts +65 -1
- package/script/scrapeconfig.d.ts.map +1 -1
- package/script/scrapeconfig.js +88 -4
- package/script/screenshotconfig.d.ts +9 -1
- package/script/screenshotconfig.d.ts.map +1 -1
- package/script/screenshotconfig.js +12 -1
- package/script/types.d.ts +128 -0
- package/script/types.d.ts.map +1 -1
- package/script/types.js +23 -0
- package/script/utils.d.ts.map +1 -1
- package/script/utils.js +16 -2
- 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 +74 -8
- package/src/browserdownloads.ts +266 -0
- package/src/client.ts +796 -65
- package/src/crawl.ts +106 -0
- package/src/crawlerconfig.ts +128 -5
- package/src/crawlerresult.ts +607 -3
- package/src/errors.ts +12 -0
- package/src/main.ts +55 -5
- package/src/monitoringconfig.ts +2 -2
- package/src/result.ts +17 -5
- package/src/scrapeconfig.ts +92 -3
- package/src/screenshotconfig.ts +14 -1
- package/src/types.ts +159 -1
- package/src/utils.ts +16 -2
- package/src/webhookserver.ts +235 -39
package/src/client.ts
CHANGED
|
@@ -8,9 +8,38 @@ import type { ExtractionConfig } from './extractionconfig.js';
|
|
|
8
8
|
import { BrowserConfig } from './browserconfig.js';
|
|
9
9
|
import { type AccountData, type ClassifyOptions, type ClassifyResult, ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
|
|
10
10
|
import { log } from './logger.js';
|
|
11
|
-
import type {
|
|
11
|
+
import type {
|
|
12
|
+
Rec,
|
|
13
|
+
Vault,
|
|
14
|
+
VaultItem,
|
|
15
|
+
VaultItemCreate,
|
|
16
|
+
VaultLinkedService,
|
|
17
|
+
VaultLinkedServiceValue,
|
|
18
|
+
VaultProbeResult,
|
|
19
|
+
VaultProbeVault,
|
|
20
|
+
VaultSecret,
|
|
21
|
+
VaultServiceLink,
|
|
22
|
+
VaultServiceUpdate,
|
|
23
|
+
VaultSyncReport,
|
|
24
|
+
} from './types.js';
|
|
12
25
|
import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
|
|
13
|
-
import {
|
|
26
|
+
import { REFRESH_MAX_INTERVAL, REFRESH_MIN_INTERVAL } from './crawlerconfig.js';
|
|
27
|
+
import {
|
|
28
|
+
CrawlerArtifact,
|
|
29
|
+
type CrawlerArtifactType,
|
|
30
|
+
CrawlerContents,
|
|
31
|
+
type CrawlerExtractResponse,
|
|
32
|
+
type CrawlerPromptAnswer,
|
|
33
|
+
type CrawlerPromptEvent,
|
|
34
|
+
type CrawlerRefreshEntry,
|
|
35
|
+
type CrawlerRefreshState,
|
|
36
|
+
type CrawlerSearchMode,
|
|
37
|
+
CrawlerSearchResponse,
|
|
38
|
+
CrawlerStatus,
|
|
39
|
+
CrawlerUrls,
|
|
40
|
+
parseCrawlerPromptStream,
|
|
41
|
+
parseCrawlerRefreshState,
|
|
42
|
+
} from './crawlerresult.js';
|
|
14
43
|
import {
|
|
15
44
|
formatMonitoringDate,
|
|
16
45
|
type CloudBrowserMonitoringOptions,
|
|
@@ -25,6 +54,18 @@ import {
|
|
|
25
54
|
type UpdateScheduleRequest,
|
|
26
55
|
} from './schedule.js';
|
|
27
56
|
|
|
57
|
+
/** ERR::<RESOURCE>::* → error-class taxonomy. */
|
|
58
|
+
const RESOURCE_TO_ERROR: Record<string, new (message: string, args: Record<string, any>) => errors.ScrapflyError> = {
|
|
59
|
+
SCRAPE: errors.ScrapflyScrapeError,
|
|
60
|
+
WEBHOOK: errors.ScrapflyWebhookError,
|
|
61
|
+
PROXY: errors.ScrapflyProxyError,
|
|
62
|
+
SCHEDULE: errors.ScrapflyScheduleError,
|
|
63
|
+
ASP: errors.ScrapflyAspError,
|
|
64
|
+
SESSION: errors.ScrapflySessionError,
|
|
65
|
+
THROTTLE: errors.ScrapflyThrottleError,
|
|
66
|
+
CRAWLER: errors.ScrapflyCrawlerError,
|
|
67
|
+
};
|
|
68
|
+
|
|
28
69
|
/**
|
|
29
70
|
* Main entry point for the Scrapfly SDK.
|
|
30
71
|
*
|
|
@@ -101,21 +142,9 @@ export class ScrapflyClient {
|
|
|
101
142
|
case 429:
|
|
102
143
|
return new errors.TooManyRequests(message, args);
|
|
103
144
|
}
|
|
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);
|
|
145
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
146
|
+
if (ResourceError) {
|
|
147
|
+
return new ResourceError(message, args);
|
|
119
148
|
}
|
|
120
149
|
if (args.resource) {
|
|
121
150
|
return new errors.ApiHttpClientError(message, args);
|
|
@@ -129,26 +158,58 @@ export class ScrapflyClient {
|
|
|
129
158
|
return new errors.UpstreamHttpServerError(message, args);
|
|
130
159
|
}
|
|
131
160
|
}
|
|
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);
|
|
161
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
162
|
+
if (ResourceError) {
|
|
163
|
+
return new ResourceError(message, args);
|
|
147
164
|
}
|
|
148
165
|
}
|
|
149
166
|
return new errors.ScrapflyError(message, args);
|
|
150
167
|
}
|
|
151
168
|
|
|
169
|
+
/** Build the typed per-part error for an API-generated batch error body. */
|
|
170
|
+
private batchApiErrorPartToError(
|
|
171
|
+
parsed: Record<string, unknown>,
|
|
172
|
+
partHeaders: Record<string, string>,
|
|
173
|
+
): errors.ScrapflyError {
|
|
174
|
+
const code = typeof parsed.code === 'string' ? parsed.code : '';
|
|
175
|
+
const message = String(parsed.message ?? parsed.reason ?? 'API error');
|
|
176
|
+
const httpStatusCode =
|
|
177
|
+
typeof parsed.http_code === 'number'
|
|
178
|
+
? parsed.http_code
|
|
179
|
+
: parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
|
|
180
|
+
const isRetryable = parsed.retryable === true;
|
|
181
|
+
|
|
182
|
+
let documentationUrl: string | undefined;
|
|
183
|
+
if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
|
|
184
|
+
const values = Object.values(parsed.links as Record<string, string>);
|
|
185
|
+
if (values.length) documentationUrl = values[0];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const args = {
|
|
189
|
+
code,
|
|
190
|
+
http_status_code: httpStatusCode,
|
|
191
|
+
is_retryable: isRetryable,
|
|
192
|
+
resource: code ? code.split('::')[1] : null,
|
|
193
|
+
documentation_url: documentationUrl,
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
197
|
+
if (ResourceError) {
|
|
198
|
+
return new ResourceError(message, args);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
switch (httpStatusCode) {
|
|
202
|
+
case 401:
|
|
203
|
+
return new errors.BadApiKeyError(message, args);
|
|
204
|
+
case 429:
|
|
205
|
+
return new errors.TooManyRequests(message, args);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return httpStatusCode >= 500
|
|
209
|
+
? new errors.ApiHttpServerError(message, args)
|
|
210
|
+
: new errors.ApiHttpClientError(message, args);
|
|
211
|
+
}
|
|
212
|
+
|
|
152
213
|
/**
|
|
153
214
|
* Handle clob and blob large objects
|
|
154
215
|
*/
|
|
@@ -157,8 +218,7 @@ export class ScrapflyClient {
|
|
|
157
218
|
|
|
158
219
|
try {
|
|
159
220
|
const url = new URL(result.content);
|
|
160
|
-
|
|
161
|
-
url.search = new URLSearchParams(params).toString();
|
|
221
|
+
url.searchParams.set('key', this.key);
|
|
162
222
|
response = await this.fetch({
|
|
163
223
|
url: url.toString(),
|
|
164
224
|
method: 'GET',
|
|
@@ -173,6 +233,20 @@ export class ScrapflyClient {
|
|
|
173
233
|
throw e;
|
|
174
234
|
}
|
|
175
235
|
|
|
236
|
+
if (!response.ok) {
|
|
237
|
+
const body = await response.text();
|
|
238
|
+
let parsed: unknown = null;
|
|
239
|
+
try {
|
|
240
|
+
parsed = JSON.parse(body);
|
|
241
|
+
} catch {
|
|
242
|
+
// Not an API error: a proxy's page, say.
|
|
243
|
+
}
|
|
244
|
+
const envelope = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
245
|
+
? parsed as Record<string, unknown>
|
|
246
|
+
: { message: body.slice(0, 500) || response.statusText };
|
|
247
|
+
throw this.batchApiErrorPartToError(envelope, { 'x-scrapfly-scrape-status': String(response.status) });
|
|
248
|
+
}
|
|
249
|
+
|
|
176
250
|
let content;
|
|
177
251
|
|
|
178
252
|
if (format === 'clob') {
|
|
@@ -195,7 +269,8 @@ export class ScrapflyClient {
|
|
|
195
269
|
handleResponse(response: Response, result: ScrapeResult): ScrapeResult {
|
|
196
270
|
// success
|
|
197
271
|
log.debug('scrape log url: ', result.result.log_url);
|
|
198
|
-
|
|
272
|
+
// QUEUED: a scrape with a webhook, delivered to it later.
|
|
273
|
+
if (result.result.status === 'QUEUED' || (result.result.status === 'DONE' && result.result.success === true)) {
|
|
199
274
|
return result;
|
|
200
275
|
}
|
|
201
276
|
// something went wrong
|
|
@@ -670,6 +745,12 @@ export class ScrapflyClient {
|
|
|
670
745
|
// Drop `key` (batch key is in the URL).
|
|
671
746
|
const params = cfg.toApiParams({ key: this.key }) as Record<string, unknown>;
|
|
672
747
|
delete params.key;
|
|
748
|
+
// What a single scrape sends as the request itself: the API reads
|
|
749
|
+
// both keys of a batch entry and runs a GET without them.
|
|
750
|
+
params.method = cfg.method;
|
|
751
|
+
if (cfg.body !== undefined) {
|
|
752
|
+
params.body = cfg.body;
|
|
753
|
+
}
|
|
673
754
|
bodyConfigs.push(params);
|
|
674
755
|
}
|
|
675
756
|
|
|
@@ -739,12 +820,29 @@ export class ScrapflyClient {
|
|
|
739
820
|
continue;
|
|
740
821
|
}
|
|
741
822
|
|
|
823
|
+
// API-generated error parts carry status >= 400 and an error body
|
|
824
|
+
// instead of the scrape envelope — surface them as typed errors.
|
|
825
|
+
const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
|
|
826
|
+
if (
|
|
827
|
+
partStatus >= 400 &&
|
|
828
|
+
parsed &&
|
|
829
|
+
typeof parsed === 'object' &&
|
|
830
|
+
!Array.isArray(parsed) &&
|
|
831
|
+
!('result' in parsed) &&
|
|
832
|
+
!('config' in parsed)
|
|
833
|
+
) {
|
|
834
|
+
yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
|
|
742
838
|
try {
|
|
839
|
+
// A config with a webhook is answered by its enqueue ack, the scrape's answer under `result`.
|
|
840
|
+
const envelope = (parsed as any).enqueued === true && (parsed as any).result ? (parsed as any).result : parsed;
|
|
743
841
|
const result = new ScrapeResult({
|
|
744
|
-
config:
|
|
745
|
-
context:
|
|
746
|
-
result:
|
|
747
|
-
uuid:
|
|
842
|
+
config: envelope.config,
|
|
843
|
+
context: envelope.context,
|
|
844
|
+
result: envelope.result,
|
|
845
|
+
uuid: envelope.uuid,
|
|
748
846
|
});
|
|
749
847
|
yield [correlationId, result];
|
|
750
848
|
} catch (resultErr) {
|
|
@@ -762,7 +860,7 @@ export class ScrapflyClient {
|
|
|
762
860
|
* Save screenshot response to a file
|
|
763
861
|
*/
|
|
764
862
|
async saveScreenshot(result: ScreenshotResult, name: string, savePath?: string): Promise<any> {
|
|
765
|
-
if (!result.image) {
|
|
863
|
+
if (!result.image || result.image.byteLength === 0) {
|
|
766
864
|
throw new Error('Screenshot binary does not exist');
|
|
767
865
|
}
|
|
768
866
|
|
|
@@ -786,25 +884,38 @@ export class ScrapflyClient {
|
|
|
786
884
|
* Turn scrapfly screenshot API response to ScreenshotResult or raise one of ScrapflyError
|
|
787
885
|
*/
|
|
788
886
|
async handleScreenshotResponse(response: Response): Promise<ScreenshotResult> {
|
|
789
|
-
// A
|
|
790
|
-
//
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
887
|
+
// A JSON answer is never an image: an error, or the 201 of a screenshot with a webhook.
|
|
888
|
+
// A Response body can only be consumed once, so it is read as text and parsed from that.
|
|
889
|
+
const isJson = (response.headers.get('content-type') ?? '').startsWith('application/json');
|
|
890
|
+
if (isJson || response.status === 201) {
|
|
891
|
+
const text = await response.text();
|
|
892
|
+
let jsonData: Rec<any> | null = null;
|
|
893
|
+
try {
|
|
894
|
+
const parsed = JSON.parse(text);
|
|
895
|
+
if (parsed !== null && typeof parsed === 'object') {
|
|
896
|
+
jsonData = parsed as Rec<any>;
|
|
897
|
+
}
|
|
898
|
+
} catch {
|
|
899
|
+
jsonData = null;
|
|
900
|
+
}
|
|
901
|
+
const message = jsonData ? JSON.stringify(jsonData) : text || `API returned status ${response.status}`;
|
|
902
|
+
if (response.status == 401 || jsonData?.http_code == 401) {
|
|
903
|
+
throw new errors.BadApiKeyError(message);
|
|
798
904
|
}
|
|
799
|
-
if (
|
|
800
|
-
|
|
905
|
+
if (jsonData) {
|
|
906
|
+
if ('error_id' in jsonData) {
|
|
907
|
+
throw new errors.ScreenshotApiError(JSON.stringify(jsonData));
|
|
908
|
+
}
|
|
909
|
+
// 201: a screenshot with a webhook, delivered to it later.
|
|
910
|
+
const job = jsonData.job_uuid;
|
|
911
|
+
if (response.status === 201 && jsonData.webhook_enqueued === true && typeof job === 'string' && job !== '') {
|
|
912
|
+
return new ScreenshotResult(response, new ArrayBuffer(0), job);
|
|
913
|
+
}
|
|
801
914
|
}
|
|
915
|
+
throw new errors.ScreenshotApiError(message);
|
|
802
916
|
}
|
|
803
917
|
if (!response.ok) {
|
|
804
|
-
|
|
805
|
-
throw new errors.ScreenshotApiError(
|
|
806
|
-
typeof body === 'string' ? body : JSON.stringify(body),
|
|
807
|
-
);
|
|
918
|
+
throw new errors.ScreenshotApiError((await response.text()) || `API returned status ${response.status}`);
|
|
808
919
|
}
|
|
809
920
|
const data = await response.arrayBuffer();
|
|
810
921
|
const result = new ScreenshotResult(response, data);
|
|
@@ -909,7 +1020,8 @@ export class ScrapflyClient {
|
|
|
909
1020
|
private throwCrawlerError(response: Response, data: Rec<any>): never {
|
|
910
1021
|
const httpCode = data.http_code ?? response.status;
|
|
911
1022
|
const code = (data.code ?? '') as string;
|
|
912
|
-
|
|
1023
|
+
// The engine relays its own failures as `{error, code}`.
|
|
1024
|
+
const message = data.message ?? (typeof data.error === 'string' ? data.error : JSON.stringify(data));
|
|
913
1025
|
if (httpCode === 401) {
|
|
914
1026
|
throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
|
|
915
1027
|
}
|
|
@@ -949,7 +1061,7 @@ export class ScrapflyClient {
|
|
|
949
1061
|
if (urlList !== undefined) {
|
|
950
1062
|
// Strip url_list from the JSON config — the URLs go through the
|
|
951
1063
|
// 'urls' multipart part instead, which the API gateway streams
|
|
952
|
-
// straight through to the
|
|
1064
|
+
// straight through to the scraping backend.
|
|
953
1065
|
delete params.url_list;
|
|
954
1066
|
const form = new FormData();
|
|
955
1067
|
const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
|
|
@@ -1340,6 +1452,384 @@ export class ScrapflyClient {
|
|
|
1340
1452
|
}
|
|
1341
1453
|
return response.ok;
|
|
1342
1454
|
}
|
|
1455
|
+
|
|
1456
|
+
/**
|
|
1457
|
+
* Run one refresh of an existing crawl immediately, without waiting for the
|
|
1458
|
+
* next scheduled period.
|
|
1459
|
+
*
|
|
1460
|
+
* `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
|
|
1461
|
+
* same `crawler_uuid`, same artifacts, same search index. Only pages whose
|
|
1462
|
+
* content actually changed are re-indexed and pages that disappeared are
|
|
1463
|
+
* dropped, so everything already pointing at this crawl keeps working.
|
|
1464
|
+
*
|
|
1465
|
+
* A refresh bills the pages it re-scrapes, exactly like the original crawl.
|
|
1466
|
+
* What unchanged pages save is the embedding and the index write.
|
|
1467
|
+
*
|
|
1468
|
+
* The call returns as soon as the run is accepted; poll `crawlStatus` or
|
|
1469
|
+
* `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
|
|
1470
|
+
* starts a second re-scrape of the whole site.
|
|
1471
|
+
*/
|
|
1472
|
+
async crawlRefreshNow(uuid: string): Promise<CrawlerRefreshState> {
|
|
1473
|
+
if (!uuid) {
|
|
1474
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1475
|
+
}
|
|
1476
|
+
let response: Response;
|
|
1477
|
+
try {
|
|
1478
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1479
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1480
|
+
// One attempt: the server may have accepted the billable refresh even
|
|
1481
|
+
// when its response is lost or replaced by a gateway error.
|
|
1482
|
+
response = await this.fetch(
|
|
1483
|
+
{
|
|
1484
|
+
url: url.toString(),
|
|
1485
|
+
method: 'POST',
|
|
1486
|
+
headers: {
|
|
1487
|
+
'user-agent': this.ua,
|
|
1488
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1489
|
+
accept: 'application/json',
|
|
1490
|
+
},
|
|
1491
|
+
},
|
|
1492
|
+
1,
|
|
1493
|
+
);
|
|
1494
|
+
} catch (e) {
|
|
1495
|
+
log.error('error', e);
|
|
1496
|
+
throw e;
|
|
1497
|
+
}
|
|
1498
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1499
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1500
|
+
this.throwCrawlerError(response, data);
|
|
1501
|
+
}
|
|
1502
|
+
return parseCrawlerRefreshState(data);
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/**
|
|
1506
|
+
* Change the refresh schedule of an existing crawl.
|
|
1507
|
+
*
|
|
1508
|
+
* `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
|
|
1509
|
+
* turning a crawl off keeps its interval for when it is turned back on.
|
|
1510
|
+
*
|
|
1511
|
+
* Turning refresh on for a crawl started without it is allowed: the crawl
|
|
1512
|
+
* already holds the URL index a refresh walks.
|
|
1513
|
+
*/
|
|
1514
|
+
async crawlRefreshSettings(
|
|
1515
|
+
uuid: string,
|
|
1516
|
+
settings: { enabled?: boolean; interval_seconds?: number },
|
|
1517
|
+
): Promise<CrawlerRefreshState> {
|
|
1518
|
+
if (!uuid) {
|
|
1519
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1520
|
+
}
|
|
1521
|
+
if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
|
|
1522
|
+
throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
|
|
1523
|
+
}
|
|
1524
|
+
if (
|
|
1525
|
+
settings.interval_seconds !== undefined &&
|
|
1526
|
+
(settings.interval_seconds < REFRESH_MIN_INTERVAL || settings.interval_seconds > REFRESH_MAX_INTERVAL)
|
|
1527
|
+
) {
|
|
1528
|
+
throw new errors.ScrapflyCrawlerError(
|
|
1529
|
+
`interval_seconds must be between ${REFRESH_MIN_INTERVAL} and ${REFRESH_MAX_INTERVAL} seconds`,
|
|
1530
|
+
);
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
// Wire keys are the ones POST /crawl already takes, so a crawl body and a
|
|
1534
|
+
// later PATCH name the same things. The enabled/interval_seconds spelling
|
|
1535
|
+
// belongs to the state block this call answers with, not to its request;
|
|
1536
|
+
// the API decodes the body with unknown fields rejected.
|
|
1537
|
+
const payload: Rec<any> = {};
|
|
1538
|
+
if (settings.enabled !== undefined) payload.refresh = settings.enabled;
|
|
1539
|
+
if (settings.interval_seconds !== undefined) payload.refresh_interval = settings.interval_seconds;
|
|
1540
|
+
|
|
1541
|
+
let response: Response;
|
|
1542
|
+
try {
|
|
1543
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1544
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1545
|
+
response = await this.fetch({
|
|
1546
|
+
url: url.toString(),
|
|
1547
|
+
method: 'PATCH',
|
|
1548
|
+
headers: {
|
|
1549
|
+
'user-agent': this.ua,
|
|
1550
|
+
'content-type': 'application/json',
|
|
1551
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1552
|
+
accept: 'application/json',
|
|
1553
|
+
},
|
|
1554
|
+
body: JSON.stringify(payload),
|
|
1555
|
+
});
|
|
1556
|
+
} catch (e) {
|
|
1557
|
+
log.error('error', e);
|
|
1558
|
+
throw e;
|
|
1559
|
+
}
|
|
1560
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1561
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1562
|
+
this.throwCrawlerError(response, data);
|
|
1563
|
+
}
|
|
1564
|
+
return parseCrawlerRefreshState(data);
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
/**
|
|
1568
|
+
* Read a crawl's refresh timeline, newest last.
|
|
1569
|
+
*
|
|
1570
|
+
* `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
|
|
1571
|
+
* runs; older rows are trimmed rather than paged, because the timeline
|
|
1572
|
+
* exists to show recent activity.
|
|
1573
|
+
*/
|
|
1574
|
+
async crawlRefreshHistory(uuid: string, opts?: { limit?: number }): Promise<CrawlerRefreshEntry[]> {
|
|
1575
|
+
if (!uuid) {
|
|
1576
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1577
|
+
}
|
|
1578
|
+
let response: Response;
|
|
1579
|
+
try {
|
|
1580
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
|
|
1581
|
+
const params: Rec<string> = { key: this.key };
|
|
1582
|
+
if (opts?.limit !== undefined) params.limit = String(opts.limit);
|
|
1583
|
+
url.search = new URLSearchParams(params).toString();
|
|
1584
|
+
response = await this.fetch({
|
|
1585
|
+
url: url.toString(),
|
|
1586
|
+
method: 'GET',
|
|
1587
|
+
headers: {
|
|
1588
|
+
'user-agent': this.ua,
|
|
1589
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1590
|
+
accept: 'application/json',
|
|
1591
|
+
},
|
|
1592
|
+
});
|
|
1593
|
+
} catch (e) {
|
|
1594
|
+
log.error('error', e);
|
|
1595
|
+
throw e;
|
|
1596
|
+
}
|
|
1597
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1598
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1599
|
+
this.throwCrawlerError(response, data);
|
|
1600
|
+
}
|
|
1601
|
+
return parseCrawlerRefreshState(data).history ?? [];
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
/**
|
|
1605
|
+
* Search across the search indexes of one or more crawls.
|
|
1606
|
+
*
|
|
1607
|
+
* `POST /crawl/search`: the collection endpoint is the real API and
|
|
1608
|
+
* {@link crawl.Crawl.search} is sugar over a one-element list so the two
|
|
1609
|
+
* cannot drift.
|
|
1610
|
+
*
|
|
1611
|
+
* Only crawls started with `search: true` whose index reached `READY` or
|
|
1612
|
+
* `PARTIAL` contribute. The rest come back in `skipped` with a reason and
|
|
1613
|
+
* never fail the call, so inspect `skipped` before concluding a crawl had
|
|
1614
|
+
* no match.
|
|
1615
|
+
*/
|
|
1616
|
+
async crawlSearch(
|
|
1617
|
+
crawlIds: string[],
|
|
1618
|
+
query: string,
|
|
1619
|
+
opts?: {
|
|
1620
|
+
/** 1-50 (server cap). Unset uses the server default. */
|
|
1621
|
+
limit?: number;
|
|
1622
|
+
mode?: CrawlerSearchMode;
|
|
1623
|
+
/**
|
|
1624
|
+
* Flat filter map: `url_prefix`, `host`, `source_format`,
|
|
1625
|
+
* `content_type`, `http_status`, `crawler_uuid`. Filters are pushed down
|
|
1626
|
+
* per crawl before its top-K, so they never cost recall. Unknown keys
|
|
1627
|
+
* are rejected server-side rather than ignored.
|
|
1628
|
+
*/
|
|
1629
|
+
filters?: Rec<any>;
|
|
1630
|
+
/** Next-page token from a previous response. */
|
|
1631
|
+
cursor?: string;
|
|
1632
|
+
},
|
|
1633
|
+
): Promise<CrawlerSearchResponse> {
|
|
1634
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1635
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1636
|
+
}
|
|
1637
|
+
if (!query) {
|
|
1638
|
+
throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
const payload: Rec<any> = { query, crawl_ids: crawlIds };
|
|
1642
|
+
if (opts?.limit !== undefined) payload.limit = opts.limit;
|
|
1643
|
+
if (opts?.mode !== undefined) payload.mode = opts.mode;
|
|
1644
|
+
if (opts?.filters !== undefined) payload.filters = opts.filters;
|
|
1645
|
+
if (opts?.cursor !== undefined) payload.cursor = opts.cursor;
|
|
1646
|
+
|
|
1647
|
+
let response: Response;
|
|
1648
|
+
try {
|
|
1649
|
+
const url = new URL(`${this.HOST}/crawl/search`);
|
|
1650
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1651
|
+
response = await this.fetch({
|
|
1652
|
+
url: url.toString(),
|
|
1653
|
+
method: 'POST',
|
|
1654
|
+
headers: {
|
|
1655
|
+
'user-agent': this.ua,
|
|
1656
|
+
'content-type': 'application/json',
|
|
1657
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1658
|
+
accept: 'application/json',
|
|
1659
|
+
},
|
|
1660
|
+
body: JSON.stringify(payload),
|
|
1661
|
+
});
|
|
1662
|
+
} catch (e) {
|
|
1663
|
+
log.error('error', e);
|
|
1664
|
+
throw e;
|
|
1665
|
+
}
|
|
1666
|
+
const data: Rec<any> = (await response.json()) as Rec<any>;
|
|
1667
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1668
|
+
this.throwCrawlerError(response, data);
|
|
1669
|
+
}
|
|
1670
|
+
return new CrawlerSearchResponse(data);
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
/**
|
|
1674
|
+
* Ask a question answered from the content of one or more crawls, streaming
|
|
1675
|
+
* the answer as it is generated.
|
|
1676
|
+
*
|
|
1677
|
+
* `POST /crawl/prompt`: the collection endpoint is the real API and
|
|
1678
|
+
* {@link crawl.Crawl.prompt} is sugar over a one-element list.
|
|
1679
|
+
*
|
|
1680
|
+
* Yields `source` frames, then `token` frames, then one `done`. An
|
|
1681
|
+
* `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
|
|
1682
|
+
* yielded, and can arrive after tokens were already yielded because
|
|
1683
|
+
* generation fails mid-stream.
|
|
1684
|
+
*
|
|
1685
|
+
* Consume with `for await`; abandoning the iterator early cancels the body.
|
|
1686
|
+
*
|
|
1687
|
+
* Do not consume this with `EventSource`: it reconnects on close and would
|
|
1688
|
+
* silently re-run the whole fan-out and generation.
|
|
1689
|
+
*/
|
|
1690
|
+
async *crawlPrompt(
|
|
1691
|
+
crawlIds: string[],
|
|
1692
|
+
prompt: string,
|
|
1693
|
+
opts?: {
|
|
1694
|
+
/** Retrieval overrides. Unset uses the server defaults. */
|
|
1695
|
+
search?: { limit?: number; mode?: CrawlerSearchMode; filters?: Rec<any> };
|
|
1696
|
+
/** Generation model id. Unset uses the server default. */
|
|
1697
|
+
model?: string;
|
|
1698
|
+
},
|
|
1699
|
+
): AsyncGenerator<CrawlerPromptEvent, void, undefined> {
|
|
1700
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1701
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1702
|
+
}
|
|
1703
|
+
if (!prompt) {
|
|
1704
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
const generation: Rec<any> = { stream: true };
|
|
1708
|
+
if (opts?.model !== undefined) generation.model = opts.model;
|
|
1709
|
+
const payload: Rec<any> = { prompt, crawl_ids: crawlIds, generation };
|
|
1710
|
+
if (opts?.search !== undefined) payload.search = opts.search;
|
|
1711
|
+
|
|
1712
|
+
const url = new URL(`${this.HOST}/crawl/prompt`);
|
|
1713
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1714
|
+
// One attempt only: the request runs a fan-out and a generation, both
|
|
1715
|
+
// billable, so a retry doubles the bill.
|
|
1716
|
+
const response = await this.fetch(
|
|
1717
|
+
{
|
|
1718
|
+
url: url.toString(),
|
|
1719
|
+
method: 'POST',
|
|
1720
|
+
headers: {
|
|
1721
|
+
'user-agent': this.ua,
|
|
1722
|
+
'content-type': 'application/json',
|
|
1723
|
+
accept: 'text/event-stream',
|
|
1724
|
+
},
|
|
1725
|
+
body: JSON.stringify(payload),
|
|
1726
|
+
},
|
|
1727
|
+
1,
|
|
1728
|
+
);
|
|
1729
|
+
|
|
1730
|
+
if (!response.ok) {
|
|
1731
|
+
const data: Rec<any> = (await response.json().catch(() => ({}))) as Rec<any>;
|
|
1732
|
+
this.throwCrawlerError(response, data);
|
|
1733
|
+
}
|
|
1734
|
+
if (response.body === null) {
|
|
1735
|
+
throw new errors.ScrapflyCrawlerError('prompt response carried no body');
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
yield* parseCrawlerPromptStream(response.body);
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
/**
|
|
1742
|
+
* Ask a question answered from the content of one or more crawls, and get
|
|
1743
|
+
* the whole answer in one object once generation completes.
|
|
1744
|
+
*
|
|
1745
|
+
* `POST /crawl/prompt` with `generation.stream: false`: the same facts as
|
|
1746
|
+
* the frames of {@link crawlPrompt}. {@link crawl.Crawl.promptAnswer} is
|
|
1747
|
+
* sugar over a one-element list.
|
|
1748
|
+
*/
|
|
1749
|
+
async crawlPromptAnswer(
|
|
1750
|
+
crawlIds: string[],
|
|
1751
|
+
prompt: string,
|
|
1752
|
+
opts?: {
|
|
1753
|
+
/** Retrieval overrides. Unset uses the server defaults. */
|
|
1754
|
+
search?: { limit?: number; mode?: CrawlerSearchMode; filters?: Rec<any> };
|
|
1755
|
+
/** Generation model id. Unset uses the server default. */
|
|
1756
|
+
model?: string;
|
|
1757
|
+
},
|
|
1758
|
+
): Promise<CrawlerPromptAnswer> {
|
|
1759
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1760
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1761
|
+
}
|
|
1762
|
+
if (!prompt) {
|
|
1763
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
const generation: Rec<any> = { stream: false };
|
|
1767
|
+
if (opts?.model !== undefined) generation.model = opts.model;
|
|
1768
|
+
const payload: Rec<any> = { prompt, crawl_ids: crawlIds, generation };
|
|
1769
|
+
if (opts?.search !== undefined) payload.search = opts.search;
|
|
1770
|
+
|
|
1771
|
+
return (await this.postCrawlerJson('/crawl/prompt', payload)) as CrawlerPromptAnswer;
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/**
|
|
1775
|
+
* Extract a structured object from the content of one or more crawls.
|
|
1776
|
+
*
|
|
1777
|
+
* `POST /crawl/extract` retrieves like {@link crawlPromptAnswer} and answers
|
|
1778
|
+
* with `data` shaped by `schema`, a JSON Schema handed to the model as its
|
|
1779
|
+
* response schema. There is no streaming variant. {@link crawl.Crawl.extract}
|
|
1780
|
+
* is sugar over a one-element list.
|
|
1781
|
+
*/
|
|
1782
|
+
async crawlExtract<T = any>(
|
|
1783
|
+
crawlIds: string[],
|
|
1784
|
+
prompt: string,
|
|
1785
|
+
schema: Rec<any>,
|
|
1786
|
+
opts?: {
|
|
1787
|
+
/** Retrieval overrides. Unset uses the server defaults. */
|
|
1788
|
+
search?: { limit?: number; mode?: CrawlerSearchMode; filters?: Rec<any> };
|
|
1789
|
+
},
|
|
1790
|
+
): Promise<CrawlerExtractResponse<T>> {
|
|
1791
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1792
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1793
|
+
}
|
|
1794
|
+
if (!prompt) {
|
|
1795
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1796
|
+
}
|
|
1797
|
+
if (typeof schema !== 'object' || schema === null || Array.isArray(schema) || Object.keys(schema).length === 0) {
|
|
1798
|
+
throw new errors.ScrapflyCrawlerError('schema must be a non-empty JSON Schema object');
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
const payload: Rec<any> = { prompt, crawl_ids: crawlIds, schema };
|
|
1802
|
+
if (opts?.search !== undefined) payload.search = opts.search;
|
|
1803
|
+
|
|
1804
|
+
return (await this.postCrawlerJson('/crawl/extract', payload)) as CrawlerExtractResponse<T>;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
/** POST a JSON body to a crawler endpoint that generates, once, and return its JSON answer. */
|
|
1808
|
+
private async postCrawlerJson(path: string, payload: Rec<any>): Promise<Rec<any>> {
|
|
1809
|
+
const url = new URL(`${this.HOST}${path}`);
|
|
1810
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1811
|
+
// One attempt only: a retry re-runs the fan-out and the generation.
|
|
1812
|
+
const response = await this.fetch(
|
|
1813
|
+
{
|
|
1814
|
+
url: url.toString(),
|
|
1815
|
+
method: 'POST',
|
|
1816
|
+
headers: {
|
|
1817
|
+
'user-agent': this.ua,
|
|
1818
|
+
'content-type': 'application/json',
|
|
1819
|
+
accept: 'application/json',
|
|
1820
|
+
},
|
|
1821
|
+
body: JSON.stringify(payload),
|
|
1822
|
+
},
|
|
1823
|
+
1,
|
|
1824
|
+
);
|
|
1825
|
+
|
|
1826
|
+
if (!response.ok) {
|
|
1827
|
+
const data: Rec<any> = (await response.json().catch(() => ({}))) as Rec<any>;
|
|
1828
|
+
this.throwCrawlerError(response, data);
|
|
1829
|
+
}
|
|
1830
|
+
return (await response.json()) as Rec<any>;
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1343
1833
|
// --- Cloud Browser ---
|
|
1344
1834
|
|
|
1345
1835
|
/**
|
|
@@ -1356,19 +1846,31 @@ export class ScrapflyClient {
|
|
|
1356
1846
|
|
|
1357
1847
|
/**
|
|
1358
1848
|
* 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
|
|
1849
|
+
* the `X-Browser-Project-Salt` response header returned on VNC-enabled
|
|
1850
|
+
* Cloud Browser upgrades, where the salt is also the VNC password prefix.
|
|
1361
1851
|
*/
|
|
1362
1852
|
async cloudBrowserProjectSalt(): Promise<string> {
|
|
1363
1853
|
return BrowserConfig.projectSalt(this.key);
|
|
1364
1854
|
}
|
|
1365
1855
|
|
|
1856
|
+
/**
|
|
1857
|
+
* Return the password a native VNC client must type to attach to a session
|
|
1858
|
+
* created with `config`: `<projectSalt>-<vnc_password>`.
|
|
1859
|
+
*
|
|
1860
|
+
* Copy this value into your VNC client when connecting to the TCP endpoint
|
|
1861
|
+
* (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
|
|
1862
|
+
* `vnc_password` instead.
|
|
1863
|
+
*/
|
|
1864
|
+
async cloudBrowserVncPassword(config: BrowserConfig): Promise<string> {
|
|
1865
|
+
return config.vncClientPassword(this.key);
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1366
1868
|
/**
|
|
1367
1869
|
* Call the Cloud Browser Unblock API.
|
|
1368
1870
|
*
|
|
1369
1871
|
* Unblock always uses a residential proxy (no proxy pool selection) and
|
|
1370
1872
|
* always performs a GET — the endpoint's purpose is to harvest cookies /
|
|
1371
|
-
* clearance tokens via an
|
|
1873
|
+
* clearance tokens via an Unblocker navigation, not to proxy arbitrary
|
|
1372
1874
|
* HTTP requests.
|
|
1373
1875
|
*/
|
|
1374
1876
|
async cloudBrowserUnblock(options: {
|
|
@@ -1550,12 +2052,12 @@ export class ScrapflyClient {
|
|
|
1550
2052
|
}
|
|
1551
2053
|
|
|
1552
2054
|
// ----- Cloud Browser Credential Vault -------------------------------------
|
|
1553
|
-
// Server contract documented
|
|
2055
|
+
// Server contract documented in the Vault API reference.
|
|
1554
2056
|
//
|
|
1555
2057
|
// SECURITY: the vault key is the customer-held secret that decrypts every
|
|
1556
2058
|
// item in the vault. The server emits it ONCE on POST /vault and POST
|
|
1557
2059
|
// /vault/{id}/rotate; never log it, never include it in error messages,
|
|
1558
|
-
// never put it in a breadcrumb
|
|
2060
|
+
// never put it in a breadcrumb, and never echo it back to a caller.
|
|
1559
2061
|
|
|
1560
2062
|
/**
|
|
1561
2063
|
* Create a new Cloud Browser Credential Vault. The response contains a
|
|
@@ -1861,6 +2363,226 @@ export class ScrapflyClient {
|
|
|
1861
2363
|
};
|
|
1862
2364
|
}
|
|
1863
2365
|
|
|
2366
|
+
// ----- Vault ↔ linked secret manager (1Password) ---------------------------
|
|
2367
|
+
// A linked vault mirrors an upstream secret manager instead of holding
|
|
2368
|
+
// operator-entered items. The provider's service-account token is sealed
|
|
2369
|
+
// under the vault key like any other secret, so every endpoint that carries
|
|
2370
|
+
// a token also carries X-Vault-Key: the server verifies the key BEFORE
|
|
2371
|
+
// sealing, because a well-formed wrong key would link the vault and leave a
|
|
2372
|
+
// token every later sync fails to open.
|
|
2373
|
+
|
|
2374
|
+
/**
|
|
2375
|
+
* Link a vault to a secret manager. The token is sealed under `vaultKey`, so
|
|
2376
|
+
* the key is mandatory here. The vault must not already be linked and must
|
|
2377
|
+
* hold no rows owned by a previous service (the server answers 409).
|
|
2378
|
+
*/
|
|
2379
|
+
async cloudBrowserVaultServiceLink(
|
|
2380
|
+
vaultId: string,
|
|
2381
|
+
vaultKey: string,
|
|
2382
|
+
link: VaultServiceLink,
|
|
2383
|
+
): Promise<{ vault: Vault; message: string }> {
|
|
2384
|
+
if (!link.token) {
|
|
2385
|
+
throw new Error('cloudBrowserVaultServiceLink: token is required when linking a service');
|
|
2386
|
+
}
|
|
2387
|
+
// Same rule as the server's linked_service_data validation; caught here so a
|
|
2388
|
+
// malformed link does not cost a round trip.
|
|
2389
|
+
if (!link.linked_service_data?.vault_id && !link.linked_service_data?.vault_name) {
|
|
2390
|
+
throw new Error(
|
|
2391
|
+
'cloudBrowserVaultServiceLink: linked_service_data requires vault_id or vault_name',
|
|
2392
|
+
);
|
|
2393
|
+
}
|
|
2394
|
+
const url = new URL(
|
|
2395
|
+
this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service',
|
|
2396
|
+
);
|
|
2397
|
+
url.searchParams.set('key', this.key);
|
|
2398
|
+
|
|
2399
|
+
const response = await this.fetch({
|
|
2400
|
+
url: url.toString(),
|
|
2401
|
+
method: 'POST',
|
|
2402
|
+
headers: {
|
|
2403
|
+
'content-type': 'application/json',
|
|
2404
|
+
'user-agent': this.ua,
|
|
2405
|
+
'X-Vault-Key': vaultKey,
|
|
2406
|
+
},
|
|
2407
|
+
body: JSON.stringify({
|
|
2408
|
+
linked_service: link.linked_service,
|
|
2409
|
+
token: link.token,
|
|
2410
|
+
linked_service_data: link.linked_service_data,
|
|
2411
|
+
}),
|
|
2412
|
+
});
|
|
2413
|
+
|
|
2414
|
+
if (!response.ok) {
|
|
2415
|
+
throw new Error(`Vault service link failed: ${response.status} ${await response.text()}`);
|
|
2416
|
+
}
|
|
2417
|
+
return await response.json() as { vault: Vault; message: string };
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
/**
|
|
2421
|
+
* Update a link: edit the non-secret selection rules, rotate the token, or
|
|
2422
|
+
* both. `vaultKey` is required only when `token` is supplied, mirroring
|
|
2423
|
+
* `cloudBrowserVaultItemUpdate`; a config-only edit needs no key.
|
|
2424
|
+
*
|
|
2425
|
+
* A token rotation also clears the server's one-hour auth back-off, so a link
|
|
2426
|
+
* broken by a dead token syncs again on the next round.
|
|
2427
|
+
*/
|
|
2428
|
+
async cloudBrowserVaultServiceUpdate(
|
|
2429
|
+
vaultId: string,
|
|
2430
|
+
opts: VaultServiceUpdate & { vaultKey?: string },
|
|
2431
|
+
): Promise<{ vault: Vault; message: string }> {
|
|
2432
|
+
if (opts.token !== undefined && opts.token !== '' && (opts.vaultKey === undefined || opts.vaultKey === '')) {
|
|
2433
|
+
throw new Error(
|
|
2434
|
+
'cloudBrowserVaultServiceUpdate: vaultKey is required when rotating the service token',
|
|
2435
|
+
);
|
|
2436
|
+
}
|
|
2437
|
+
const url = new URL(
|
|
2438
|
+
this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service',
|
|
2439
|
+
);
|
|
2440
|
+
url.searchParams.set('key', this.key);
|
|
2441
|
+
|
|
2442
|
+
const body: Record<string, unknown> = {};
|
|
2443
|
+
if (opts.token !== undefined) body.token = opts.token;
|
|
2444
|
+
if (opts.linked_service_data !== undefined) body.linked_service_data = opts.linked_service_data;
|
|
2445
|
+
|
|
2446
|
+
const headers: Record<string, string> = {
|
|
2447
|
+
'content-type': 'application/json',
|
|
2448
|
+
'user-agent': this.ua,
|
|
2449
|
+
};
|
|
2450
|
+
if (opts.vaultKey !== undefined && opts.vaultKey !== '') {
|
|
2451
|
+
headers['X-Vault-Key'] = opts.vaultKey;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
const response = await this.fetch({
|
|
2455
|
+
url: url.toString(),
|
|
2456
|
+
method: 'PATCH',
|
|
2457
|
+
headers,
|
|
2458
|
+
body: JSON.stringify(body),
|
|
2459
|
+
});
|
|
2460
|
+
|
|
2461
|
+
if (!response.ok) {
|
|
2462
|
+
throw new Error(`Vault service update failed: ${response.status} ${await response.text()}`);
|
|
2463
|
+
}
|
|
2464
|
+
return await response.json() as { vault: Vault; message: string };
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
/**
|
|
2468
|
+
* Unlink the provider. `keepItems` governs only the mirrored rows — kept as
|
|
2469
|
+
* plain manual items, or deleted — while the sealed token is removed either
|
|
2470
|
+
* way, so no vault key is needed.
|
|
2471
|
+
*
|
|
2472
|
+
* Dropping the rows is irreversible, so the default is to keep them and the
|
|
2473
|
+
* flag always goes on the wire explicitly rather than relying on a default at
|
|
2474
|
+
* either end.
|
|
2475
|
+
*/
|
|
2476
|
+
async cloudBrowserVaultServiceUnlink(
|
|
2477
|
+
vaultId: string,
|
|
2478
|
+
opts: { keepItems?: boolean } = {},
|
|
2479
|
+
): Promise<{ success: boolean; message: string }> {
|
|
2480
|
+
const url = new URL(
|
|
2481
|
+
this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service',
|
|
2482
|
+
);
|
|
2483
|
+
url.searchParams.set('key', this.key);
|
|
2484
|
+
url.searchParams.set('keep_items', (opts.keepItems ?? true) ? 'true' : 'false');
|
|
2485
|
+
|
|
2486
|
+
const response = await this.fetch({
|
|
2487
|
+
url: url.toString(),
|
|
2488
|
+
method: 'DELETE',
|
|
2489
|
+
headers: { 'user-agent': this.ua },
|
|
2490
|
+
});
|
|
2491
|
+
|
|
2492
|
+
if (!response.ok) {
|
|
2493
|
+
throw new Error(`Vault service unlink failed: ${response.status} ${await response.text()}`);
|
|
2494
|
+
}
|
|
2495
|
+
const body = await response.json() as Record<string, any>;
|
|
2496
|
+
return {
|
|
2497
|
+
success: body.success !== undefined ? Boolean(body.success) : true,
|
|
2498
|
+
message: typeof body.message === 'string' ? body.message : '',
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
/**
|
|
2503
|
+
* Force a reconcile against the provider now, bypassing the sync TTL and the
|
|
2504
|
+
* back-off a failed round leaves behind. Requires the vault key: the server
|
|
2505
|
+
* opens the sealed token with it and re-seals every mirrored row.
|
|
2506
|
+
*
|
|
2507
|
+
* The server budget is 25s; the SDK pins no per-call timeout, so the runtime's
|
|
2508
|
+
* own fetch default applies.
|
|
2509
|
+
*/
|
|
2510
|
+
async cloudBrowserVaultServiceSync(vaultId: string, vaultKey: string): Promise<VaultSyncReport> {
|
|
2511
|
+
const url = new URL(
|
|
2512
|
+
this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/sync',
|
|
2513
|
+
);
|
|
2514
|
+
url.searchParams.set('key', this.key);
|
|
2515
|
+
|
|
2516
|
+
const response = await this.fetch({
|
|
2517
|
+
url: url.toString(),
|
|
2518
|
+
method: 'POST',
|
|
2519
|
+
headers: {
|
|
2520
|
+
'user-agent': this.ua,
|
|
2521
|
+
'X-Vault-Key': vaultKey,
|
|
2522
|
+
},
|
|
2523
|
+
});
|
|
2524
|
+
|
|
2525
|
+
if (!response.ok) {
|
|
2526
|
+
throw new Error(`Vault service sync failed: ${response.status} ${await response.text()}`);
|
|
2527
|
+
}
|
|
2528
|
+
return await response.json() as VaultSyncReport;
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
/**
|
|
2532
|
+
* Probe the provider: proves a token is live and lists the upstream vaults it
|
|
2533
|
+
* can read. Writes nothing, so it never moves the vault's sync state.
|
|
2534
|
+
*
|
|
2535
|
+
* With no `token` the sealed token of an existing link is probed (the vault
|
|
2536
|
+
* key opens it). Passing an unsaved `token` instead enumerates the upstream
|
|
2537
|
+
* vaults BEFORE a link exists, which is how a caller picks `vault_id`.
|
|
2538
|
+
*
|
|
2539
|
+
* `linkedService` stays optional and undefaulted here: this is the one endpoint
|
|
2540
|
+
* whose empty discriminator the server itself resolves to 1Password, and a
|
|
2541
|
+
* client-side default would send a field the bodyless stored-token path must
|
|
2542
|
+
* not carry.
|
|
2543
|
+
*
|
|
2544
|
+
* The server budget is 10s; the SDK pins no per-call timeout, so the runtime's
|
|
2545
|
+
* own fetch default applies.
|
|
2546
|
+
*/
|
|
2547
|
+
async cloudBrowserVaultServiceTest(
|
|
2548
|
+
vaultId: string,
|
|
2549
|
+
vaultKey: string,
|
|
2550
|
+
opts: { linkedService?: VaultLinkedServiceValue; token?: string } = {},
|
|
2551
|
+
): Promise<VaultProbeResult> {
|
|
2552
|
+
const url = new URL(
|
|
2553
|
+
this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/test',
|
|
2554
|
+
);
|
|
2555
|
+
url.searchParams.set('key', this.key);
|
|
2556
|
+
|
|
2557
|
+
const headers: Record<string, string> = {
|
|
2558
|
+
'user-agent': this.ua,
|
|
2559
|
+
'X-Vault-Key': vaultKey,
|
|
2560
|
+
};
|
|
2561
|
+
// A bodyless request is what selects the stored-token path server-side, so
|
|
2562
|
+
// send a body only when the caller supplied something to probe with.
|
|
2563
|
+
let body: string | undefined;
|
|
2564
|
+
if (opts.token !== undefined || opts.linkedService !== undefined) {
|
|
2565
|
+
const payload: Record<string, unknown> = {};
|
|
2566
|
+
if (opts.linkedService !== undefined) payload.linked_service = opts.linkedService;
|
|
2567
|
+
if (opts.token !== undefined) payload.token = opts.token;
|
|
2568
|
+
body = JSON.stringify(payload);
|
|
2569
|
+
headers['content-type'] = 'application/json';
|
|
2570
|
+
}
|
|
2571
|
+
|
|
2572
|
+
const response = await this.fetch({
|
|
2573
|
+
url: url.toString(),
|
|
2574
|
+
method: 'POST',
|
|
2575
|
+
headers,
|
|
2576
|
+
body,
|
|
2577
|
+
});
|
|
2578
|
+
|
|
2579
|
+
if (!response.ok) {
|
|
2580
|
+
throw new Error(`Vault service test failed: ${response.status} ${await response.text()}`);
|
|
2581
|
+
}
|
|
2582
|
+
const json = await response.json() as VaultProbeResult & { vaults_visible: VaultProbeVault[] | null };
|
|
2583
|
+
return { ...json, vaults_visible: json.vaults_visible ?? [] };
|
|
2584
|
+
}
|
|
2585
|
+
|
|
1864
2586
|
/**
|
|
1865
2587
|
* Download a debug session recording video.
|
|
1866
2588
|
* Returns the video as an ArrayBuffer (stream from server).
|
|
@@ -1954,7 +2676,12 @@ export class ScrapflyClient {
|
|
|
1954
2676
|
// -------------------------------------------------------------------------
|
|
1955
2677
|
|
|
1956
2678
|
/** Create a Web Scraping API schedule. `scrape_config` is the same shape
|
|
1957
|
-
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`).
|
|
2679
|
+
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
|
|
2680
|
+
* forwarded to the API verbatim, so its keys are wire keys, not the SDK
|
|
2681
|
+
* option names. The anti-bot bypass may be spelled either way here: the API
|
|
2682
|
+
* folds `unblocker` into `asp` on the STORED config, with the same precedence
|
|
2683
|
+
* the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
|
|
2684
|
+
* absent, `null` or `""`), so both names reach the replayed scrape. */
|
|
1958
2685
|
async createScrapeSchedule(
|
|
1959
2686
|
scrapeConfig: Record<string, unknown>,
|
|
1960
2687
|
request: CreateScheduleRequest,
|
|
@@ -1980,7 +2707,11 @@ export class ScrapflyClient {
|
|
|
1980
2707
|
) as Schedule;
|
|
1981
2708
|
}
|
|
1982
2709
|
|
|
1983
|
-
/** Create a Crawler API schedule.
|
|
2710
|
+
/** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
|
|
2711
|
+
* its keys are wire keys, not the SDK option names. As with
|
|
2712
|
+
* `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
|
|
2713
|
+
* `unblocker`: the API folds the alias into `asp` on the stored config before
|
|
2714
|
+
* it is ever replayed. */
|
|
1984
2715
|
async createCrawlerSchedule(
|
|
1985
2716
|
crawlerConfig: Record<string, unknown>,
|
|
1986
2717
|
request: CreateScheduleRequest,
|
|
@@ -1998,7 +2729,7 @@ export class ScrapflyClient {
|
|
|
1998
2729
|
return await this.scheduleRequest('GET', `/schedules/${encodeURIComponent(id)}`) as Schedule;
|
|
1999
2730
|
}
|
|
2000
2731
|
|
|
2001
|
-
/** List
|
|
2732
|
+
/** List the schedules of the API key's project and environment, optionally filtered by kind/status. */
|
|
2002
2733
|
async listSchedules(opts?: ListSchedulesOptions): Promise<Schedule[]> {
|
|
2003
2734
|
return await this.scheduleRequest(
|
|
2004
2735
|
'GET',
|