@fetchbrain.com/sdk 0.1.4

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.
@@ -0,0 +1,538 @@
1
+ /**
2
+ * FetchBrain SDK Types
3
+ *
4
+ * Type definitions for the FetchBrain AI-powered scraping optimization SDK.
5
+ */
6
+ /** Intelligence level for AI inference accuracy */
7
+ type IntelligenceLevel = 'realtime' | 'high' | 'standard' | 'deep';
8
+ /** AI memory depth levels - deeper memory may have minor hallucinations */
9
+ declare enum AIMemoryDepth {
10
+ REALTIME = 1,
11
+ HIGH = 2,
12
+ STANDARD = 3,
13
+ DEEP = 4
14
+ }
15
+ /** Configuration for FetchBrain SDK */
16
+ interface FetchBrainConfig {
17
+ /** API key for authentication */
18
+ apiKey: string;
19
+ /** Base URL for API (defaults to production) */
20
+ baseUrl?: string;
21
+ /** Intelligence level for AI responses */
22
+ intelligence?: IntelligenceLevel;
23
+ /** Whether AI should learn from new pages */
24
+ learning?: boolean;
25
+ /**
26
+ * Control which handlers run when AI knows the page.
27
+ * - false: Auto-skip all handlers when AI knows (default)
28
+ * - true: Always run all handlers
29
+ * - string[]: Only run handlers with these labels (e.g., ['listing', 'category'])
30
+ * - 'default': Only run the default handler
31
+ *
32
+ * AI data always available via context.ai
33
+ */
34
+ alwaysRun?: boolean | string | string[];
35
+ /** Custom data extractor for learning */
36
+ extractForLearning?: (data: unknown) => Record<string, unknown>;
37
+ /**
38
+ * If true, only return cached data from the same build version.
39
+ * When a scraper updates, it will re-scrape instead of using stale data.
40
+ * Uses APIFY_ACTOR_BUILD_ID environment variable.
41
+ * Default: false
42
+ */
43
+ strictBuildMatch?: boolean;
44
+ /** Request timeout in ms (default: 500ms for fast degradation) */
45
+ timeout?: number;
46
+ /** Enable debug logging */
47
+ debug?: boolean;
48
+ /**
49
+ * Telemetry configuration - opt-in anonymous data sharing
50
+ * Helps improve proxy recommendations, detect blocks, optimize configs
51
+ * Default: disabled
52
+ */
53
+ telemetry?: TelemetryConfig;
54
+ }
55
+ /** Query request to the API */
56
+ interface QueryRequest {
57
+ urls: string[];
58
+ actorId?: string;
59
+ intelligence: IntelligenceLevel;
60
+ /** If specified, only return data from this build version */
61
+ build?: string;
62
+ }
63
+ /** Single query result */
64
+ interface QueryResultItem {
65
+ url: string;
66
+ known: boolean;
67
+ data?: Record<string, unknown>;
68
+ confidence?: number;
69
+ }
70
+ /** Query response from the API */
71
+ interface QueryResponse {
72
+ known: QueryResultItem[];
73
+ unknown: string[];
74
+ }
75
+ /** Learn request to the API */
76
+ interface LearnRequest {
77
+ actorId?: string;
78
+ entries: Array<{
79
+ url: string;
80
+ data: Record<string, unknown>;
81
+ }>;
82
+ }
83
+ /** Learn response from the API */
84
+ interface LearnResponse {
85
+ status: 'accepted' | 'rejected' | 'flagged';
86
+ learned: number;
87
+ verification?: {
88
+ schemaValid: boolean;
89
+ valuesValid: boolean;
90
+ duplicate: boolean;
91
+ warnings: string[];
92
+ };
93
+ }
94
+ /** Stats response from the API */
95
+ interface StatsResponse {
96
+ queries: number;
97
+ recognized: number;
98
+ recognitionRate: number;
99
+ learned: number;
100
+ period: string;
101
+ }
102
+ /** Result from AI knowledge query */
103
+ interface AIResult {
104
+ known: boolean;
105
+ data?: Record<string, unknown>;
106
+ confidence?: number;
107
+ fallback?: boolean;
108
+ }
109
+ /** Circuit breaker states */
110
+ type CircuitState = 'closed' | 'open' | 'half-open';
111
+ /** Circuit breaker configuration */
112
+ interface CircuitBreakerConfig {
113
+ /** Number of failures before opening circuit */
114
+ failureThreshold: number;
115
+ /** Time to wait before trying half-open state (ms) */
116
+ resetTimeout: number;
117
+ /** Number of successful calls to close circuit from half-open */
118
+ successThreshold: number;
119
+ }
120
+ /** Batch configuration */
121
+ interface BatchConfig {
122
+ /** Max items per batch */
123
+ maxSize: number;
124
+ /** Max wait time before flushing (ms) */
125
+ maxWait: number;
126
+ }
127
+ /** Log levels */
128
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
129
+ /** Logger interface */
130
+ interface Logger {
131
+ debug: (message: string, ...args: unknown[]) => void;
132
+ info: (message: string, ...args: unknown[]) => void;
133
+ warn: (message: string, ...args: unknown[]) => void;
134
+ error: (message: string, ...args: unknown[]) => void;
135
+ }
136
+ /**
137
+ * Telemetry configuration - opt-in data sharing for AI improvements
138
+ */
139
+ interface TelemetryConfig {
140
+ /** Enable telemetry collection (default: false) */
141
+ enabled: boolean;
142
+ /** Share performance metrics: response times, retries, status codes */
143
+ sharePerformance?: boolean;
144
+ /** Share proxy info: country, type (never IP addresses) */
145
+ shareProxyInfo?: boolean;
146
+ /** Share site patterns: block rates, rate limits detected */
147
+ shareSitePatterns?: boolean;
148
+ }
149
+ /**
150
+ * Telemetry data collected from Crawlee context
151
+ * All data is sanitized - no PII, no credentials, no raw content
152
+ */
153
+ interface TelemetryData {
154
+ domain: string;
155
+ urlHash: string;
156
+ urlPattern?: string;
157
+ responseTimeMs?: number;
158
+ totalTimeMs?: number;
159
+ statusCode?: number;
160
+ contentSize?: number;
161
+ retryCount?: number;
162
+ proxyCountry?: string;
163
+ proxyType?: string;
164
+ proxySuccess?: boolean;
165
+ sessionAge?: number;
166
+ sessionErrorScore?: number;
167
+ cookieCount?: number;
168
+ blocked?: boolean;
169
+ blockType?: string;
170
+ crawlerType?: string;
171
+ requestLabel?: string;
172
+ timestamp: string;
173
+ }
174
+ /**
175
+ * Telemetry request to the API
176
+ */
177
+ interface TelemetryRequest {
178
+ entries: TelemetryData[];
179
+ }
180
+ /**
181
+ * Telemetry response from the API
182
+ */
183
+ interface TelemetryResponse {
184
+ received: number;
185
+ status: 'success' | 'partial' | 'error';
186
+ }
187
+
188
+ /**
189
+ * FetchBrain API Client
190
+ *
191
+ * Handles all communication with the FetchBrain API including:
192
+ * - Request batching for high concurrency
193
+ * - Circuit breaker for graceful degradation
194
+ * - Automatic retries and timeouts
195
+ */
196
+ declare class FetchBrainClient {
197
+ private config;
198
+ private circuitBreaker;
199
+ private batcher;
200
+ private logger;
201
+ constructor(config: FetchBrainConfig);
202
+ /**
203
+ * Query if FetchBrain "knows" a URL
204
+ */
205
+ query(url: string): Promise<AIResult>;
206
+ /**
207
+ * Query multiple URLs at once (bypass batcher for bulk operations)
208
+ */
209
+ queryBulk(urls: string[]): Promise<Map<string, AIResult>>;
210
+ /**
211
+ * "Teach" FetchBrain new data
212
+ */
213
+ learn(url: string, data: Record<string, unknown>): Promise<LearnResponse>;
214
+ /**
215
+ * Get usage statistics
216
+ */
217
+ stats(): Promise<StatsResponse | null>;
218
+ /**
219
+ * Execute a batch query against the API
220
+ */
221
+ private executeBatchQuery;
222
+ /**
223
+ * Make an HTTP request to the API
224
+ */
225
+ private makeRequest;
226
+ /**
227
+ * Get the current configuration
228
+ */
229
+ getConfig(): FetchBrainConfig;
230
+ /**
231
+ * Get the circuit breaker state
232
+ */
233
+ getCircuitState(): {
234
+ state: CircuitState;
235
+ failures: number;
236
+ successes: number;
237
+ };
238
+ /**
239
+ * Reset the circuit breaker (for testing)
240
+ */
241
+ resetCircuit(): void;
242
+ /**
243
+ * Clear pending batched requests
244
+ */
245
+ clearBatch(): void;
246
+ /**
247
+ * Send telemetry data to the API
248
+ * This is fire-and-forget - failures are silently ignored
249
+ */
250
+ sendTelemetry(entries: TelemetryData[]): Promise<void>;
251
+ /**
252
+ * Check if telemetry is enabled
253
+ */
254
+ isTelemetryEnabled(): boolean;
255
+ /**
256
+ * Get telemetry config
257
+ */
258
+ getTelemetryConfig(): TelemetryConfig;
259
+ }
260
+
261
+ /**
262
+ * Async context for tracking current request
263
+ * This allows Dataset.pushData interception even when called statically
264
+ */
265
+ interface RequestContext {
266
+ url: string;
267
+ client: FetchBrainClient;
268
+ learning: boolean;
269
+ aiKnown: boolean;
270
+ }
271
+ /**
272
+ * Get the current request context (used by pushData wrapper)
273
+ */
274
+ declare function getCurrentContext(): RequestContext | undefined;
275
+ /**
276
+ * AI context available in request handler
277
+ */
278
+ interface FetchBrainContext {
279
+ /** Whether AI knows this URL */
280
+ known: boolean;
281
+ /** AI data if known */
282
+ data?: Record<string, unknown>;
283
+ /** Confidence score (0-1) */
284
+ confidence?: number;
285
+ /** Use AI data and skip scraping (call in handler to early return) */
286
+ useAIData: () => Promise<void>;
287
+ }
288
+ /**
289
+ * FetchBrain main class
290
+ *
291
+ * Provides the static enhance() method to wrap Crawlee crawlers
292
+ * with AI-powered optimization
293
+ */
294
+ declare class FetchBrain {
295
+ private client;
296
+ private logger;
297
+ constructor(config: FetchBrainConfig);
298
+ /**
299
+ * Query if FetchBrain "knows" a URL
300
+ */
301
+ query(options: {
302
+ url: string;
303
+ intelligence?: string;
304
+ }): Promise<{
305
+ known: boolean;
306
+ data: Record<string, unknown> | undefined;
307
+ confidence: number | undefined;
308
+ }>;
309
+ /**
310
+ * "Teach" FetchBrain new data
311
+ */
312
+ learn(options: {
313
+ url: string;
314
+ data: Record<string, unknown>;
315
+ }): Promise<LearnResponse>;
316
+ /**
317
+ * Get usage statistics
318
+ */
319
+ stats(): Promise<StatsResponse | null>;
320
+ /**
321
+ * Enhance a Crawlee crawler with FetchBrain optimization
322
+ *
323
+ * This wraps the crawler's request handler to:
324
+ * 1. Query AI before making requests (AI knows = skip request)
325
+ * 2. Teach AI after successful requests (learning)
326
+ *
327
+ * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
328
+ * @param config - FetchBrain configuration
329
+ * @returns Enhanced crawler with same interface
330
+ */
331
+ static enhance<T>(crawler: T, config: FetchBrainConfig): T & {
332
+ fetchBrain: FetchBrainClient;
333
+ };
334
+ }
335
+ /**
336
+ * Create a standalone FetchBrain client without crawler enhancement
337
+ */
338
+ declare function createFetchBrain(config: FetchBrainConfig): FetchBrain;
339
+ /**
340
+ * Dataset interface for pushData wrapper
341
+ */
342
+ interface DatasetLike {
343
+ pushData: (data: Record<string, unknown> | Record<string, unknown>[]) => Promise<void>;
344
+ open?: (name?: string | null) => Promise<DatasetLike>;
345
+ }
346
+ /**
347
+ * AI-aware pushData wrapper
348
+ *
349
+ * Use this instead of Dataset.pushData() for automatic AI learning.
350
+ * Works with both static Dataset class and dataset instances.
351
+ *
352
+ * @example
353
+ * ```typescript
354
+ * import { Dataset } from 'crawlee';
355
+ * import { pushData } from '@fetchbrain.com/sdk';
356
+ *
357
+ * // Default dataset:
358
+ * await pushData(data, Dataset);
359
+ *
360
+ * // Named dataset (opens automatically):
361
+ * await pushData(data, Dataset, 'products');
362
+ *
363
+ * // Pre-opened dataset instance:
364
+ * const myDataset = await Dataset.open('products');
365
+ * await pushData(data, myDataset);
366
+ * ```
367
+ */
368
+ declare function pushData(data: Record<string, unknown> | Record<string, unknown>[], dataset: DatasetLike, datasetName?: string): Promise<void>;
369
+
370
+ /**
371
+ * Circuit Breaker Pattern Implementation
372
+ *
373
+ * Protects scrapers from API failures:
374
+ * - CLOSED: Normal operation, requests pass through
375
+ * - OPEN: API failing, skip all requests (scraper continues normally)
376
+ * - HALF-OPEN: Testing if API recovered
377
+ */
378
+ declare class CircuitBreaker {
379
+ private state;
380
+ private failures;
381
+ private successes;
382
+ private lastFailureTime;
383
+ private config;
384
+ private logger;
385
+ constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger);
386
+ /**
387
+ * Check if requests should be allowed through
388
+ */
389
+ isOpen(): boolean;
390
+ /**
391
+ * Record a successful API call
392
+ */
393
+ recordSuccess(): void;
394
+ /**
395
+ * Record a failed API call
396
+ */
397
+ recordFailure(): void;
398
+ /**
399
+ * Reset the circuit breaker to closed state
400
+ */
401
+ reset(): void;
402
+ /**
403
+ * Get current circuit state
404
+ */
405
+ getState(): CircuitState;
406
+ /**
407
+ * Get statistics about the circuit breaker
408
+ */
409
+ getStats(): {
410
+ state: CircuitState;
411
+ failures: number;
412
+ successes: number;
413
+ };
414
+ }
415
+
416
+ type BatchExecutor = (urls: string[]) => Promise<Map<string, AIResult>>;
417
+ /**
418
+ * Request Batcher
419
+ *
420
+ * Batches individual URL queries into bulk API calls to reduce connections.
421
+ * Important for high-concurrency scrapers (50-100+ concurrent requests).
422
+ */
423
+ declare class RequestBatcher {
424
+ private queue;
425
+ private flushTimeout;
426
+ private config;
427
+ private executor;
428
+ private logger;
429
+ constructor(executor: BatchExecutor, config: Partial<BatchConfig> | undefined, logger: Logger);
430
+ /**
431
+ * Add a URL to the batch queue
432
+ */
433
+ query(url: string): Promise<AIResult>;
434
+ /**
435
+ * Flush the current batch
436
+ */
437
+ private flush;
438
+ /**
439
+ * Get current queue size
440
+ */
441
+ getQueueSize(): number;
442
+ /**
443
+ * Clear the queue (for cleanup)
444
+ */
445
+ clear(): void;
446
+ }
447
+
448
+ /**
449
+ * Creates a logger with the specified minimum level
450
+ */
451
+ declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
452
+
453
+ /**
454
+ * Telemetry Collection Module
455
+ *
456
+ * Collects anonymized performance and behavior data from Crawlee contexts.
457
+ * All data is sanitized - no PII, credentials, or raw content is ever collected.
458
+ */
459
+
460
+ /**
461
+ * Crawlee-like context interface (subset of what we need)
462
+ * This allows the telemetry to work with any Crawlee crawler type
463
+ */
464
+ interface CrawleeContext {
465
+ request: {
466
+ url: string;
467
+ retryCount?: number;
468
+ label?: string;
469
+ userData?: Record<string, unknown>;
470
+ };
471
+ response?: {
472
+ status?: number;
473
+ statusCode?: number;
474
+ headers?: Record<string, string> | Headers;
475
+ };
476
+ proxyInfo?: {
477
+ url?: string;
478
+ hostname?: string;
479
+ countryCode?: string;
480
+ };
481
+ session?: {
482
+ errorScore?: number;
483
+ usageCount?: number;
484
+ };
485
+ crawler?: {
486
+ constructor?: {
487
+ name?: string;
488
+ };
489
+ };
490
+ }
491
+ /**
492
+ * Additional timing info that can be passed separately
493
+ */
494
+ interface RequestTiming {
495
+ startTime?: number;
496
+ endTime?: number;
497
+ responseTime?: number;
498
+ contentSize?: number;
499
+ }
500
+ /**
501
+ * Collect telemetry from a Crawlee context
502
+ * Returns sanitized data safe for transmission
503
+ */
504
+ declare function collectTelemetry(context: CrawleeContext, timing?: RequestTiming, config?: TelemetryConfig, error?: Error): Promise<TelemetryData | null>;
505
+ /**
506
+ * Telemetry buffer for batching before send
507
+ */
508
+ declare class TelemetryBuffer {
509
+ private buffer;
510
+ private readonly maxSize;
511
+ private readonly flushInterval;
512
+ private flushTimer?;
513
+ private flushCallback?;
514
+ constructor(options?: {
515
+ maxSize?: number;
516
+ flushInterval?: number;
517
+ onFlush?: (entries: TelemetryData[]) => Promise<void>;
518
+ });
519
+ /**
520
+ * Add telemetry entry to buffer
521
+ */
522
+ add(entry: TelemetryData | null): void;
523
+ /**
524
+ * Flush buffer and send telemetry
525
+ */
526
+ flush(): Promise<TelemetryData[]>;
527
+ /**
528
+ * Get current buffer size
529
+ */
530
+ get size(): number;
531
+ private startFlushTimer;
532
+ /**
533
+ * Stop the flush timer and flush remaining entries
534
+ */
535
+ stop(): Promise<void>;
536
+ }
537
+
538
+ export { AIMemoryDepth, type AIResult, type BatchConfig, CircuitBreaker, type CircuitBreakerConfig, type CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, type FetchBrainConfig, type FetchBrainContext, type IntelligenceLevel, type LearnRequest, type LearnResponse, type LogLevel, type Logger, type QueryRequest, type QueryResponse, type QueryResultItem, RequestBatcher, type RequestTiming, type StatsResponse, TelemetryBuffer, type TelemetryConfig, type TelemetryData, type TelemetryRequest, type TelemetryResponse, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };