@fetchbrain.com/sdk 0.1.5 → 0.1.7
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 +11 -7
- package/dist/index.d.mts +31 -8
- package/dist/index.d.ts +31 -8
- package/dist/index.js +199 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +199 -25
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **The AI That Already Knows The Web** - AI-powered scraping optimization for Crawlee
|
|
4
4
|
|
|
5
|
-
[](https://www.npmjs.com/package/@fetchbrain
|
|
6
|
-
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [](https://www.npmjs.com/package/@fetchbrain/sdk) [](https://opensource.org/licenses/MIT)
|
|
7
6
|
|
|
8
7
|
FetchBrain uses a neural network continuously trained on millions of web pages. Ask first → Get instant results. AI doesn't know? → We fetch & learn for next time.
|
|
9
8
|
|
|
@@ -42,7 +41,7 @@ const crawler = FetchBrain.enhance(
|
|
|
42
41
|
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
43
42
|
intelligence: "high", // High confidence AI responses
|
|
44
43
|
learning: true, // AI learns from scraped pages
|
|
45
|
-
}
|
|
44
|
+
},
|
|
46
45
|
);
|
|
47
46
|
|
|
48
47
|
await crawler.run(urls);
|
|
@@ -136,7 +135,7 @@ const crawler = FetchBrain.enhance(
|
|
|
136
135
|
await pushData(data);
|
|
137
136
|
},
|
|
138
137
|
}),
|
|
139
|
-
{ apiKey: "your-api-key", alwaysRun: true }
|
|
138
|
+
{ apiKey: "your-api-key", alwaysRun: true },
|
|
140
139
|
);
|
|
141
140
|
```
|
|
142
141
|
|
|
@@ -152,6 +151,8 @@ const crawler = FetchBrain.enhance(
|
|
|
152
151
|
|
|
153
152
|
## Using Dataset.pushData
|
|
154
153
|
|
|
154
|
+
> ⚠️ **Important**: AI learning **only happens** when you use `context.pushData()` or the SDK's `pushData()` wrapper below. Direct calls to `Dataset.pushData()` **will not trigger learning**, and the AI won't recognize these URLs in future runs.
|
|
155
|
+
|
|
155
156
|
If you use `Dataset.pushData()` instead of `context.pushData()`, use our wrapper for automatic AI learning:
|
|
156
157
|
|
|
157
158
|
```typescript
|
|
@@ -163,14 +164,17 @@ const crawler = FetchBrain.enhance(
|
|
|
163
164
|
requestHandler: async ({ $, request }) => {
|
|
164
165
|
const data = { title: $("h1").text() };
|
|
165
166
|
|
|
166
|
-
// Use pushData wrapper for AI learning
|
|
167
|
+
// ✅ Use pushData wrapper for AI learning
|
|
167
168
|
await pushData(data, Dataset);
|
|
168
169
|
|
|
169
|
-
// Or with named dataset
|
|
170
|
+
// ✅ Or with named dataset
|
|
170
171
|
await pushData(data, Dataset, "products");
|
|
172
|
+
|
|
173
|
+
// ❌ This will NOT learn:
|
|
174
|
+
// await Dataset.pushData(data);
|
|
171
175
|
},
|
|
172
176
|
}),
|
|
173
|
-
{ apiKey: "your-api-key" }
|
|
177
|
+
{ apiKey: "your-api-key" },
|
|
174
178
|
);
|
|
175
179
|
```
|
|
176
180
|
|
package/dist/index.d.mts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Type definitions for the FetchBrain AI-powered scraping optimization SDK.
|
|
5
5
|
*/
|
|
6
6
|
/** Intelligence level for AI inference accuracy */
|
|
7
|
-
type IntelligenceLevel =
|
|
7
|
+
type IntelligenceLevel = "realtime" | "high" | "standard" | "deep";
|
|
8
8
|
/** AI memory depth levels - deeper memory may have minor hallucinations */
|
|
9
9
|
declare enum AIMemoryDepth {
|
|
10
10
|
REALTIME = 1,
|
|
@@ -35,16 +35,29 @@ interface FetchBrainConfig {
|
|
|
35
35
|
/** Custom data extractor for learning */
|
|
36
36
|
extractForLearning?: (data: unknown) => Record<string, unknown>;
|
|
37
37
|
/**
|
|
38
|
-
* If true, only return
|
|
38
|
+
* If true, only return recognized data from the same build version.
|
|
39
39
|
* When a scraper updates, it will re-scrape instead of using stale data.
|
|
40
40
|
* Uses APIFY_ACTOR_BUILD_ID environment variable.
|
|
41
41
|
* Default: false
|
|
42
42
|
*/
|
|
43
|
-
|
|
43
|
+
refreshOnRebuild?: boolean;
|
|
44
44
|
/** Request timeout in ms (default: 500ms for fast degradation) */
|
|
45
45
|
timeout?: number;
|
|
46
46
|
/** Enable debug logging */
|
|
47
47
|
debug?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Field name to use as URL for learning
|
|
50
|
+
* Useful when request URL is an API endpoint but data contains the actual page URL
|
|
51
|
+
*/
|
|
52
|
+
learnUrlField?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Batching configuration for high-performance crawling
|
|
55
|
+
*/
|
|
56
|
+
batch?: Partial<BatchConfig>;
|
|
57
|
+
/**
|
|
58
|
+
* Circuit breaker configuration for stability
|
|
59
|
+
*/
|
|
60
|
+
circuitBreaker?: Partial<CircuitBreakerConfig>;
|
|
48
61
|
/**
|
|
49
62
|
* Telemetry configuration - opt-in anonymous data sharing
|
|
50
63
|
* Helps improve proxy recommendations, detect blocks, optimize configs
|
|
@@ -82,7 +95,7 @@ interface LearnRequest {
|
|
|
82
95
|
}
|
|
83
96
|
/** Learn response from the API */
|
|
84
97
|
interface LearnResponse {
|
|
85
|
-
status:
|
|
98
|
+
status: "accepted" | "rejected" | "flagged";
|
|
86
99
|
learned: number;
|
|
87
100
|
verification?: {
|
|
88
101
|
schemaValid: boolean;
|
|
@@ -107,7 +120,7 @@ interface AIResult {
|
|
|
107
120
|
fallback?: boolean;
|
|
108
121
|
}
|
|
109
122
|
/** Circuit breaker states */
|
|
110
|
-
type CircuitState =
|
|
123
|
+
type CircuitState = "closed" | "open" | "half-open";
|
|
111
124
|
/** Circuit breaker configuration */
|
|
112
125
|
interface CircuitBreakerConfig {
|
|
113
126
|
/** Number of failures before opening circuit */
|
|
@@ -125,7 +138,7 @@ interface BatchConfig {
|
|
|
125
138
|
maxWait: number;
|
|
126
139
|
}
|
|
127
140
|
/** Log levels */
|
|
128
|
-
type LogLevel =
|
|
141
|
+
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
129
142
|
/** Logger interface */
|
|
130
143
|
interface Logger {
|
|
131
144
|
debug: (message: string, ...args: unknown[]) => void;
|
|
@@ -182,7 +195,7 @@ interface TelemetryRequest {
|
|
|
182
195
|
*/
|
|
183
196
|
interface TelemetryResponse {
|
|
184
197
|
received: number;
|
|
185
|
-
status:
|
|
198
|
+
status: "success" | "partial" | "error";
|
|
186
199
|
}
|
|
187
200
|
|
|
188
201
|
/**
|
|
@@ -197,6 +210,7 @@ declare class FetchBrainClient {
|
|
|
197
210
|
private config;
|
|
198
211
|
private circuitBreaker;
|
|
199
212
|
private batcher;
|
|
213
|
+
private learnBatcher;
|
|
200
214
|
private logger;
|
|
201
215
|
constructor(config: FetchBrainConfig);
|
|
202
216
|
/**
|
|
@@ -208,7 +222,7 @@ declare class FetchBrainClient {
|
|
|
208
222
|
*/
|
|
209
223
|
queryBulk(urls: string[]): Promise<Map<string, AIResult>>;
|
|
210
224
|
/**
|
|
211
|
-
* "Teach" FetchBrain new data
|
|
225
|
+
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
212
226
|
*/
|
|
213
227
|
learn(url: string, data: Record<string, unknown>): Promise<LearnResponse>;
|
|
214
228
|
/**
|
|
@@ -219,6 +233,10 @@ declare class FetchBrainClient {
|
|
|
219
233
|
* Execute a batch query against the API
|
|
220
234
|
*/
|
|
221
235
|
private executeBatchQuery;
|
|
236
|
+
/**
|
|
237
|
+
* Execute a batch learn against the API
|
|
238
|
+
*/
|
|
239
|
+
private executeBatchLearn;
|
|
222
240
|
/**
|
|
223
241
|
* Make an HTTP request to the API
|
|
224
242
|
*/
|
|
@@ -243,6 +261,10 @@ declare class FetchBrainClient {
|
|
|
243
261
|
* Clear pending batched requests
|
|
244
262
|
*/
|
|
245
263
|
clearBatch(): void;
|
|
264
|
+
/**
|
|
265
|
+
* Flush pending learn requests (call before shutdown)
|
|
266
|
+
*/
|
|
267
|
+
flushLearnBatch(): Promise<void>;
|
|
246
268
|
/**
|
|
247
269
|
* Send telemetry data to the API
|
|
248
270
|
* This is fire-and-forget - failures are silently ignored
|
|
@@ -447,6 +469,7 @@ declare class RequestBatcher {
|
|
|
447
469
|
|
|
448
470
|
/**
|
|
449
471
|
* Creates a logger with the specified minimum level
|
|
472
|
+
* Matches Crawlee log style: "INFO FetchBrain: message"
|
|
450
473
|
*/
|
|
451
474
|
declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
|
|
452
475
|
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Type definitions for the FetchBrain AI-powered scraping optimization SDK.
|
|
5
5
|
*/
|
|
6
6
|
/** Intelligence level for AI inference accuracy */
|
|
7
|
-
type IntelligenceLevel =
|
|
7
|
+
type IntelligenceLevel = "realtime" | "high" | "standard" | "deep";
|
|
8
8
|
/** AI memory depth levels - deeper memory may have minor hallucinations */
|
|
9
9
|
declare enum AIMemoryDepth {
|
|
10
10
|
REALTIME = 1,
|
|
@@ -35,16 +35,29 @@ interface FetchBrainConfig {
|
|
|
35
35
|
/** Custom data extractor for learning */
|
|
36
36
|
extractForLearning?: (data: unknown) => Record<string, unknown>;
|
|
37
37
|
/**
|
|
38
|
-
* If true, only return
|
|
38
|
+
* If true, only return recognized data from the same build version.
|
|
39
39
|
* When a scraper updates, it will re-scrape instead of using stale data.
|
|
40
40
|
* Uses APIFY_ACTOR_BUILD_ID environment variable.
|
|
41
41
|
* Default: false
|
|
42
42
|
*/
|
|
43
|
-
|
|
43
|
+
refreshOnRebuild?: boolean;
|
|
44
44
|
/** Request timeout in ms (default: 500ms for fast degradation) */
|
|
45
45
|
timeout?: number;
|
|
46
46
|
/** Enable debug logging */
|
|
47
47
|
debug?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Field name to use as URL for learning
|
|
50
|
+
* Useful when request URL is an API endpoint but data contains the actual page URL
|
|
51
|
+
*/
|
|
52
|
+
learnUrlField?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Batching configuration for high-performance crawling
|
|
55
|
+
*/
|
|
56
|
+
batch?: Partial<BatchConfig>;
|
|
57
|
+
/**
|
|
58
|
+
* Circuit breaker configuration for stability
|
|
59
|
+
*/
|
|
60
|
+
circuitBreaker?: Partial<CircuitBreakerConfig>;
|
|
48
61
|
/**
|
|
49
62
|
* Telemetry configuration - opt-in anonymous data sharing
|
|
50
63
|
* Helps improve proxy recommendations, detect blocks, optimize configs
|
|
@@ -82,7 +95,7 @@ interface LearnRequest {
|
|
|
82
95
|
}
|
|
83
96
|
/** Learn response from the API */
|
|
84
97
|
interface LearnResponse {
|
|
85
|
-
status:
|
|
98
|
+
status: "accepted" | "rejected" | "flagged";
|
|
86
99
|
learned: number;
|
|
87
100
|
verification?: {
|
|
88
101
|
schemaValid: boolean;
|
|
@@ -107,7 +120,7 @@ interface AIResult {
|
|
|
107
120
|
fallback?: boolean;
|
|
108
121
|
}
|
|
109
122
|
/** Circuit breaker states */
|
|
110
|
-
type CircuitState =
|
|
123
|
+
type CircuitState = "closed" | "open" | "half-open";
|
|
111
124
|
/** Circuit breaker configuration */
|
|
112
125
|
interface CircuitBreakerConfig {
|
|
113
126
|
/** Number of failures before opening circuit */
|
|
@@ -125,7 +138,7 @@ interface BatchConfig {
|
|
|
125
138
|
maxWait: number;
|
|
126
139
|
}
|
|
127
140
|
/** Log levels */
|
|
128
|
-
type LogLevel =
|
|
141
|
+
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
129
142
|
/** Logger interface */
|
|
130
143
|
interface Logger {
|
|
131
144
|
debug: (message: string, ...args: unknown[]) => void;
|
|
@@ -182,7 +195,7 @@ interface TelemetryRequest {
|
|
|
182
195
|
*/
|
|
183
196
|
interface TelemetryResponse {
|
|
184
197
|
received: number;
|
|
185
|
-
status:
|
|
198
|
+
status: "success" | "partial" | "error";
|
|
186
199
|
}
|
|
187
200
|
|
|
188
201
|
/**
|
|
@@ -197,6 +210,7 @@ declare class FetchBrainClient {
|
|
|
197
210
|
private config;
|
|
198
211
|
private circuitBreaker;
|
|
199
212
|
private batcher;
|
|
213
|
+
private learnBatcher;
|
|
200
214
|
private logger;
|
|
201
215
|
constructor(config: FetchBrainConfig);
|
|
202
216
|
/**
|
|
@@ -208,7 +222,7 @@ declare class FetchBrainClient {
|
|
|
208
222
|
*/
|
|
209
223
|
queryBulk(urls: string[]): Promise<Map<string, AIResult>>;
|
|
210
224
|
/**
|
|
211
|
-
* "Teach" FetchBrain new data
|
|
225
|
+
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
212
226
|
*/
|
|
213
227
|
learn(url: string, data: Record<string, unknown>): Promise<LearnResponse>;
|
|
214
228
|
/**
|
|
@@ -219,6 +233,10 @@ declare class FetchBrainClient {
|
|
|
219
233
|
* Execute a batch query against the API
|
|
220
234
|
*/
|
|
221
235
|
private executeBatchQuery;
|
|
236
|
+
/**
|
|
237
|
+
* Execute a batch learn against the API
|
|
238
|
+
*/
|
|
239
|
+
private executeBatchLearn;
|
|
222
240
|
/**
|
|
223
241
|
* Make an HTTP request to the API
|
|
224
242
|
*/
|
|
@@ -243,6 +261,10 @@ declare class FetchBrainClient {
|
|
|
243
261
|
* Clear pending batched requests
|
|
244
262
|
*/
|
|
245
263
|
clearBatch(): void;
|
|
264
|
+
/**
|
|
265
|
+
* Flush pending learn requests (call before shutdown)
|
|
266
|
+
*/
|
|
267
|
+
flushLearnBatch(): Promise<void>;
|
|
246
268
|
/**
|
|
247
269
|
* Send telemetry data to the API
|
|
248
270
|
* This is fire-and-forget - failures are silently ignored
|
|
@@ -447,6 +469,7 @@ declare class RequestBatcher {
|
|
|
447
469
|
|
|
448
470
|
/**
|
|
449
471
|
* Creates a logger with the specified minimum level
|
|
472
|
+
* Matches Crawlee log style: "INFO FetchBrain: message"
|
|
450
473
|
*/
|
|
451
474
|
declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
|
|
452
475
|
|
package/dist/index.js
CHANGED
|
@@ -184,39 +184,146 @@ var RequestBatcher = class {
|
|
|
184
184
|
this.queue = [];
|
|
185
185
|
}
|
|
186
186
|
};
|
|
187
|
+
var LearnBatcher = class {
|
|
188
|
+
constructor(executor, config = {}, logger) {
|
|
189
|
+
this.queue = [];
|
|
190
|
+
this.flushTimeout = null;
|
|
191
|
+
this.executor = executor;
|
|
192
|
+
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
193
|
+
this.logger = logger;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Add a learn entry to the batch queue
|
|
197
|
+
*/
|
|
198
|
+
async learn(url, data) {
|
|
199
|
+
return new Promise((resolve, reject) => {
|
|
200
|
+
this.queue.push({ entry: { url, data }, resolve, reject });
|
|
201
|
+
if (this.queue.length >= this.config.maxSize) {
|
|
202
|
+
this.flush();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (!this.flushTimeout) {
|
|
206
|
+
this.flushTimeout = setTimeout(() => {
|
|
207
|
+
this.flush();
|
|
208
|
+
}, this.config.maxWait);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Flush the current batch
|
|
214
|
+
*/
|
|
215
|
+
async flush() {
|
|
216
|
+
if (this.flushTimeout) {
|
|
217
|
+
clearTimeout(this.flushTimeout);
|
|
218
|
+
this.flushTimeout = null;
|
|
219
|
+
}
|
|
220
|
+
if (this.queue.length === 0) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const batch = this.queue.splice(0, this.config.maxSize);
|
|
224
|
+
const entries = batch.map((r) => r.entry);
|
|
225
|
+
this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
|
|
226
|
+
try {
|
|
227
|
+
const result = await this.executor(entries);
|
|
228
|
+
for (const request of batch) {
|
|
229
|
+
request.resolve(result);
|
|
230
|
+
}
|
|
231
|
+
} catch (error) {
|
|
232
|
+
for (const request of batch) {
|
|
233
|
+
request.reject(error);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (this.queue.length > 0) {
|
|
237
|
+
this.flushTimeout = setTimeout(() => {
|
|
238
|
+
this.flush();
|
|
239
|
+
}, this.config.maxWait);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Force flush and wait for completion (for cleanup/shutdown)
|
|
244
|
+
*/
|
|
245
|
+
async forceFlush() {
|
|
246
|
+
if (this.queue.length > 0) {
|
|
247
|
+
await this.flush();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Get current queue size
|
|
252
|
+
*/
|
|
253
|
+
getQueueSize() {
|
|
254
|
+
return this.queue.length;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Clear the queue (for cleanup)
|
|
258
|
+
*/
|
|
259
|
+
clear() {
|
|
260
|
+
if (this.flushTimeout) {
|
|
261
|
+
clearTimeout(this.flushTimeout);
|
|
262
|
+
this.flushTimeout = null;
|
|
263
|
+
}
|
|
264
|
+
for (const request of this.queue) {
|
|
265
|
+
request.resolve({ status: "rejected", learned: 0 });
|
|
266
|
+
}
|
|
267
|
+
this.queue = [];
|
|
268
|
+
}
|
|
269
|
+
};
|
|
187
270
|
|
|
188
271
|
// src/logger.ts
|
|
189
|
-
var
|
|
272
|
+
var COLORS = {
|
|
273
|
+
reset: "\x1B[0m",
|
|
274
|
+
cyan: "\x1B[36m",
|
|
275
|
+
green: "\x1B[32m",
|
|
276
|
+
yellow: "\x1B[33m",
|
|
277
|
+
red: "\x1B[31m",
|
|
278
|
+
gray: "\x1B[90m"
|
|
279
|
+
};
|
|
190
280
|
var LOG_LEVELS = {
|
|
191
281
|
debug: 0,
|
|
192
282
|
info: 1,
|
|
193
283
|
warn: 2,
|
|
194
284
|
error: 3
|
|
195
285
|
};
|
|
286
|
+
var LEVEL_COLORS = {
|
|
287
|
+
debug: COLORS.gray,
|
|
288
|
+
info: COLORS.green,
|
|
289
|
+
warn: COLORS.yellow,
|
|
290
|
+
error: COLORS.red
|
|
291
|
+
};
|
|
292
|
+
var LEVEL_LABELS = {
|
|
293
|
+
debug: "DEBUG",
|
|
294
|
+
info: "INFO ",
|
|
295
|
+
warn: "WARN ",
|
|
296
|
+
error: "ERROR"
|
|
297
|
+
};
|
|
196
298
|
function createLogger(minLevel = "info", enabled = true) {
|
|
197
299
|
const shouldLog = (level) => {
|
|
198
300
|
if (!enabled) return false;
|
|
199
301
|
return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
|
|
200
302
|
};
|
|
303
|
+
const formatLog = (level, message) => {
|
|
304
|
+
const levelColor = LEVEL_COLORS[level];
|
|
305
|
+
const label = LEVEL_LABELS[level];
|
|
306
|
+
return `${levelColor}${label}${COLORS.reset} ${COLORS.cyan}FetchBrain:${COLORS.reset} ${message}`;
|
|
307
|
+
};
|
|
201
308
|
return {
|
|
202
309
|
debug: (message, ...args) => {
|
|
203
310
|
if (shouldLog("debug")) {
|
|
204
|
-
console.debug(
|
|
311
|
+
console.debug(formatLog("debug", message), ...args);
|
|
205
312
|
}
|
|
206
313
|
},
|
|
207
314
|
info: (message, ...args) => {
|
|
208
315
|
if (shouldLog("info")) {
|
|
209
|
-
console.info(
|
|
316
|
+
console.info(formatLog("info", message), ...args);
|
|
210
317
|
}
|
|
211
318
|
},
|
|
212
319
|
warn: (message, ...args) => {
|
|
213
320
|
if (shouldLog("warn")) {
|
|
214
|
-
console.warn(
|
|
321
|
+
console.warn(formatLog("warn", message), ...args);
|
|
215
322
|
}
|
|
216
323
|
},
|
|
217
324
|
error: (message, ...args) => {
|
|
218
325
|
if (shouldLog("error")) {
|
|
219
|
-
console.error(
|
|
326
|
+
console.error(formatLog("error", message), ...args);
|
|
220
327
|
}
|
|
221
328
|
}
|
|
222
329
|
};
|
|
@@ -225,6 +332,7 @@ function createLogger(minLevel = "info", enabled = true) {
|
|
|
225
332
|
// src/client.ts
|
|
226
333
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
227
334
|
var DEFAULT_TIMEOUT = 500;
|
|
335
|
+
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
228
336
|
var currentContext = {};
|
|
229
337
|
function setScrapeContext(ctx) {
|
|
230
338
|
currentContext = ctx;
|
|
@@ -240,17 +348,28 @@ var FetchBrainClient = class {
|
|
|
240
348
|
intelligence: config.intelligence || "high",
|
|
241
349
|
learning: config.learning ?? true,
|
|
242
350
|
alwaysRun: config.alwaysRun ?? false,
|
|
243
|
-
|
|
351
|
+
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
244
352
|
timeout: config.timeout || DEFAULT_TIMEOUT,
|
|
245
353
|
debug: config.debug || false,
|
|
246
354
|
extractForLearning: config.extractForLearning,
|
|
247
|
-
|
|
355
|
+
learnUrlField: config.learnUrlField,
|
|
356
|
+
telemetry: config.telemetry ?? { enabled: true },
|
|
357
|
+
batch: config.batch,
|
|
358
|
+
circuitBreaker: config.circuitBreaker
|
|
248
359
|
};
|
|
249
360
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
250
|
-
this.circuitBreaker = new CircuitBreaker(
|
|
361
|
+
this.circuitBreaker = new CircuitBreaker(
|
|
362
|
+
this.config.circuitBreaker,
|
|
363
|
+
this.logger
|
|
364
|
+
);
|
|
251
365
|
this.batcher = new RequestBatcher(
|
|
252
366
|
(urls) => this.executeBatchQuery(urls),
|
|
253
|
-
|
|
367
|
+
this.config.batch,
|
|
368
|
+
this.logger
|
|
369
|
+
);
|
|
370
|
+
this.learnBatcher = new LearnBatcher(
|
|
371
|
+
(entries) => this.executeBatchLearn(entries),
|
|
372
|
+
this.config.batch,
|
|
254
373
|
this.logger
|
|
255
374
|
);
|
|
256
375
|
}
|
|
@@ -289,7 +408,7 @@ var FetchBrainClient = class {
|
|
|
289
408
|
}
|
|
290
409
|
}
|
|
291
410
|
/**
|
|
292
|
-
* "Teach" FetchBrain new data
|
|
411
|
+
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
293
412
|
*/
|
|
294
413
|
async learn(url, data) {
|
|
295
414
|
if (!this.config.learning) {
|
|
@@ -300,18 +419,10 @@ var FetchBrainClient = class {
|
|
|
300
419
|
return { status: "rejected", learned: 0 };
|
|
301
420
|
}
|
|
302
421
|
try {
|
|
303
|
-
const
|
|
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();
|
|
422
|
+
const response = await this.learnBatcher.learn(url, data);
|
|
311
423
|
this.logger.debug(`Learned data for: ${url}`);
|
|
312
424
|
return response;
|
|
313
425
|
} catch (error) {
|
|
314
|
-
this.circuitBreaker.recordFailure();
|
|
315
426
|
this.logger.warn(`Learn failed for ${url}:`, error);
|
|
316
427
|
return { status: "rejected", learned: 0 };
|
|
317
428
|
}
|
|
@@ -344,7 +455,7 @@ var FetchBrainClient = class {
|
|
|
344
455
|
urls,
|
|
345
456
|
intelligence: this.config.intelligence
|
|
346
457
|
};
|
|
347
|
-
if (this.config.
|
|
458
|
+
if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
|
|
348
459
|
request.build = process.env.APIFY_ACTOR_BUILD_ID;
|
|
349
460
|
}
|
|
350
461
|
try {
|
|
@@ -369,13 +480,43 @@ var FetchBrainClient = class {
|
|
|
369
480
|
throw error;
|
|
370
481
|
}
|
|
371
482
|
}
|
|
483
|
+
/**
|
|
484
|
+
* Execute a batch learn against the API
|
|
485
|
+
*/
|
|
486
|
+
async executeBatchLearn(entries) {
|
|
487
|
+
const processedEntries = entries.map((entry) => ({
|
|
488
|
+
url: entry.url,
|
|
489
|
+
data: this.config.extractForLearning ? this.config.extractForLearning(entry.data) : entry.data
|
|
490
|
+
}));
|
|
491
|
+
try {
|
|
492
|
+
const response = await this.makeRequest(
|
|
493
|
+
"/v1/learn",
|
|
494
|
+
{
|
|
495
|
+
method: "POST",
|
|
496
|
+
body: JSON.stringify({
|
|
497
|
+
entries: processedEntries
|
|
498
|
+
})
|
|
499
|
+
},
|
|
500
|
+
DEFAULT_LEARN_TIMEOUT
|
|
501
|
+
);
|
|
502
|
+
this.circuitBreaker.recordSuccess();
|
|
503
|
+
this.logger.debug(`Batch learned ${entries.length} entries`);
|
|
504
|
+
return response;
|
|
505
|
+
} catch (error) {
|
|
506
|
+
this.circuitBreaker.recordFailure();
|
|
507
|
+
throw error;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
372
510
|
/**
|
|
373
511
|
* Make an HTTP request to the API
|
|
374
512
|
*/
|
|
375
|
-
async makeRequest(path, options) {
|
|
513
|
+
async makeRequest(path, options, timeout) {
|
|
376
514
|
const url = `${this.config.baseUrl}${path}`;
|
|
377
515
|
const controller = new AbortController();
|
|
378
|
-
const timeoutId = setTimeout(
|
|
516
|
+
const timeoutId = setTimeout(
|
|
517
|
+
() => controller.abort(),
|
|
518
|
+
timeout ?? this.config.timeout
|
|
519
|
+
);
|
|
379
520
|
const contextHeaders = {
|
|
380
521
|
"X-FB-SDK": "js",
|
|
381
522
|
"X-FB-Node": process.version || "unknown",
|
|
@@ -441,6 +582,13 @@ var FetchBrainClient = class {
|
|
|
441
582
|
*/
|
|
442
583
|
clearBatch() {
|
|
443
584
|
this.batcher.clear();
|
|
585
|
+
this.learnBatcher.clear();
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Flush pending learn requests (call before shutdown)
|
|
589
|
+
*/
|
|
590
|
+
async flushLearnBatch() {
|
|
591
|
+
await this.learnBatcher.forceFlush();
|
|
444
592
|
}
|
|
445
593
|
/**
|
|
446
594
|
* Send telemetry data to the API
|
|
@@ -684,6 +832,16 @@ var FetchBrain = class {
|
|
|
684
832
|
}
|
|
685
833
|
}
|
|
686
834
|
});
|
|
835
|
+
const runStats = {
|
|
836
|
+
totalRequests: 0,
|
|
837
|
+
aiKnown: 0,
|
|
838
|
+
aiSkipped: 0,
|
|
839
|
+
// AI knew + skipped scraping
|
|
840
|
+
learned: 0,
|
|
841
|
+
scraped: 0,
|
|
842
|
+
// Actually ran handler
|
|
843
|
+
startTime: 0
|
|
844
|
+
};
|
|
687
845
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
688
846
|
if (!originalHandler) {
|
|
689
847
|
logger.warn("No request handler found on crawler, returning unmodified");
|
|
@@ -695,6 +853,7 @@ var FetchBrain = class {
|
|
|
695
853
|
const url = request.url;
|
|
696
854
|
const label = request.label;
|
|
697
855
|
const startTime = Date.now();
|
|
856
|
+
runStats.totalRequests++;
|
|
698
857
|
setScrapeContext({
|
|
699
858
|
crawler: crawlerType,
|
|
700
859
|
label,
|
|
@@ -726,15 +885,19 @@ var FetchBrain = class {
|
|
|
726
885
|
const handlerLabel = request.label;
|
|
727
886
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
728
887
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
888
|
+
runStats.aiKnown++;
|
|
889
|
+
runStats.aiSkipped++;
|
|
729
890
|
logger.info(
|
|
730
|
-
`
|
|
891
|
+
`AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
731
892
|
);
|
|
732
893
|
if (originalPushData) {
|
|
733
894
|
await originalPushData.call(context, aiResult.data);
|
|
734
895
|
}
|
|
735
896
|
return;
|
|
736
897
|
}
|
|
898
|
+
runStats.scraped++;
|
|
737
899
|
if (aiResult.known) {
|
|
900
|
+
runStats.aiKnown++;
|
|
738
901
|
logger.info(
|
|
739
902
|
`Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
|
|
740
903
|
);
|
|
@@ -746,8 +909,9 @@ var FetchBrain = class {
|
|
|
746
909
|
context.pushData = async (data) => {
|
|
747
910
|
const shouldLearn = !usedAIData && !aiResult.known;
|
|
748
911
|
if (shouldLearn) {
|
|
749
|
-
|
|
750
|
-
|
|
912
|
+
runStats.learned++;
|
|
913
|
+
const requestUrl = requestContextMap.get(context) || url;
|
|
914
|
+
await client.learn(requestUrl, data);
|
|
751
915
|
}
|
|
752
916
|
return originalPushData.call(context, data);
|
|
753
917
|
};
|
|
@@ -846,14 +1010,24 @@ var FetchBrain = class {
|
|
|
846
1010
|
if (typeof crawlerAny.run === "function") {
|
|
847
1011
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
848
1012
|
crawlerAny.run = async (...args) => {
|
|
1013
|
+
runStats.startTime = Date.now();
|
|
849
1014
|
try {
|
|
850
1015
|
const result = await originalRun(...args);
|
|
851
1016
|
return result;
|
|
852
1017
|
} finally {
|
|
1018
|
+
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1019
|
+
await client.flushLearnBatch();
|
|
853
1020
|
if (config.telemetry?.enabled) {
|
|
854
1021
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
855
1022
|
await telemetryBuffer.stop();
|
|
856
1023
|
}
|
|
1024
|
+
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1025
|
+
1
|
|
1026
|
+
);
|
|
1027
|
+
const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
|
|
1028
|
+
logger.info(
|
|
1029
|
+
`Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
|
|
1030
|
+
);
|
|
857
1031
|
}
|
|
858
1032
|
};
|
|
859
1033
|
}
|