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/crawlerresult.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { ScrapflyCrawlerError } from './errors.js';
|
|
1
2
|
import { writeFile } from './polyfill.js';
|
|
3
|
+
import type { Rec } from './types.js';
|
|
2
4
|
|
|
3
5
|
/**
|
|
4
6
|
* Pull a required field out of an API response body and fail loud if it's
|
|
@@ -119,6 +121,13 @@ export class CrawlerStatus {
|
|
|
119
121
|
/** `null` while the crawler is still running; bool once terminal. */
|
|
120
122
|
is_success: boolean | null;
|
|
121
123
|
state: CrawlerState;
|
|
124
|
+
/**
|
|
125
|
+
* `null` unless the crawl was started with `search: true`. Polling this is
|
|
126
|
+
* the webhook-free way to learn when the index became queryable.
|
|
127
|
+
*/
|
|
128
|
+
search: CrawlerSearchState | null;
|
|
129
|
+
/** `null` unless the crawl re-scrapes itself on a period. */
|
|
130
|
+
refresh: CrawlerRefreshState | null;
|
|
122
131
|
|
|
123
132
|
constructor(data: Record<string, any>) {
|
|
124
133
|
// Canonical API field name is `crawler_uuid`; accept short `uuid` as a
|
|
@@ -159,6 +168,15 @@ export class CrawlerStatus {
|
|
|
159
168
|
stop_time: optionalField<number>(state, 'stop_time', 'number', 'CrawlerStatus.state'),
|
|
160
169
|
stop_reason: optionalField<CrawlerStopReason>(state, 'stop_reason', 'string', 'CrawlerStatus.state'),
|
|
161
170
|
};
|
|
171
|
+
|
|
172
|
+
// Both blocks go through their field whitelist rather than a cast to the
|
|
173
|
+
// interface. A cast is a compile-time claim only: raw JSON rides through
|
|
174
|
+
// it, so a field the model never declared still reaches the caller and a
|
|
175
|
+
// field the model lost still looks decoded.
|
|
176
|
+
const search = optionalField<Record<string, any>>(data, 'search', 'object', 'CrawlerStatus');
|
|
177
|
+
this.search = search ? parseCrawlerSearchState(search) : null;
|
|
178
|
+
const refresh = optionalField<Record<string, any>>(data, 'refresh', 'object', 'CrawlerStatus');
|
|
179
|
+
this.refresh = refresh ? parseCrawlerRefreshState(refresh) : null;
|
|
162
180
|
}
|
|
163
181
|
|
|
164
182
|
/** True while the crawler is still working (PENDING or RUNNING). */
|
|
@@ -190,6 +208,496 @@ export class CrawlerStatus {
|
|
|
190
208
|
}
|
|
191
209
|
}
|
|
192
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Which retrieval legs a search runs. `hybrid` runs both and merges them with
|
|
213
|
+
* reciprocal rank fusion; it is the server default when the field is omitted.
|
|
214
|
+
*/
|
|
215
|
+
export type CrawlerSearchMode = 'vector' | 'fts' | 'hybrid';
|
|
216
|
+
|
|
217
|
+
/** Lifecycle of a crawl's auto-refresh loop. */
|
|
218
|
+
export type CrawlerRefreshStatus = 'DISABLED' | 'SCHEDULED' | 'RUNNING' | 'FAILED';
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* One row of a crawl's refresh timeline.
|
|
222
|
+
*
|
|
223
|
+
* `sample_updated` / `sample_removed` carry at most ten URLs each. The full
|
|
224
|
+
* lists are never inlined: a 5,000-page crawl would otherwise put 5,000
|
|
225
|
+
* strings into every status poll.
|
|
226
|
+
*/
|
|
227
|
+
export interface CrawlerRefreshEntry {
|
|
228
|
+
at?: string;
|
|
229
|
+
/** Refresh generation this run produced, 1 for the first. */
|
|
230
|
+
generation?: number;
|
|
231
|
+
/** URLs this run discovered that the crawl did not hold. */
|
|
232
|
+
added?: number;
|
|
233
|
+
/** Known URLs whose content fingerprint changed. */
|
|
234
|
+
updated?: number;
|
|
235
|
+
/** Known URLs that no longer exist and were dropped. */
|
|
236
|
+
removed?: number;
|
|
237
|
+
/** Re-scraped with an identical fingerprint: no embedding, no index write. */
|
|
238
|
+
unchanged?: number;
|
|
239
|
+
/** URLs the run could not fetch. They keep their previous content. */
|
|
240
|
+
failed?: number;
|
|
241
|
+
duration_ms?: number;
|
|
242
|
+
search_status?: string;
|
|
243
|
+
error?: string;
|
|
244
|
+
/** Up to ten re-indexed URLs. */
|
|
245
|
+
sample_updated?: string[];
|
|
246
|
+
/** Up to ten dropped URLs. */
|
|
247
|
+
sample_removed?: string[];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* The `refresh` block of a crawl, carried by `GET /crawl/{uuid}/status` and
|
|
252
|
+
* returned by the three refresh calls.
|
|
253
|
+
*
|
|
254
|
+
* Parsed leniently: older API builds omit the block entirely.
|
|
255
|
+
*/
|
|
256
|
+
export interface CrawlerRefreshState {
|
|
257
|
+
enabled: boolean;
|
|
258
|
+
/** Period between runs in seconds; 0 when disabled. */
|
|
259
|
+
interval_seconds: number;
|
|
260
|
+
status: CrawlerRefreshStatus;
|
|
261
|
+
/** Number of refresh runs completed so far. */
|
|
262
|
+
generation?: number;
|
|
263
|
+
last_run_at?: string;
|
|
264
|
+
/** Absent while refresh is disabled. */
|
|
265
|
+
next_run_at?: string;
|
|
266
|
+
error?: string;
|
|
267
|
+
/**
|
|
268
|
+
* When the run currently in flight began. Only `GET /crawl/{uuid}/status`
|
|
269
|
+
* carries it: the three refresh routes render a typed state that does not
|
|
270
|
+
* declare the field, so it is optional on both paths.
|
|
271
|
+
*/
|
|
272
|
+
started_at?: string;
|
|
273
|
+
/**
|
|
274
|
+
* Consecutive failed runs; reset to 0 by the first run that succeeds. Same
|
|
275
|
+
* route asymmetry as `started_at`.
|
|
276
|
+
*/
|
|
277
|
+
consecutive_failures?: number;
|
|
278
|
+
/** Newest last, capped at the 50 most recent runs. */
|
|
279
|
+
history?: CrawlerRefreshEntry[];
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Pages a run actually touched. Zero means the site stood still. */
|
|
283
|
+
export function refreshChanged(entry: CrawlerRefreshEntry | null | undefined): number {
|
|
284
|
+
return (entry?.added ?? 0) + (entry?.updated ?? 0) + (entry?.removed ?? 0);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Normalize a refresh envelope.
|
|
289
|
+
*
|
|
290
|
+
* The three refresh endpoints answer with the state at the top level;
|
|
291
|
+
* `GET /status` nests it under `refresh`. Accepting both means the SDK never
|
|
292
|
+
* has to guess which call produced the payload.
|
|
293
|
+
*
|
|
294
|
+
* This is a field whitelist, not a spread: a key that is not named here never
|
|
295
|
+
* reaches the caller, whatever the interface declares.
|
|
296
|
+
*/
|
|
297
|
+
export function parseCrawlerRefreshState(data: Record<string, any>): CrawlerRefreshState {
|
|
298
|
+
const block = data && typeof data.refresh === 'object' && data.refresh !== null ? data.refresh : data;
|
|
299
|
+
return {
|
|
300
|
+
enabled: block.enabled === true,
|
|
301
|
+
interval_seconds: typeof block.interval_seconds === 'number' ? block.interval_seconds : 0,
|
|
302
|
+
status: (block.status as CrawlerRefreshStatus) ?? 'DISABLED',
|
|
303
|
+
generation: block.generation,
|
|
304
|
+
last_run_at: block.last_run_at ?? undefined,
|
|
305
|
+
next_run_at: block.next_run_at ?? undefined,
|
|
306
|
+
error: block.error ?? undefined,
|
|
307
|
+
started_at: block.started_at ?? undefined,
|
|
308
|
+
consecutive_failures: block.consecutive_failures ?? undefined,
|
|
309
|
+
history: Array.isArray(block.history) ? (block.history as CrawlerRefreshEntry[]) : [],
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export type CrawlerSearchStatus = 'DISABLED' | 'BUILDING' | 'READY' | 'PARTIAL' | 'FAILED';
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The `search` block describing a crawl's index, carried by
|
|
317
|
+
* `GET /crawl/{uuid}/status` and by the two search webhooks.
|
|
318
|
+
*
|
|
319
|
+
* Parsed leniently: the block is sparse on failure and older API builds omit
|
|
320
|
+
* it entirely.
|
|
321
|
+
*/
|
|
322
|
+
export interface CrawlerSearchState {
|
|
323
|
+
status: CrawlerSearchStatus;
|
|
324
|
+
/** Storage path of the index manifest; absent until the artifact is published. */
|
|
325
|
+
manifest?: string;
|
|
326
|
+
/** Crawled pages represented in the index. */
|
|
327
|
+
documents?: number;
|
|
328
|
+
/** Embedded chunks those pages were split into. */
|
|
329
|
+
vectors?: number;
|
|
330
|
+
/** Chunks discarded during the build (embedding failures, oversized rows). */
|
|
331
|
+
dropped?: number;
|
|
332
|
+
queue_depth?: number;
|
|
333
|
+
fragments?: number;
|
|
334
|
+
error?: string;
|
|
335
|
+
built_at?: string;
|
|
336
|
+
/** Vector index type (e.g. `IVF_PQ`); absent below the index threshold. */
|
|
337
|
+
index?: string;
|
|
338
|
+
/**
|
|
339
|
+
* Bumped when a paused crawl resumes and rebuilds. Results from different
|
|
340
|
+
* generations are not comparable.
|
|
341
|
+
*/
|
|
342
|
+
generation?: number;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** True when the index can answer a query right now. */
|
|
346
|
+
export function isSearchable(state: CrawlerSearchState | null | undefined): boolean {
|
|
347
|
+
return state?.status === 'READY' || state?.status === 'PARTIAL';
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Normalize a search envelope.
|
|
352
|
+
*
|
|
353
|
+
* `GET /status` nests the block under `search` and so do the two search
|
|
354
|
+
* webhooks; taking the block on its own as well means a caller holding either
|
|
355
|
+
* envelope decodes the same way.
|
|
356
|
+
*
|
|
357
|
+
* This is a field whitelist, not a spread: a key that is not named here never
|
|
358
|
+
* reaches the caller, whatever the interface declares. `status` is the one
|
|
359
|
+
* field with no sane absent value, so a block without it reads as DISABLED.
|
|
360
|
+
*/
|
|
361
|
+
export function parseCrawlerSearchState(data: Record<string, any>): CrawlerSearchState {
|
|
362
|
+
const block = data && typeof data.search === 'object' && data.search !== null ? data.search : data;
|
|
363
|
+
return {
|
|
364
|
+
status: (block.status as CrawlerSearchStatus) ?? 'DISABLED',
|
|
365
|
+
manifest: block.manifest ?? undefined,
|
|
366
|
+
documents: block.documents ?? undefined,
|
|
367
|
+
vectors: block.vectors ?? undefined,
|
|
368
|
+
dropped: block.dropped ?? undefined,
|
|
369
|
+
queue_depth: block.queue_depth ?? undefined,
|
|
370
|
+
fragments: block.fragments ?? undefined,
|
|
371
|
+
error: block.error ?? undefined,
|
|
372
|
+
built_at: block.built_at ?? undefined,
|
|
373
|
+
index: block.index ?? undefined,
|
|
374
|
+
generation: block.generation ?? undefined,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Per-leg scores behind a result. Which keys appear depends on the mode. */
|
|
379
|
+
export interface CrawlerSearchScores {
|
|
380
|
+
vector?: number;
|
|
381
|
+
fts?: number;
|
|
382
|
+
rrf?: number;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* One matched chunk from `POST /crawl/search`.
|
|
387
|
+
*
|
|
388
|
+
* A result is a chunk, not a page: `chunk_id` orders chunks within one crawled
|
|
389
|
+
* document and `text` is only the matched slice. Expand a hit back to the
|
|
390
|
+
* whole document through `contents_url`, or through `warc_offset`/`warc_end`
|
|
391
|
+
* against the crawl's WARC artifact.
|
|
392
|
+
*/
|
|
393
|
+
export interface CrawlerSearchResult {
|
|
394
|
+
rank: number;
|
|
395
|
+
score: number;
|
|
396
|
+
scores: CrawlerSearchScores;
|
|
397
|
+
crawler_uuid: string;
|
|
398
|
+
url: string;
|
|
399
|
+
title: string | null;
|
|
400
|
+
source_format: string | null;
|
|
401
|
+
content_type: string | null;
|
|
402
|
+
chunk_id: number;
|
|
403
|
+
text: string;
|
|
404
|
+
warc_offset: number | null;
|
|
405
|
+
warc_end: number | null;
|
|
406
|
+
contents_url: string | null;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** A crawl that was opened and searched. */
|
|
410
|
+
export interface CrawlerSearchCrawl {
|
|
411
|
+
crawler_uuid: string;
|
|
412
|
+
documents?: number;
|
|
413
|
+
vectors?: number;
|
|
414
|
+
index?: string;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Why a requested crawl contributed nothing. A skip is never fatal. */
|
|
418
|
+
export type CrawlerSkipReason =
|
|
419
|
+
| 'search_not_enabled'
|
|
420
|
+
| 'search_not_ready'
|
|
421
|
+
| 'search_failed'
|
|
422
|
+
| 'search_disabled'
|
|
423
|
+
| 'incompatible_index'
|
|
424
|
+
| 'deadline';
|
|
425
|
+
|
|
426
|
+
export interface CrawlerSearchSkipped {
|
|
427
|
+
crawler_uuid: string;
|
|
428
|
+
reason: CrawlerSkipReason;
|
|
429
|
+
status?: string;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Fan-out timing and IO counters. */
|
|
433
|
+
export interface CrawlerSearchStats {
|
|
434
|
+
duration_ms?: number;
|
|
435
|
+
crawls_searched?: number;
|
|
436
|
+
candidates?: number;
|
|
437
|
+
gcs_gets?: number;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Wraps the JSON response of `POST /crawl/search`.
|
|
442
|
+
*
|
|
443
|
+
* The envelope states its own completeness: `exact` with most crawls unopened
|
|
444
|
+
* is the normal outcome, because the fan-out proves via an admissible bound
|
|
445
|
+
* that the unopened crawls held nothing better. `partial` means the deadline
|
|
446
|
+
* cut the fan-out short.
|
|
447
|
+
*
|
|
448
|
+
* Strict on the fields the contract always carries, lenient on the rest, so
|
|
449
|
+
* drift in the ranking envelope surfaces at parse time rather than as an
|
|
450
|
+
* empty result list.
|
|
451
|
+
*/
|
|
452
|
+
export class CrawlerSearchResponse {
|
|
453
|
+
query: string;
|
|
454
|
+
mode: CrawlerSearchMode;
|
|
455
|
+
limit: number;
|
|
456
|
+
completeness: 'exact' | 'partial';
|
|
457
|
+
results: CrawlerSearchResult[];
|
|
458
|
+
crawls: CrawlerSearchCrawl[];
|
|
459
|
+
skipped: CrawlerSearchSkipped[];
|
|
460
|
+
stats: CrawlerSearchStats;
|
|
461
|
+
|
|
462
|
+
crawls_requested: number | null;
|
|
463
|
+
crawls_searched: number | null;
|
|
464
|
+
crawls_pruned_exact: number | null;
|
|
465
|
+
/**
|
|
466
|
+
* The crawls the deadline cut, and the crawls whose index could not be read,
|
|
467
|
+
* named rather than counted: a caller told "3 failed" cannot retry them.
|
|
468
|
+
*/
|
|
469
|
+
crawls_skipped_deadline: string[] | null;
|
|
470
|
+
crawls_failed: CrawlerSearchSkipped[] | null;
|
|
471
|
+
/**
|
|
472
|
+
* `null` until a crawl has actually been opened. Zero is a different claim:
|
|
473
|
+
* it says the best unsearched score was 0, not that no bound exists.
|
|
474
|
+
*/
|
|
475
|
+
theta: number | null;
|
|
476
|
+
max_ub_unsearched: number | null;
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Opaque token for the next page, `null` on the last one. Paging is
|
|
480
|
+
* cursor-based: an offset over a partial fan-out would re-run the legs and
|
|
481
|
+
* shift ranks.
|
|
482
|
+
*/
|
|
483
|
+
cursor: string | null;
|
|
484
|
+
|
|
485
|
+
constructor(data: Record<string, any>) {
|
|
486
|
+
this.query = requireField<string>(data, 'query', 'string', 'CrawlerSearchResponse');
|
|
487
|
+
this.mode = requireField<CrawlerSearchMode>(data, 'mode', 'string', 'CrawlerSearchResponse');
|
|
488
|
+
this.limit = requireField<number>(data, 'limit', 'number', 'CrawlerSearchResponse');
|
|
489
|
+
this.completeness = requireField<'exact' | 'partial'>(
|
|
490
|
+
data,
|
|
491
|
+
'completeness',
|
|
492
|
+
'string',
|
|
493
|
+
'CrawlerSearchResponse',
|
|
494
|
+
);
|
|
495
|
+
|
|
496
|
+
const results = requireField<Record<string, any>[]>(data, 'results', 'array', 'CrawlerSearchResponse');
|
|
497
|
+
this.results = results.map((r, i) => {
|
|
498
|
+
const context = `CrawlerSearchResponse.results[${i}]`;
|
|
499
|
+
return {
|
|
500
|
+
rank: requireField<number>(r, 'rank', 'number', context),
|
|
501
|
+
score: requireField<number>(r, 'score', 'number', context),
|
|
502
|
+
scores: optionalField<CrawlerSearchScores>(r, 'scores', 'object', context) ?? {},
|
|
503
|
+
crawler_uuid: requireField<string>(r, 'crawler_uuid', 'string', context),
|
|
504
|
+
url: requireField<string>(r, 'url', 'string', context),
|
|
505
|
+
title: optionalField<string>(r, 'title', 'string', context),
|
|
506
|
+
source_format: optionalField<string>(r, 'source_format', 'string', context),
|
|
507
|
+
content_type: optionalField<string>(r, 'content_type', 'string', context),
|
|
508
|
+
chunk_id: requireField<number>(r, 'chunk_id', 'number', context),
|
|
509
|
+
text: requireField<string>(r, 'text', 'string', context),
|
|
510
|
+
warc_offset: optionalField<number>(r, 'warc_offset', 'number', context),
|
|
511
|
+
warc_end: optionalField<number>(r, 'warc_end', 'number', context),
|
|
512
|
+
contents_url: optionalField<string>(r, 'contents_url', 'string', context),
|
|
513
|
+
};
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
this.crawls = optionalField<CrawlerSearchCrawl[]>(data, 'crawls', 'array', 'CrawlerSearchResponse') ?? [];
|
|
517
|
+
this.skipped = optionalField<CrawlerSearchSkipped[]>(data, 'skipped', 'array', 'CrawlerSearchResponse') ?? [];
|
|
518
|
+
this.stats = optionalField<CrawlerSearchStats>(data, 'stats', 'object', 'CrawlerSearchResponse') ?? {};
|
|
519
|
+
|
|
520
|
+
this.crawls_requested = optionalField<number>(data, 'crawls_requested', 'number', 'CrawlerSearchResponse');
|
|
521
|
+
this.crawls_searched = optionalField<number>(data, 'crawls_searched', 'number', 'CrawlerSearchResponse');
|
|
522
|
+
this.crawls_pruned_exact = optionalField<number>(data, 'crawls_pruned_exact', 'number', 'CrawlerSearchResponse');
|
|
523
|
+
this.crawls_skipped_deadline = optionalField<string[]>(
|
|
524
|
+
data,
|
|
525
|
+
'crawls_skipped_deadline',
|
|
526
|
+
'array',
|
|
527
|
+
'CrawlerSearchResponse',
|
|
528
|
+
);
|
|
529
|
+
this.crawls_failed = optionalField<CrawlerSearchSkipped[]>(
|
|
530
|
+
data,
|
|
531
|
+
'crawls_failed',
|
|
532
|
+
'array',
|
|
533
|
+
'CrawlerSearchResponse',
|
|
534
|
+
);
|
|
535
|
+
this.theta = optionalField<number>(data, 'theta', 'number', 'CrawlerSearchResponse');
|
|
536
|
+
this.max_ub_unsearched = optionalField<number>(data, 'max_ub_unsearched', 'number', 'CrawlerSearchResponse');
|
|
537
|
+
|
|
538
|
+
this.cursor = optionalField<string>(data, 'cursor', 'string', 'CrawlerSearchResponse');
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** True when the ranking is provably complete for the requested crawls. */
|
|
542
|
+
get isExact(): boolean {
|
|
543
|
+
return this.completeness === 'exact';
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** One retrieved chunk the answer may cite. */
|
|
548
|
+
export interface CrawlerPromptSource {
|
|
549
|
+
id: number;
|
|
550
|
+
crawler_uuid: string;
|
|
551
|
+
url: string;
|
|
552
|
+
title?: string;
|
|
553
|
+
score?: number;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
/** Payload of the terminal `done` frame. */
|
|
558
|
+
export interface CrawlerPromptDone {
|
|
559
|
+
sources_used?: number[];
|
|
560
|
+
/** Retrieved chunks that did not fit the context and never reached the model. */
|
|
561
|
+
sources_dropped?: number;
|
|
562
|
+
/**
|
|
563
|
+
* True when the model hit its output cap. The answer is still delivered;
|
|
564
|
+
* whether to use it is the caller's call.
|
|
565
|
+
*/
|
|
566
|
+
truncated?: boolean;
|
|
567
|
+
/** Actual charge, including zero. Undefined when the server does not report it. */
|
|
568
|
+
api_credit?: number;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* One decoded frame of the `POST /crawl/prompt` stream.
|
|
573
|
+
*
|
|
574
|
+
* Frames arrive as `source`*, then `token`*, then one `done`, or one `error`
|
|
575
|
+
* which is thrown rather than yielded because generation can fail after
|
|
576
|
+
* tokens have already been delivered.
|
|
577
|
+
*/
|
|
578
|
+
export type CrawlerPromptEvent =
|
|
579
|
+
| { event: 'source'; data: CrawlerPromptSource }
|
|
580
|
+
| { event: 'token'; data: string }
|
|
581
|
+
| { event: 'done'; data: CrawlerPromptDone };
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Decode the `POST /crawl/prompt` SSE body into typed frames.
|
|
585
|
+
*
|
|
586
|
+
* Only `event:` and `data:` lines matter; `:keepalive` comment frames exist
|
|
587
|
+
* to keep intermediaries from closing an idle connection and carry nothing.
|
|
588
|
+
* Token payloads are JSON strings; every other frame is a JSON object.
|
|
589
|
+
*
|
|
590
|
+
* An `event: error` frame throws rather than yields: the caller is already
|
|
591
|
+
* inside a `for await` and a yielded error object is too easy to ignore after
|
|
592
|
+
* tokens have started arriving.
|
|
593
|
+
*
|
|
594
|
+
* Decoding is explicitly UTF-8 with `stream: true`, because a multi-byte
|
|
595
|
+
* character can straddle two chunks of the body.
|
|
596
|
+
* EOF before a complete `done` frame throws, even after tokens were delivered.
|
|
597
|
+
*/
|
|
598
|
+
export async function* parseCrawlerPromptStream(
|
|
599
|
+
body: ReadableStream<Uint8Array>,
|
|
600
|
+
): AsyncGenerator<CrawlerPromptEvent, void, undefined> {
|
|
601
|
+
const reader = body.getReader();
|
|
602
|
+
const decoder = new TextDecoder('utf-8');
|
|
603
|
+
let buffer = '';
|
|
604
|
+
let eventName = '';
|
|
605
|
+
let data: string[] = [];
|
|
606
|
+
|
|
607
|
+
const decodeFrame = (name: string, raw: string): CrawlerPromptEvent | null => {
|
|
608
|
+
if (name === 'token') {
|
|
609
|
+
let token: string;
|
|
610
|
+
try {
|
|
611
|
+
token = JSON.parse(raw) as string;
|
|
612
|
+
} catch {
|
|
613
|
+
// A server sending bare text instead of a JSON string is still
|
|
614
|
+
// sending a token; do not drop the answer over the quoting.
|
|
615
|
+
token = raw;
|
|
616
|
+
}
|
|
617
|
+
return { event: 'token', data: token };
|
|
618
|
+
}
|
|
619
|
+
if (name === 'source') {
|
|
620
|
+
return { event: 'source', data: JSON.parse(raw) as CrawlerPromptSource };
|
|
621
|
+
}
|
|
622
|
+
if (name === 'done') {
|
|
623
|
+
const payload = JSON.parse(raw) as Rec<any>;
|
|
624
|
+
// Build the public result explicitly: a TypeScript cast does not remove
|
|
625
|
+
// legacy model, token or provider-cost fields from the runtime object.
|
|
626
|
+
return {
|
|
627
|
+
event: 'done',
|
|
628
|
+
data: {
|
|
629
|
+
sources_used: optionalField<number[]>(payload, 'sources_used', 'array', 'CrawlerPromptDone') ?? undefined,
|
|
630
|
+
sources_dropped: optionalField<number>(payload, 'sources_dropped', 'number', 'CrawlerPromptDone') ?? undefined,
|
|
631
|
+
truncated: optionalField<boolean>(payload, 'truncated', 'boolean', 'CrawlerPromptDone') ?? undefined,
|
|
632
|
+
api_credit: optionalField<number>(payload, 'api_credit', 'number', 'CrawlerPromptDone') ?? undefined,
|
|
633
|
+
},
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
if (name === 'error') {
|
|
637
|
+
let payload: Rec<any> = {};
|
|
638
|
+
try {
|
|
639
|
+
payload = JSON.parse(raw) as Rec<any>;
|
|
640
|
+
} catch {
|
|
641
|
+
payload = { message: raw };
|
|
642
|
+
}
|
|
643
|
+
throw new ScrapflyCrawlerError(payload.message ?? raw, {
|
|
644
|
+
code: (payload.code ?? 'ERR::CRAWLER::UNKNOWN') as string,
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
return null;
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
try {
|
|
651
|
+
for (;;) {
|
|
652
|
+
const { done, value } = await reader.read();
|
|
653
|
+
if (value !== undefined) {
|
|
654
|
+
buffer += decoder.decode(value, { stream: true });
|
|
655
|
+
}
|
|
656
|
+
if (done) {
|
|
657
|
+
buffer += decoder.decode();
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
let newline = buffer.indexOf('\n');
|
|
661
|
+
while (newline !== -1) {
|
|
662
|
+
const line = buffer.slice(0, newline).replace(/\r$/, '');
|
|
663
|
+
buffer = buffer.slice(newline + 1);
|
|
664
|
+
newline = buffer.indexOf('\n');
|
|
665
|
+
|
|
666
|
+
if (line.startsWith(':')) continue;
|
|
667
|
+
|
|
668
|
+
// A blank line terminates a frame.
|
|
669
|
+
if (line === '') {
|
|
670
|
+
if (eventName !== '' && data.length > 0) {
|
|
671
|
+
const event = decodeFrame(eventName, data.join('\n'));
|
|
672
|
+
if (event !== null) {
|
|
673
|
+
yield event;
|
|
674
|
+
if (event.event === 'done') return;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
eventName = '';
|
|
678
|
+
data = [];
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
if (line.startsWith('event:')) {
|
|
683
|
+
eventName = line.slice('event:'.length).trim();
|
|
684
|
+
} else if (line.startsWith('data:')) {
|
|
685
|
+
data.push(line.slice('data:'.length).replace(/^ /, ''));
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (done) {
|
|
690
|
+
throw new ScrapflyCrawlerError('Prompt stream ended before the done frame', {
|
|
691
|
+
code: 'ERR::CRAWLER::PROMPT_GENERATION_FAILED',
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
} finally {
|
|
696
|
+
// Covers both exhaustion and an early `break` out of the caller's loop.
|
|
697
|
+
await reader.cancel().catch(() => {});
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
193
701
|
/**
|
|
194
702
|
* Single URL entry from `GET /crawl/{uuid}/urls`.
|
|
195
703
|
*
|
|
@@ -358,7 +866,7 @@ export interface CrawlerWebhookCommon {
|
|
|
358
866
|
* Webhook for the four "lifecycle" events that share an identical payload shape:
|
|
359
867
|
* `crawler_started`, `crawler_stopped`, `crawler_cancelled`, `crawler_finished`.
|
|
360
868
|
*
|
|
361
|
-
* Verified against
|
|
869
|
+
* Verified against the Crawler API webhook payload reference.
|
|
362
870
|
*/
|
|
363
871
|
export interface CrawlerLifecycleWebhook {
|
|
364
872
|
event: 'crawler_started' | 'crawler_stopped' | 'crawler_cancelled' | 'crawler_finished';
|
|
@@ -412,6 +920,56 @@ export interface CrawlerUrlFailedWebhook {
|
|
|
412
920
|
};
|
|
413
921
|
}
|
|
414
922
|
|
|
923
|
+
/**
|
|
924
|
+
* Payload for `crawler_search_ready` and `crawler_search_failed`.
|
|
925
|
+
*
|
|
926
|
+
* The index is published after the crawl's own success classification and can
|
|
927
|
+
* fail without the crawl failing, so these are separate from the lifecycle
|
|
928
|
+
* events. They are also the only crawler webhooks emitted without an `action`
|
|
929
|
+
* tag, hence the `Partial` on the common fields.
|
|
930
|
+
*/
|
|
931
|
+
export interface CrawlerSearchWebhook {
|
|
932
|
+
event: 'crawler_search_ready' | 'crawler_search_failed';
|
|
933
|
+
payload: Omit<CrawlerWebhookCommon, 'action'> & {
|
|
934
|
+
action?: string;
|
|
935
|
+
seed_url: string;
|
|
936
|
+
links: { status: string };
|
|
937
|
+
search: CrawlerSearchState;
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Payload for `crawler_updated`, emitted once per auto-refresh run that changed
|
|
943
|
+
* at least one page.
|
|
944
|
+
*
|
|
945
|
+
* A run over a site that stood still, and a run that failed outright, change
|
|
946
|
+
* nothing and are not delivered, so receiving this event is by itself proof of
|
|
947
|
+
* a diff.
|
|
948
|
+
*/
|
|
949
|
+
export interface CrawlerUpdatedWebhook {
|
|
950
|
+
event: 'crawler_updated';
|
|
951
|
+
payload: CrawlerWebhookCommon & {
|
|
952
|
+
seed_url: string;
|
|
953
|
+
links: { status: string };
|
|
954
|
+
/**
|
|
955
|
+
* The run, as the same row the refresh timeline keeps. Its sample lists are
|
|
956
|
+
* absent here: this event carries the URLs in `documents` instead, at a
|
|
957
|
+
* higher cap.
|
|
958
|
+
*/
|
|
959
|
+
refresh: CrawlerRefreshEntry;
|
|
960
|
+
documents: {
|
|
961
|
+
/**
|
|
962
|
+
* Re-indexed URLs, added and changed alike. Which of the two a URL was
|
|
963
|
+
* only survives in the counts on `refresh`.
|
|
964
|
+
*/
|
|
965
|
+
updated: string[];
|
|
966
|
+
removed: string[];
|
|
967
|
+
/** Either list was cut at Scrapfly's 100-URL cap; the counts stay whole. */
|
|
968
|
+
truncated: boolean;
|
|
969
|
+
};
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
|
|
415
973
|
/**
|
|
416
974
|
* Discriminated union of every crawler webhook payload type.
|
|
417
975
|
*
|
|
@@ -422,7 +980,9 @@ export type CrawlerWebhookPayload =
|
|
|
422
980
|
| CrawlerUrlVisitedWebhook
|
|
423
981
|
| CrawlerUrlSkippedWebhook
|
|
424
982
|
| CrawlerUrlDiscoveredWebhook
|
|
425
|
-
| CrawlerUrlFailedWebhook
|
|
983
|
+
| CrawlerUrlFailedWebhook
|
|
984
|
+
| CrawlerSearchWebhook
|
|
985
|
+
| CrawlerUpdatedWebhook;
|
|
426
986
|
|
|
427
987
|
const LIFECYCLE_EVENTS = new Set([
|
|
428
988
|
'crawler_started',
|
|
@@ -467,7 +1027,10 @@ export function parseCrawlerWebhook(body: unknown): CrawlerWebhookPayload {
|
|
|
467
1027
|
event === 'crawler_url_visited' ||
|
|
468
1028
|
event === 'crawler_url_skipped' ||
|
|
469
1029
|
event === 'crawler_url_discovered' ||
|
|
470
|
-
event === 'crawler_url_failed'
|
|
1030
|
+
event === 'crawler_url_failed' ||
|
|
1031
|
+
event === 'crawler_search_ready' ||
|
|
1032
|
+
event === 'crawler_search_failed' ||
|
|
1033
|
+
event === 'crawler_updated'
|
|
471
1034
|
) {
|
|
472
1035
|
// The body has already been validated to have an `event` and `payload`. The
|
|
473
1036
|
// narrower per-event field shapes are runtime-checked by the discriminated union
|
package/src/errors.ts
CHANGED
|
@@ -59,6 +59,18 @@ export class ScrapflyProxyError extends HttpError {}
|
|
|
59
59
|
export class ScrapflyThrottleError extends HttpError {}
|
|
60
60
|
/** Raised when Scrapfly failed to bypass anti-scraping protection on the target. */
|
|
61
61
|
export class ScrapflyAspError extends HttpError {}
|
|
62
|
+
/**
|
|
63
|
+
* Raised when the unblocker (formerly "ASP") could not get through the target's
|
|
64
|
+
* anti-bot protection.
|
|
65
|
+
*
|
|
66
|
+
* This is the SAME class as {@link ScrapflyAspError}, not a subclass and not a
|
|
67
|
+
* second class, so `instanceof ScrapflyUnblockerError` and `instanceof
|
|
68
|
+
* ScrapflyAspError` are interchangeable and customer code written against
|
|
69
|
+
* either name keeps working. The class is still selected by the literal `ASP`
|
|
70
|
+
* segment of the `ERR::ASP::*` codes the API sends.
|
|
71
|
+
*/
|
|
72
|
+
export const ScrapflyUnblockerError: typeof ScrapflyAspError = ScrapflyAspError;
|
|
73
|
+
export type ScrapflyUnblockerError = ScrapflyAspError;
|
|
62
74
|
/** Raised when a scheduled scrape cannot be created or fulfilled. */
|
|
63
75
|
export class ScrapflyScheduleError extends HttpError {}
|
|
64
76
|
/** Raised when a webhook is invalid or cannot be delivered (e.g. full queue). */
|
package/src/main.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* const result = await client.scrape(new ScrapeConfig({
|
|
15
15
|
* url: 'https://web-scraping.dev/products',
|
|
16
16
|
* render_js: true,
|
|
17
|
-
*
|
|
17
|
+
* unblocker: true,
|
|
18
18
|
* }));
|
|
19
19
|
* console.log(result.content);
|
|
20
20
|
* ```
|
|
@@ -55,16 +55,39 @@ export { Crawl } from './crawl.js';
|
|
|
55
55
|
export {
|
|
56
56
|
CrawlerArtifact,
|
|
57
57
|
CrawlerContents,
|
|
58
|
+
CrawlerSearchResponse,
|
|
58
59
|
CrawlerStatus,
|
|
59
60
|
CrawlerUrls,
|
|
61
|
+
isSearchable,
|
|
62
|
+
parseCrawlerPromptStream,
|
|
63
|
+
parseCrawlerRefreshState,
|
|
64
|
+
parseCrawlerSearchState,
|
|
60
65
|
parseCrawlerWebhook,
|
|
66
|
+
refreshChanged,
|
|
61
67
|
} from './crawlerresult.js';
|
|
62
68
|
export type {
|
|
63
69
|
CrawlerArtifactType,
|
|
64
70
|
CrawlerLifecycleWebhook,
|
|
71
|
+
CrawlerPromptDone,
|
|
72
|
+
CrawlerPromptEvent,
|
|
73
|
+
CrawlerPromptSource,
|
|
74
|
+
CrawlerRefreshEntry,
|
|
75
|
+
CrawlerRefreshState,
|
|
76
|
+
CrawlerRefreshStatus,
|
|
77
|
+
CrawlerSearchCrawl,
|
|
78
|
+
CrawlerSearchMode,
|
|
79
|
+
CrawlerSearchResult,
|
|
80
|
+
CrawlerSearchScores,
|
|
81
|
+
CrawlerSearchSkipped,
|
|
82
|
+
CrawlerSearchState,
|
|
83
|
+
CrawlerSearchStats,
|
|
84
|
+
CrawlerSearchStatus,
|
|
85
|
+
CrawlerSearchWebhook,
|
|
86
|
+
CrawlerSkipReason,
|
|
65
87
|
CrawlerState,
|
|
66
88
|
CrawlerStatusValue,
|
|
67
89
|
CrawlerStopReason,
|
|
90
|
+
CrawlerUpdatedWebhook,
|
|
68
91
|
CrawlerUrlDiscoveredWebhook,
|
|
69
92
|
CrawlerUrlEntry,
|
|
70
93
|
CrawlerUrlFailedWebhook,
|
|
@@ -96,4 +119,4 @@ export type {
|
|
|
96
119
|
|
|
97
120
|
export { log } from './logger.js';
|
|
98
121
|
|
|
99
|
-
export { createServer, verifySignature } from './webhookserver.js';
|
|
122
|
+
export { createServer, ResourceType, verifySignature } from './webhookserver.js';
|