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.
Files changed (101) hide show
  1. package/README.md +72 -5
  2. package/esm/browserconfig.d.ts +57 -9
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +63 -5
  5. package/esm/browserdownloads.d.ts +70 -0
  6. package/esm/browserdownloads.d.ts.map +1 -0
  7. package/esm/browserdownloads.js +215 -0
  8. package/esm/client.d.ts +224 -8
  9. package/esm/client.d.ts.map +1 -1
  10. package/esm/client.js +646 -62
  11. package/esm/crawl.d.ts +83 -1
  12. package/esm/crawl.d.ts.map +1 -1
  13. package/esm/crawl.js +73 -0
  14. package/esm/crawlerconfig.d.ts +54 -3
  15. package/esm/crawlerconfig.d.ts.map +1 -1
  16. package/esm/crawlerconfig.js +96 -2
  17. package/esm/crawlerresult.d.ts +374 -2
  18. package/esm/crawlerresult.d.ts.map +1 -1
  19. package/esm/crawlerresult.js +367 -1
  20. package/esm/errors.d.ts +12 -0
  21. package/esm/errors.d.ts.map +1 -1
  22. package/esm/errors.js +11 -0
  23. package/esm/main.d.ts +12 -7
  24. package/esm/main.d.ts.map +1 -1
  25. package/esm/main.js +10 -5
  26. package/esm/monitoringconfig.d.ts +2 -2
  27. package/esm/result.d.ts +11 -1
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/result.js +14 -5
  30. package/esm/scrapeconfig.d.ts +65 -1
  31. package/esm/scrapeconfig.d.ts.map +1 -1
  32. package/esm/scrapeconfig.js +88 -4
  33. package/esm/screenshotconfig.d.ts +9 -1
  34. package/esm/screenshotconfig.d.ts.map +1 -1
  35. package/esm/screenshotconfig.js +12 -1
  36. package/esm/types.d.ts +128 -0
  37. package/esm/types.d.ts.map +1 -1
  38. package/esm/types.js +22 -1
  39. package/esm/utils.d.ts.map +1 -1
  40. package/esm/utils.js +16 -2
  41. package/esm/webhookserver.d.ts +33 -15
  42. package/esm/webhookserver.d.ts.map +1 -1
  43. package/esm/webhookserver.js +197 -38
  44. package/package.json +1 -1
  45. package/script/browserconfig.d.ts +57 -9
  46. package/script/browserconfig.d.ts.map +1 -1
  47. package/script/browserconfig.js +63 -5
  48. package/script/browserdownloads.d.ts +70 -0
  49. package/script/browserdownloads.d.ts.map +1 -0
  50. package/script/browserdownloads.js +221 -0
  51. package/script/client.d.ts +224 -8
  52. package/script/client.d.ts.map +1 -1
  53. package/script/client.js +645 -61
  54. package/script/crawl.d.ts +83 -1
  55. package/script/crawl.d.ts.map +1 -1
  56. package/script/crawl.js +73 -0
  57. package/script/crawlerconfig.d.ts +54 -3
  58. package/script/crawlerconfig.d.ts.map +1 -1
  59. package/script/crawlerconfig.js +97 -3
  60. package/script/crawlerresult.d.ts +374 -2
  61. package/script/crawlerresult.d.ts.map +1 -1
  62. package/script/crawlerresult.js +374 -2
  63. package/script/errors.d.ts +12 -0
  64. package/script/errors.d.ts.map +1 -1
  65. package/script/errors.js +12 -1
  66. package/script/main.d.ts +12 -7
  67. package/script/main.d.ts.map +1 -1
  68. package/script/main.js +20 -4
  69. package/script/monitoringconfig.d.ts +2 -2
  70. package/script/result.d.ts +11 -1
  71. package/script/result.d.ts.map +1 -1
  72. package/script/result.js +14 -5
  73. package/script/scrapeconfig.d.ts +65 -1
  74. package/script/scrapeconfig.d.ts.map +1 -1
  75. package/script/scrapeconfig.js +88 -4
  76. package/script/screenshotconfig.d.ts +9 -1
  77. package/script/screenshotconfig.d.ts.map +1 -1
  78. package/script/screenshotconfig.js +12 -1
  79. package/script/types.d.ts +128 -0
  80. package/script/types.d.ts.map +1 -1
  81. package/script/types.js +23 -0
  82. package/script/utils.d.ts.map +1 -1
  83. package/script/utils.js +16 -2
  84. package/script/webhookserver.d.ts +33 -15
  85. package/script/webhookserver.d.ts.map +1 -1
  86. package/script/webhookserver.js +197 -38
  87. package/src/browserconfig.ts +74 -8
  88. package/src/browserdownloads.ts +266 -0
  89. package/src/client.ts +796 -65
  90. package/src/crawl.ts +106 -0
  91. package/src/crawlerconfig.ts +128 -5
  92. package/src/crawlerresult.ts +607 -3
  93. package/src/errors.ts +12 -0
  94. package/src/main.ts +55 -5
  95. package/src/monitoringconfig.ts +2 -2
  96. package/src/result.ts +17 -5
  97. package/src/scrapeconfig.ts +92 -3
  98. package/src/screenshotconfig.ts +14 -1
  99. package/src/types.ts +159 -1
  100. package/src/utils.ts +16 -2
  101. package/src/webhookserver.ts +235 -39
