@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.
package/dist/index.js ADDED
@@ -0,0 +1,903 @@
1
+ 'use strict';
2
+
3
+ var async_hooks = require('async_hooks');
4
+
5
+ // src/enhance.ts
6
+
7
+ // src/circuit-breaker.ts
8
+ var DEFAULT_CONFIG = {
9
+ failureThreshold: 3,
10
+ resetTimeout: 3e4,
11
+ // 30 seconds
12
+ successThreshold: 1
13
+ };
14
+ var CircuitBreaker = class {
15
+ constructor(config = {}, logger) {
16
+ this.state = "closed";
17
+ this.failures = 0;
18
+ this.successes = 0;
19
+ this.lastFailureTime = 0;
20
+ this.config = { ...DEFAULT_CONFIG, ...config };
21
+ this.logger = logger;
22
+ }
23
+ /**
24
+ * Check if requests should be allowed through
25
+ */
26
+ isOpen() {
27
+ if (this.state === "closed") {
28
+ return false;
29
+ }
30
+ if (this.state === "open") {
31
+ const now = Date.now();
32
+ if (now - this.lastFailureTime >= this.config.resetTimeout) {
33
+ this.logger.info("Circuit transitioning to half-open, testing API...");
34
+ this.state = "half-open";
35
+ this.successes = 0;
36
+ return false;
37
+ }
38
+ return true;
39
+ }
40
+ return false;
41
+ }
42
+ /**
43
+ * Record a successful API call
44
+ */
45
+ recordSuccess() {
46
+ if (this.state === "half-open") {
47
+ this.successes++;
48
+ if (this.successes >= this.config.successThreshold) {
49
+ this.logger.info("API recovered, circuit closed");
50
+ this.reset();
51
+ }
52
+ } else if (this.state === "closed") {
53
+ this.failures = 0;
54
+ }
55
+ }
56
+ /**
57
+ * Record a failed API call
58
+ */
59
+ recordFailure() {
60
+ this.failures++;
61
+ this.lastFailureTime = Date.now();
62
+ if (this.state === "half-open") {
63
+ this.logger.warn("API still failing, circuit reopened");
64
+ this.state = "open";
65
+ return;
66
+ }
67
+ if (this.failures >= this.config.failureThreshold) {
68
+ this.logger.warn(
69
+ `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
70
+ );
71
+ this.state = "open";
72
+ }
73
+ }
74
+ /**
75
+ * Reset the circuit breaker to closed state
76
+ */
77
+ reset() {
78
+ this.state = "closed";
79
+ this.failures = 0;
80
+ this.successes = 0;
81
+ this.lastFailureTime = 0;
82
+ }
83
+ /**
84
+ * Get current circuit state
85
+ */
86
+ getState() {
87
+ return this.state;
88
+ }
89
+ /**
90
+ * Get statistics about the circuit breaker
91
+ */
92
+ getStats() {
93
+ return {
94
+ state: this.state,
95
+ failures: this.failures,
96
+ successes: this.successes
97
+ };
98
+ }
99
+ };
100
+
101
+ // src/batch.ts
102
+ var DEFAULT_CONFIG2 = {
103
+ maxSize: 50,
104
+ maxWait: 50
105
+ // 50ms
106
+ };
107
+ var RequestBatcher = class {
108
+ constructor(executor, config = {}, logger) {
109
+ this.queue = [];
110
+ this.flushTimeout = null;
111
+ this.executor = executor;
112
+ this.config = { ...DEFAULT_CONFIG2, ...config };
113
+ this.logger = logger;
114
+ }
115
+ /**
116
+ * Add a URL to the batch queue
117
+ */
118
+ async query(url) {
119
+ return new Promise((resolve, reject) => {
120
+ this.queue.push({ url, resolve, reject });
121
+ if (this.queue.length >= this.config.maxSize) {
122
+ this.flush();
123
+ return;
124
+ }
125
+ if (!this.flushTimeout) {
126
+ this.flushTimeout = setTimeout(() => {
127
+ this.flush();
128
+ }, this.config.maxWait);
129
+ }
130
+ });
131
+ }
132
+ /**
133
+ * Flush the current batch
134
+ */
135
+ async flush() {
136
+ if (this.flushTimeout) {
137
+ clearTimeout(this.flushTimeout);
138
+ this.flushTimeout = null;
139
+ }
140
+ if (this.queue.length === 0) {
141
+ return;
142
+ }
143
+ const batch = this.queue.splice(0, this.config.maxSize);
144
+ const urls = batch.map((r) => r.url);
145
+ this.logger.debug(`Flushing batch of ${urls.length} URLs`);
146
+ try {
147
+ const results = await this.executor(urls);
148
+ for (const request of batch) {
149
+ const result = results.get(request.url);
150
+ if (result) {
151
+ request.resolve(result);
152
+ } else {
153
+ request.resolve({ known: false });
154
+ }
155
+ }
156
+ } catch (error) {
157
+ for (const request of batch) {
158
+ request.reject(error);
159
+ }
160
+ }
161
+ if (this.queue.length > 0) {
162
+ this.flushTimeout = setTimeout(() => {
163
+ this.flush();
164
+ }, this.config.maxWait);
165
+ }
166
+ }
167
+ /**
168
+ * Get current queue size
169
+ */
170
+ getQueueSize() {
171
+ return this.queue.length;
172
+ }
173
+ /**
174
+ * Clear the queue (for cleanup)
175
+ */
176
+ clear() {
177
+ if (this.flushTimeout) {
178
+ clearTimeout(this.flushTimeout);
179
+ this.flushTimeout = null;
180
+ }
181
+ for (const request of this.queue) {
182
+ request.resolve({ known: false, fallback: true });
183
+ }
184
+ this.queue = [];
185
+ }
186
+ };
187
+
188
+ // src/logger.ts
189
+ var LOG_PREFIX = "[FetchBrain]";
190
+ var LOG_LEVELS = {
191
+ debug: 0,
192
+ info: 1,
193
+ warn: 2,
194
+ error: 3
195
+ };
196
+ function createLogger(minLevel = "info", enabled = true) {
197
+ const shouldLog = (level) => {
198
+ if (!enabled) return false;
199
+ return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
200
+ };
201
+ return {
202
+ debug: (message, ...args) => {
203
+ if (shouldLog("debug")) {
204
+ console.debug(`${LOG_PREFIX} ${message}`, ...args);
205
+ }
206
+ },
207
+ info: (message, ...args) => {
208
+ if (shouldLog("info")) {
209
+ console.info(`${LOG_PREFIX} ${message}`, ...args);
210
+ }
211
+ },
212
+ warn: (message, ...args) => {
213
+ if (shouldLog("warn")) {
214
+ console.warn(`${LOG_PREFIX} ${message}`, ...args);
215
+ }
216
+ },
217
+ error: (message, ...args) => {
218
+ if (shouldLog("error")) {
219
+ console.error(`${LOG_PREFIX} ${message}`, ...args);
220
+ }
221
+ }
222
+ };
223
+ }
224
+
225
+ // src/client.ts
226
+ var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
227
+ var DEFAULT_TIMEOUT = 500;
228
+ var currentContext = {};
229
+ function setScrapeContext(ctx) {
230
+ currentContext = ctx;
231
+ }
232
+ function clearScrapeContext() {
233
+ currentContext = {};
234
+ }
235
+ var FetchBrainClient = class {
236
+ constructor(config) {
237
+ this.config = {
238
+ apiKey: config.apiKey,
239
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL,
240
+ intelligence: config.intelligence || "high",
241
+ learning: config.learning ?? true,
242
+ alwaysRun: config.alwaysRun ?? false,
243
+ strictBuildMatch: config.strictBuildMatch ?? false,
244
+ timeout: config.timeout || DEFAULT_TIMEOUT,
245
+ debug: config.debug || false,
246
+ extractForLearning: config.extractForLearning,
247
+ telemetry: config.telemetry ?? { enabled: true }
248
+ };
249
+ this.logger = createLogger(this.config.debug ? "debug" : "info", true);
250
+ this.circuitBreaker = new CircuitBreaker({}, this.logger);
251
+ this.batcher = new RequestBatcher(
252
+ (urls) => this.executeBatchQuery(urls),
253
+ {},
254
+ this.logger
255
+ );
256
+ }
257
+ /**
258
+ * Query if FetchBrain "knows" a URL
259
+ */
260
+ async query(url) {
261
+ if (this.circuitBreaker.isOpen()) {
262
+ this.logger.debug(`Circuit open, skipping query for: ${url}`);
263
+ return { known: false, fallback: true };
264
+ }
265
+ try {
266
+ return await this.batcher.query(url);
267
+ } catch (error) {
268
+ this.logger.debug(`Query failed for ${url}:`, error);
269
+ return { known: false, fallback: true };
270
+ }
271
+ }
272
+ /**
273
+ * Query multiple URLs at once (bypass batcher for bulk operations)
274
+ */
275
+ async queryBulk(urls) {
276
+ if (this.circuitBreaker.isOpen()) {
277
+ this.logger.debug(`Circuit open, skipping bulk query`);
278
+ return new Map(
279
+ urls.map((url) => [url, { known: false, fallback: true }])
280
+ );
281
+ }
282
+ try {
283
+ return await this.executeBatchQuery(urls);
284
+ } catch (error) {
285
+ this.logger.debug(`Bulk query failed:`, error);
286
+ return new Map(
287
+ urls.map((url) => [url, { known: false, fallback: true }])
288
+ );
289
+ }
290
+ }
291
+ /**
292
+ * "Teach" FetchBrain new data
293
+ */
294
+ async learn(url, data) {
295
+ if (!this.config.learning) {
296
+ return { status: "rejected", learned: 0 };
297
+ }
298
+ if (this.circuitBreaker.isOpen()) {
299
+ this.logger.debug(`Circuit open, skipping learn for: ${url}`);
300
+ return { status: "rejected", learned: 0 };
301
+ }
302
+ try {
303
+ const extractedData = this.config.extractForLearning ? this.config.extractForLearning(data) : data;
304
+ const response = await this.makeRequest("/v1/learn", {
305
+ method: "POST",
306
+ body: JSON.stringify({
307
+ entries: [{ url, data: extractedData }]
308
+ })
309
+ });
310
+ this.circuitBreaker.recordSuccess();
311
+ this.logger.debug(`Learned data for: ${url}`);
312
+ return response;
313
+ } catch (error) {
314
+ this.circuitBreaker.recordFailure();
315
+ this.logger.warn(`Learn failed for ${url}:`, error);
316
+ return { status: "rejected", learned: 0 };
317
+ }
318
+ }
319
+ /**
320
+ * Get usage statistics
321
+ */
322
+ async stats() {
323
+ if (this.circuitBreaker.isOpen()) {
324
+ return null;
325
+ }
326
+ try {
327
+ const response = await this.makeRequest("/v1/stats", {
328
+ method: "GET"
329
+ });
330
+ this.circuitBreaker.recordSuccess();
331
+ return response;
332
+ } catch (error) {
333
+ this.circuitBreaker.recordFailure();
334
+ this.logger.warn("Stats request failed:", error);
335
+ return null;
336
+ }
337
+ }
338
+ /**
339
+ * Execute a batch query against the API
340
+ */
341
+ async executeBatchQuery(urls) {
342
+ const results = /* @__PURE__ */ new Map();
343
+ const request = {
344
+ urls,
345
+ intelligence: this.config.intelligence
346
+ };
347
+ if (this.config.strictBuildMatch && process.env.APIFY_ACTOR_BUILD_ID) {
348
+ request.build = process.env.APIFY_ACTOR_BUILD_ID;
349
+ }
350
+ try {
351
+ const response = await this.makeRequest("/v1/query", {
352
+ method: "POST",
353
+ body: JSON.stringify(request)
354
+ });
355
+ this.circuitBreaker.recordSuccess();
356
+ for (const item of response.known) {
357
+ results.set(item.url, {
358
+ known: true,
359
+ data: item.data,
360
+ confidence: item.confidence
361
+ });
362
+ }
363
+ for (const url of response.unknown) {
364
+ results.set(url, { known: false });
365
+ }
366
+ return results;
367
+ } catch (error) {
368
+ this.circuitBreaker.recordFailure();
369
+ throw error;
370
+ }
371
+ }
372
+ /**
373
+ * Make an HTTP request to the API
374
+ */
375
+ async makeRequest(path, options) {
376
+ const url = `${this.config.baseUrl}${path}`;
377
+ const controller = new AbortController();
378
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
379
+ const contextHeaders = {
380
+ "X-FB-SDK": "js",
381
+ "X-FB-Node": process.version || "unknown",
382
+ "X-FB-Platform": process.platform || "unknown"
383
+ };
384
+ if (process.env.NODE_ENV) {
385
+ contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
386
+ }
387
+ if (process.env.APIFY_ACTOR_ID) {
388
+ contextHeaders["X-FB-Apify"] = process.env.APIFY_ACTOR_ID;
389
+ }
390
+ if (process.env.APIFY_ACTOR_BUILD_ID) {
391
+ contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
392
+ }
393
+ if (process.env.APIFY_ACTOR_RUN_ID) {
394
+ contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
395
+ }
396
+ if (currentContext.crawler) {
397
+ contextHeaders["X-FB-Crawler"] = currentContext.crawler;
398
+ }
399
+ if (currentContext.label) {
400
+ contextHeaders["X-FB-Label"] = currentContext.label;
401
+ }
402
+ try {
403
+ const response = await fetch(url, {
404
+ ...options,
405
+ headers: {
406
+ Authorization: `Bearer ${this.config.apiKey}`,
407
+ "Content-Type": "application/json",
408
+ ...contextHeaders,
409
+ ...options.headers
410
+ },
411
+ signal: controller.signal
412
+ });
413
+ if (!response.ok) {
414
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
415
+ }
416
+ return await response.json();
417
+ } finally {
418
+ clearTimeout(timeoutId);
419
+ }
420
+ }
421
+ /**
422
+ * Get the current configuration
423
+ */
424
+ getConfig() {
425
+ return { ...this.config };
426
+ }
427
+ /**
428
+ * Get the circuit breaker state
429
+ */
430
+ getCircuitState() {
431
+ return this.circuitBreaker.getStats();
432
+ }
433
+ /**
434
+ * Reset the circuit breaker (for testing)
435
+ */
436
+ resetCircuit() {
437
+ this.circuitBreaker.reset();
438
+ }
439
+ /**
440
+ * Clear pending batched requests
441
+ */
442
+ clearBatch() {
443
+ this.batcher.clear();
444
+ }
445
+ /**
446
+ * Send telemetry data to the API
447
+ * This is fire-and-forget - failures are silently ignored
448
+ */
449
+ async sendTelemetry(entries) {
450
+ if (!this.config.telemetry?.enabled || entries.length === 0) {
451
+ return;
452
+ }
453
+ try {
454
+ await this.makeRequest("/v1/telemetry", {
455
+ method: "POST",
456
+ body: JSON.stringify({ entries })
457
+ });
458
+ } catch {
459
+ }
460
+ }
461
+ /**
462
+ * Check if telemetry is enabled
463
+ */
464
+ isTelemetryEnabled() {
465
+ return this.config.telemetry?.enabled ?? false;
466
+ }
467
+ /**
468
+ * Get telemetry config
469
+ */
470
+ getTelemetryConfig() {
471
+ return this.config.telemetry;
472
+ }
473
+ };
474
+
475
+ // src/telemetry.ts
476
+ async function hashString(str) {
477
+ const encoder = new TextEncoder();
478
+ const data = encoder.encode(str);
479
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
480
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
481
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
482
+ }
483
+ function extractDomain(url) {
484
+ try {
485
+ return new URL(url).hostname;
486
+ } catch {
487
+ return "unknown";
488
+ }
489
+ }
490
+ function generalizeUrlPath(url) {
491
+ try {
492
+ const parsed = new URL(url);
493
+ const path = parsed.pathname;
494
+ return path.replace(/\/\d+/g, "/*").replace(/\/[a-f0-9-]{36}/gi, "/*").replace(/\/[a-zA-Z0-9]{20,}/g, "/*").replace(/\?.*$/, "");
495
+ } catch {
496
+ return "/*";
497
+ }
498
+ }
499
+ function detectBlockType(statusCode, errorMessage) {
500
+ if (!statusCode && !errorMessage) return void 0;
501
+ if (statusCode === 403) return "403";
502
+ if (statusCode === 429) return "429";
503
+ if (statusCode === 503) return "503";
504
+ if (statusCode && statusCode >= 400) return `${statusCode}`;
505
+ const msg = errorMessage?.toLowerCase() || "";
506
+ if (msg.includes("captcha")) return "captcha";
507
+ if (msg.includes("timeout")) return "timeout";
508
+ if (msg.includes("blocked")) return "blocked";
509
+ if (msg.includes("rate limit")) return "429";
510
+ return void 0;
511
+ }
512
+ function extractProxyType(proxyUrl) {
513
+ if (!proxyUrl) return void 0;
514
+ const url = proxyUrl.toLowerCase();
515
+ if (url.includes("residential")) return "residential";
516
+ if (url.includes("mobile")) return "mobile";
517
+ if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
518
+ if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
519
+ return "residential";
520
+ }
521
+ return "datacenter";
522
+ }
523
+ async function collectTelemetry(context, timing, config, error) {
524
+ if (!config?.enabled) {
525
+ return null;
526
+ }
527
+ const url = context.request.url;
528
+ const statusCode = context.response?.status || context.response?.statusCode;
529
+ const telemetry = {
530
+ domain: extractDomain(url),
531
+ urlHash: await hashString(url),
532
+ urlPattern: generalizeUrlPath(url),
533
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
534
+ };
535
+ if (config.sharePerformance !== false) {
536
+ telemetry.statusCode = statusCode;
537
+ telemetry.retryCount = context.request.retryCount;
538
+ if (timing) {
539
+ telemetry.responseTimeMs = timing.responseTime;
540
+ telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
541
+ telemetry.contentSize = timing.contentSize;
542
+ }
543
+ }
544
+ if (config.shareProxyInfo !== false && context.proxyInfo) {
545
+ telemetry.proxyCountry = context.proxyInfo.countryCode;
546
+ telemetry.proxyType = extractProxyType(context.proxyInfo.url);
547
+ telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
548
+ }
549
+ if (config.shareSitePatterns !== false) {
550
+ const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
551
+ telemetry.blocked = isBlocked || !!error;
552
+ telemetry.blockType = detectBlockType(statusCode, error?.message);
553
+ }
554
+ if (context.session) {
555
+ telemetry.sessionAge = context.session.usageCount;
556
+ telemetry.sessionErrorScore = context.session.errorScore;
557
+ }
558
+ telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
559
+ telemetry.requestLabel = context.request.label;
560
+ return telemetry;
561
+ }
562
+ var TelemetryBuffer = class {
563
+ constructor(options = {}) {
564
+ this.buffer = [];
565
+ this.maxSize = options.maxSize ?? 50;
566
+ this.flushInterval = options.flushInterval ?? 3e4;
567
+ this.flushCallback = options.onFlush;
568
+ this.startFlushTimer();
569
+ }
570
+ /**
571
+ * Add telemetry entry to buffer
572
+ */
573
+ add(entry) {
574
+ if (!entry) return;
575
+ this.buffer.push(entry);
576
+ if (this.buffer.length >= this.maxSize) {
577
+ this.flush();
578
+ }
579
+ }
580
+ /**
581
+ * Flush buffer and send telemetry
582
+ */
583
+ async flush() {
584
+ if (this.buffer.length === 0) return [];
585
+ const entries = [...this.buffer];
586
+ this.buffer = [];
587
+ if (this.flushCallback) {
588
+ try {
589
+ await this.flushCallback(entries);
590
+ } catch (err) {
591
+ console.debug("Telemetry flush failed:", err);
592
+ }
593
+ }
594
+ return entries;
595
+ }
596
+ /**
597
+ * Get current buffer size
598
+ */
599
+ get size() {
600
+ return this.buffer.length;
601
+ }
602
+ startFlushTimer() {
603
+ this.flushTimer = setInterval(() => {
604
+ this.flush();
605
+ }, this.flushInterval);
606
+ }
607
+ /**
608
+ * Stop the flush timer and flush remaining entries
609
+ */
610
+ async stop() {
611
+ if (this.flushTimer) {
612
+ clearInterval(this.flushTimer);
613
+ }
614
+ await this.flush();
615
+ }
616
+ };
617
+
618
+ // src/enhance.ts
619
+ var asyncContext = new async_hooks.AsyncLocalStorage();
620
+ function getCurrentContext() {
621
+ return asyncContext.getStore();
622
+ }
623
+ function shouldRunHandler(alwaysRun, label) {
624
+ if (alwaysRun === void 0 || alwaysRun === false) {
625
+ return false;
626
+ }
627
+ if (alwaysRun === true) {
628
+ return true;
629
+ }
630
+ const labels = Array.isArray(alwaysRun) ? alwaysRun : [alwaysRun];
631
+ const requestLabel = label || "default";
632
+ return labels.includes(requestLabel);
633
+ }
634
+ var requestContextMap = /* @__PURE__ */ new WeakMap();
635
+ var FetchBrain = class {
636
+ constructor(config) {
637
+ this.client = new FetchBrainClient(config);
638
+ this.logger = createLogger(config.debug ? "debug" : "info", true);
639
+ }
640
+ /**
641
+ * Query if FetchBrain "knows" a URL
642
+ */
643
+ async query(options) {
644
+ const result = await this.client.query(options.url);
645
+ return {
646
+ known: result.known,
647
+ data: result.data,
648
+ confidence: result.confidence
649
+ };
650
+ }
651
+ /**
652
+ * "Teach" FetchBrain new data
653
+ */
654
+ async learn(options) {
655
+ return this.client.learn(options.url, options.data);
656
+ }
657
+ /**
658
+ * Get usage statistics
659
+ */
660
+ async stats() {
661
+ return this.client.stats();
662
+ }
663
+ /**
664
+ * Enhance a Crawlee crawler with FetchBrain optimization
665
+ *
666
+ * This wraps the crawler's request handler to:
667
+ * 1. Query AI before making requests (AI knows = skip request)
668
+ * 2. Teach AI after successful requests (learning)
669
+ *
670
+ * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
671
+ * @param config - FetchBrain configuration
672
+ * @returns Enhanced crawler with same interface
673
+ */
674
+ static enhance(crawler, config) {
675
+ const client = new FetchBrainClient(config);
676
+ const logger = createLogger(config.debug ? "debug" : "info", true);
677
+ const telemetryBuffer = new TelemetryBuffer({
678
+ maxSize: 50,
679
+ flushInterval: 3e4,
680
+ onFlush: async (entries) => {
681
+ if (config.telemetry?.enabled) {
682
+ await client.sendTelemetry(entries);
683
+ logger.debug(`Telemetry: sent ${entries.length} entries`);
684
+ }
685
+ }
686
+ });
687
+ const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
688
+ if (!originalHandler) {
689
+ logger.warn("No request handler found on crawler, returning unmodified");
690
+ return Object.assign(crawler, { fetchBrain: client });
691
+ }
692
+ const crawlerType = crawler.constructor?.name || "Unknown";
693
+ const wrappedHandler = async (context) => {
694
+ const { request } = context;
695
+ const url = request.url;
696
+ const label = request.label;
697
+ const startTime = Date.now();
698
+ setScrapeContext({
699
+ crawler: crawlerType,
700
+ label,
701
+ url
702
+ });
703
+ try {
704
+ const aiResult = await client.query(url);
705
+ let usedAIData = false;
706
+ const originalPushData = context.pushData;
707
+ context.ai = {
708
+ known: aiResult.known,
709
+ data: aiResult.data,
710
+ confidence: aiResult.confidence,
711
+ useAIData: async () => {
712
+ if (aiResult.known && aiResult.data && originalPushData) {
713
+ usedAIData = true;
714
+ await originalPushData.call(context, aiResult.data);
715
+ logger.info(
716
+ `Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
717
+ );
718
+ }
719
+ }
720
+ };
721
+ request.userData = {
722
+ ...request.userData,
723
+ fetchBrainKnown: aiResult.known,
724
+ fetchBrainData: aiResult.data
725
+ };
726
+ const handlerLabel = request.label;
727
+ const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
728
+ if (aiResult.known && aiResult.data && !runHandler) {
729
+ logger.info(
730
+ `Optimized: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
731
+ );
732
+ if (originalPushData) {
733
+ await originalPushData.call(context, aiResult.data);
734
+ }
735
+ return;
736
+ }
737
+ if (aiResult.known) {
738
+ logger.info(
739
+ `Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
740
+ );
741
+ } else {
742
+ logger.debug(`Learning: ${url}`);
743
+ }
744
+ requestContextMap.set(context, url);
745
+ if (originalPushData && config.learning !== false) {
746
+ context.pushData = async (data) => {
747
+ const shouldLearn = !usedAIData && !aiResult.known;
748
+ if (shouldLearn) {
749
+ const currentUrl = requestContextMap.get(context) || url;
750
+ await client.learn(currentUrl, data);
751
+ }
752
+ return originalPushData.call(context, data);
753
+ };
754
+ }
755
+ const requestContext = {
756
+ url,
757
+ client,
758
+ learning: config.learning !== false,
759
+ aiKnown: aiResult.known
760
+ };
761
+ await asyncContext.run(requestContext, async () => {
762
+ await originalHandler.call(crawler, context);
763
+ });
764
+ requestContextMap.delete(context);
765
+ if (config.telemetry?.enabled) {
766
+ try {
767
+ const telemetry = await collectTelemetry(
768
+ {
769
+ request: {
770
+ url,
771
+ retryCount: request.retryCount,
772
+ label,
773
+ userData: request.userData
774
+ },
775
+ response: {
776
+ statusCode: context.response?.statusCode || context.response?.status
777
+ },
778
+ proxyInfo: context.proxyInfo ? {
779
+ url: context.proxyInfo.url,
780
+ hostname: context.proxyInfo.hostname,
781
+ countryCode: context.proxyInfo.countryCode
782
+ } : void 0,
783
+ session: context.session ? {
784
+ errorScore: context.session.errorScore,
785
+ usageCount: context.session.usageCount
786
+ } : void 0,
787
+ crawler: {
788
+ constructor: { name: crawlerType }
789
+ }
790
+ },
791
+ {
792
+ startTime,
793
+ endTime: Date.now(),
794
+ responseTime: Date.now() - startTime,
795
+ contentSize: context.response?.body?.length
796
+ },
797
+ config.telemetry
798
+ );
799
+ if (telemetry) {
800
+ telemetryBuffer.add(telemetry);
801
+ }
802
+ } catch (err) {
803
+ logger.debug(`Telemetry collection error: ${err}`);
804
+ }
805
+ }
806
+ } catch (err) {
807
+ if (config.telemetry?.enabled) {
808
+ try {
809
+ const telemetry = await collectTelemetry(
810
+ {
811
+ request: {
812
+ url,
813
+ retryCount: request.retryCount,
814
+ label
815
+ },
816
+ crawler: {
817
+ constructor: { name: crawlerType }
818
+ }
819
+ },
820
+ {
821
+ startTime,
822
+ endTime: Date.now(),
823
+ responseTime: Date.now() - startTime
824
+ },
825
+ config.telemetry,
826
+ err instanceof Error ? err : new Error(String(err))
827
+ );
828
+ if (telemetry) {
829
+ telemetryBuffer.add(telemetry);
830
+ }
831
+ } catch {
832
+ }
833
+ }
834
+ throw err;
835
+ } finally {
836
+ clearScrapeContext();
837
+ }
838
+ };
839
+ const crawlerAny = crawler;
840
+ if ("requestHandler" in crawlerAny) {
841
+ crawlerAny.requestHandler = wrappedHandler;
842
+ }
843
+ if ("userDefinedRequestHandler" in crawlerAny) {
844
+ crawlerAny.userDefinedRequestHandler = wrappedHandler;
845
+ }
846
+ if (typeof crawlerAny.run === "function") {
847
+ const originalRun = crawlerAny.run.bind(crawlerAny);
848
+ crawlerAny.run = async (...args) => {
849
+ try {
850
+ const result = await originalRun(...args);
851
+ return result;
852
+ } finally {
853
+ if (config.telemetry?.enabled) {
854
+ logger.debug("Telemetry: flushing on crawl complete");
855
+ await telemetryBuffer.stop();
856
+ }
857
+ }
858
+ };
859
+ }
860
+ return Object.assign(crawler, { fetchBrain: client });
861
+ }
862
+ };
863
+ function createFetchBrain(config) {
864
+ return new FetchBrain(config);
865
+ }
866
+ async function pushData(data, dataset, datasetName) {
867
+ const ctx = getCurrentContext();
868
+ if (ctx && ctx.learning && !ctx.aiKnown) {
869
+ const items = Array.isArray(data) ? data : [data];
870
+ for (const item of items) {
871
+ await ctx.client.learn(ctx.url, item);
872
+ }
873
+ }
874
+ if (datasetName && dataset.open) {
875
+ const namedDataset = await dataset.open(datasetName);
876
+ await namedDataset.pushData(data);
877
+ } else {
878
+ await dataset.pushData(data);
879
+ }
880
+ }
881
+
882
+ // src/types.ts
883
+ var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
884
+ AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
885
+ AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
886
+ AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
887
+ AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
888
+ return AIMemoryDepth2;
889
+ })(AIMemoryDepth || {});
890
+
891
+ exports.AIMemoryDepth = AIMemoryDepth;
892
+ exports.CircuitBreaker = CircuitBreaker;
893
+ exports.FetchBrain = FetchBrain;
894
+ exports.FetchBrainClient = FetchBrainClient;
895
+ exports.RequestBatcher = RequestBatcher;
896
+ exports.TelemetryBuffer = TelemetryBuffer;
897
+ exports.collectTelemetry = collectTelemetry;
898
+ exports.createFetchBrain = createFetchBrain;
899
+ exports.createLogger = createLogger;
900
+ exports.getCurrentContext = getCurrentContext;
901
+ exports.pushData = pushData;
902
+ //# sourceMappingURL=index.js.map
903
+ //# sourceMappingURL=index.js.map