@@ -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,537 @@ 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
+ /** How much of the corpus a prompt answer or an extraction covers. */
557
+ export interface CrawlerPromptSearch {
558
+ completeness: 'exact' | 'partial';
559
+ crawls_requested?: number;
560
+ crawls_searched?: number;
561
+ crawls_pruned_exact?: number;
562
+ /** Requested crawls that contributed nothing, with a reason. Never fatal. */
563
+ skipped: CrawlerSearchSkipped[];
564
+ }
565
+
566
+ /** The answer of `POST /crawl/prompt` with `generation.stream: false`: the facts of the stream, in one object. */
567
+ export interface CrawlerPromptAnswer {
568
+ prompt: string;
569
+ answer: string;
570
+ sources: CrawlerPromptSource[];
571
+ sources_used: number[];
572
+ /** Retrieved chunks that did not fit the context and never reached the model. */
573
+ sources_dropped: number;
574
+ /** True when the model hit its output cap. The answer is still delivered. */
575
+ truncated: boolean;
576
+ search: CrawlerPromptSearch;
577
+ /** Actual charge, including zero. Undefined when the server does not report it. */
578
+ api_credit?: number;
579
+ }
580
+
581
+ /**
582
+ * The response of `POST /crawl/extract`. `data` is shaped by the request's JSON
583
+ * Schema, which constrains the model as it generates; it is not validated again
584
+ * afterwards, so validate on your side anything you act on.
585
+ */
586
+ export interface CrawlerExtractResponse<T = any> {
587
+ prompt: string;
588
+ data: T;
589
+ /** The retrieved chunks `data` was built from. */
590
+ sources: CrawlerPromptSource[];
591
+ /** Retrieved chunks that did not fit the context and never reached the model. */
592
+ sources_dropped: number;
593
+ /** True when the model hit its output cap. */
594
+ truncated: boolean;
595
+ search: CrawlerPromptSearch;
596
+ }
597
+
598
+ /** Payload of the terminal `done` frame. */
599
+ export interface CrawlerPromptDone {
600
+ sources_used?: number[];
601
+ /** Retrieved chunks that did not fit the context and never reached the model. */
602
+ sources_dropped?: number;
603
+ /**
604
+ * True when the model hit its output cap. The answer is still delivered;
605
+ * whether to use it is the caller's call.
606
+ */
607
+ truncated?: boolean;
608
+ /** Actual charge, including zero. Undefined when the server does not report it. */
609
+ api_credit?: number;
610
+ }
611
+
612
+ /**
613
+ * One decoded frame of the `POST /crawl/prompt` stream.
614
+ *
615
+ * Frames arrive as `source`*, then `token`*, then one `done`, or one `error`
616
+ * which is thrown rather than yielded because generation can fail after
617
+ * tokens have already been delivered.
618
+ */
619
+ export type CrawlerPromptEvent =
620
+ | { event: 'source'; data: CrawlerPromptSource }
621
+ | { event: 'token'; data: string }
622
+ | { event: 'done'; data: CrawlerPromptDone };
623
+
624
+ /**
625
+ * Decode the `POST /crawl/prompt` SSE body into typed frames.
626
+ *
627
+ * Only `event:` and `data:` lines matter; `:keepalive` comment frames exist
628
+ * to keep intermediaries from closing an idle connection and carry nothing.
629
+ * Token payloads are JSON strings; every other frame is a JSON object.
630
+ *
631
+ * An `event: error` frame throws rather than yields: the caller is already
632
+ * inside a `for await` and a yielded error object is too easy to ignore after
633
+ * tokens have started arriving.
634
+ *
635
+ * Decoding is explicitly UTF-8 with `stream: true`, because a multi-byte
636
+ * character can straddle two chunks of the body.
637
+ * EOF before a complete `done` frame throws, even after tokens were delivered.
638
+ */
639
+ export async function* parseCrawlerPromptStream(
640
+ body: ReadableStream<Uint8Array>,
641
+ ): AsyncGenerator<CrawlerPromptEvent, void, undefined> {
642
+ const reader = body.getReader();
643
+ const decoder = new TextDecoder('utf-8');
644
+ let buffer = '';
645
+ let eventName = '';
646
+ let data: string[] = [];
647
+
648
+ const decodeFrame = (name: string, raw: string): CrawlerPromptEvent | null => {
649
+ if (name === 'token') {
650
+ let token: string;
651
+ try {
652
+ token = JSON.parse(raw) as string;
653
+ } catch {
654
+ // A server sending bare text instead of a JSON string is still
655
+ // sending a token; do not drop the answer over the quoting.
656
+ token = raw;
657
+ }
658
+ return { event: 'token', data: token };
659
+ }
660
+ if (name === 'source') {
661
+ return { event: 'source', data: JSON.parse(raw) as CrawlerPromptSource };
662
+ }
663
+ if (name === 'done') {
664
+ const payload = JSON.parse(raw) as Rec<any>;
665
+ // Build the public result explicitly: a TypeScript cast does not remove
666
+ // legacy model, token or provider-cost fields from the runtime object.
667
+ return {
668
+ event: 'done',
669
+ data: {
670
+ sources_used: optionalField<number[]>(payload, 'sources_used', 'array', 'CrawlerPromptDone') ?? undefined,
671
+ sources_dropped: optionalField<number>(payload, 'sources_dropped', 'number', 'CrawlerPromptDone') ?? undefined,
672
+ truncated: optionalField<boolean>(payload, 'truncated', 'boolean', 'CrawlerPromptDone') ?? undefined,
673
+ api_credit: optionalField<number>(payload, 'api_credit', 'number', 'CrawlerPromptDone') ?? undefined,
674
+ },
675
+ };
676
+ }
677
+ if (name === 'error') {
678
+ let payload: Rec<any> = {};
679
+ try {
680
+ payload = JSON.parse(raw) as Rec<any>;
681
+ } catch {
682
+ payload = { message: raw };
683
+ }
684
+ throw new ScrapflyCrawlerError(payload.message ?? raw, {
685
+ code: (payload.code ?? 'ERR::CRAWLER::UNKNOWN') as string,
686
+ });
687
+ }
688
+ return null;
689
+ };
690
+
691
+ try {
692
+ for (;;) {
693
+ const { done, value } = await reader.read();
694
+ if (value !== undefined) {
695
+ buffer += decoder.decode(value, { stream: true });
696
+ }
697
+ if (done) {
698
+ buffer += decoder.decode();
699
+ }
700
+
701
+ let newline = buffer.indexOf('\n');
702
+ while (newline !== -1) {
703
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
704
+ buffer = buffer.slice(newline + 1);
705
+ newline = buffer.indexOf('\n');
706
+
707
+ if (line.startsWith(':')) continue;
708
+
709
+ // A blank line terminates a frame.
710
+ if (line === '') {
711
+ if (eventName !== '' && data.length > 0) {
712
+ const event = decodeFrame(eventName, data.join('\n'));
713
+ if (event !== null) {
714
+ yield event;
715
+ if (event.event === 'done') return;
716
+ }
717
+ }
718
+ eventName = '';
719
+ data = [];
720
+ continue;
721
+ }
722
+
723
+ if (line.startsWith('event:')) {
724
+ eventName = line.slice('event:'.length).trim();
725
+ } else if (line.startsWith('data:')) {
726
+ data.push(line.slice('data:'.length).replace(/^ /, ''));
727
+ }
728
+ }
729
+
730
+ if (done) {
731
+ throw new ScrapflyCrawlerError('Prompt stream ended before the done frame', {
732
+ code: 'ERR::CRAWLER::PROMPT_GENERATION_FAILED',
733
+ });
734
+ }
735
+ }
736
+ } finally {
737
+ // Covers both exhaustion and an early `break` out of the caller's loop.
738
+ await reader.cancel().catch(() => {});
739
+ }
740
+ }
741
+
193
742
  /**
194
743
  * Single URL entry from `GET /crawl/{uuid}/urls`.
195
744
  *
@@ -358,7 +907,7 @@ export interface CrawlerWebhookCommon {
358
907
  * Webhook for the four "lifecycle" events that share an identical payload shape:
359
908
  * `crawler_started`, `crawler_stopped`, `crawler_cancelled`, `crawler_finished`.
360
909
  *
361
- * Verified against `apps/scrapfly/web-app/src/Template/Docs/crawler-api/webhooks_example/`.
910
+ * Verified against the Crawler API webhook payload reference.
362
911
  */
363
912
  export interface CrawlerLifecycleWebhook {
364
913
  event: 'crawler_started' | 'crawler_stopped' | 'crawler_cancelled' | 'crawler_finished';
@@ -412,6 +961,56 @@ export interface CrawlerUrlFailedWebhook {
412
961
  };
413
962
  }
414
963
 
964
+ /**
965
+ * Payload for `crawler_search_ready` and `crawler_search_failed`.
966
+ *
967
+ * The index is published after the crawl's own success classification and can
968
+ * fail without the crawl failing, so these are separate from the lifecycle
969
+ * events. They are also the only crawler webhooks emitted without an `action`
970
+ * tag, hence the `Partial` on the common fields.
971
+ */
972
+ export interface CrawlerSearchWebhook {
973
+ event: 'crawler_search_ready' | 'crawler_search_failed';
974
+ payload: Omit<CrawlerWebhookCommon, 'action'> & {
975
+ action?: string;
976
+ seed_url: string;
977
+ links: { status: string };
978
+ search: CrawlerSearchState;
979
+ };
980
+ }
981
+
982
+ /**
983
+ * Payload for `crawler_updated`, emitted once per auto-refresh run that changed
984
+ * at least one page.
985
+ *
986
+ * A run over a site that stood still, and a run that failed outright, change
987
+ * nothing and are not delivered, so receiving this event is by itself proof of
988
+ * a diff.
989
+ */
990
+ export interface CrawlerUpdatedWebhook {
991
+ event: 'crawler_updated';
992
+ payload: CrawlerWebhookCommon & {
993
+ seed_url: string;
994
+ links: { status: string };
995
+ /**
996
+ * The run, as the same row the refresh timeline keeps. Its sample lists are
997
+ * absent here: this event carries the URLs in `documents` instead, at a
998
+ * higher cap.
999
+ */
1000
+ refresh: CrawlerRefreshEntry;
1001
+ documents: {
1002
+ /**
1003
+ * Re-indexed URLs, added and changed alike. Which of the two a URL was
1004
+ * only survives in the counts on `refresh`.
1005
+ */
1006
+ updated: string[];
1007
+ removed: string[];
1008
+ /** Either list was cut at Scrapfly's 100-URL cap; the counts stay whole. */
1009
+ truncated: boolean;
1010
+ };
1011
+ };
1012
+ }
1013
+
415
1014
  /**
416
1015
  * Discriminated union of every crawler webhook payload type.
417
1016
  *
@@ -422,7 +1021,9 @@ export type CrawlerWebhookPayload =
422
1021
  | CrawlerUrlVisitedWebhook
423
1022
  | CrawlerUrlSkippedWebhook
424
1023
  | CrawlerUrlDiscoveredWebhook
425
- | CrawlerUrlFailedWebhook;
1024
+ | CrawlerUrlFailedWebhook
1025
+ | CrawlerSearchWebhook
1026
+ | CrawlerUpdatedWebhook;
426
1027
 
427
1028
  const LIFECYCLE_EVENTS = new Set([
428
1029
  'crawler_started',
@@ -467,7 +1068,10 @@ export function parseCrawlerWebhook(body: unknown): CrawlerWebhookPayload {
467
1068
  event === 'crawler_url_visited' ||
468
1069
  event === 'crawler_url_skipped' ||
469
1070
  event === 'crawler_url_discovered' ||
470
- event === 'crawler_url_failed'
1071
+ event === 'crawler_url_failed' ||
1072
+ event === 'crawler_search_ready' ||
1073
+ event === 'crawler_search_failed' ||
1074
+ event === 'crawler_updated'
471
1075
  ) {
472
1076
  // The body has already been validated to have an `event` and `payload`. The
473
1077
  // 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). */