@fetchbrain.com/sdk 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -5
- package/dist/index.d.mts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +203 -21
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +203 -21
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +1 -1
- package/dist/mock/index.d.ts +1 -1
- package/dist/{types-BOfLGSkb.d.mts → types-BbLgy1no.d.mts} +51 -1
- package/dist/{types-BOfLGSkb.d.ts → types-BbLgy1no.d.ts} +51 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -344,7 +344,14 @@ function getPlatformBuildId(env = process.env) {
|
|
|
344
344
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
345
345
|
var DEFAULT_TIMEOUT = 500;
|
|
346
346
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
347
|
+
var BULK_RECALL_TIMEOUT = 3e3;
|
|
348
|
+
var MAX_BULK_ITEMS = 100;
|
|
349
|
+
var BULK_RECALL_CONCURRENCY = 5;
|
|
350
|
+
var MAX_LEARN_ENTRIES = 50;
|
|
347
351
|
var ASK_TIMEOUT = 1e4;
|
|
352
|
+
function clampBatch(batch, cap) {
|
|
353
|
+
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
354
|
+
}
|
|
348
355
|
var ApiError = class extends Error {
|
|
349
356
|
constructor(status, statusText, serverError) {
|
|
350
357
|
super(`API error: ${status} ${statusText}`);
|
|
@@ -376,7 +383,13 @@ var FetchBrainClient = class {
|
|
|
376
383
|
telemetry: config.telemetry ?? { enabled: false },
|
|
377
384
|
// opt-in
|
|
378
385
|
batch: config.batch,
|
|
379
|
-
circuitBreaker: config.circuitBreaker
|
|
386
|
+
circuitBreaker: config.circuitBreaker,
|
|
387
|
+
skipLabels: config.skipLabels,
|
|
388
|
+
// enhance-only; stored so getConfig() round-trips
|
|
389
|
+
preRecall: config.preRecall,
|
|
390
|
+
// enhance-only; stored so getConfig() round-trips
|
|
391
|
+
onRecalled: config.onRecalled
|
|
392
|
+
// enhance-only; stored so getConfig() round-trips
|
|
380
393
|
};
|
|
381
394
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
382
395
|
this.circuitBreaker = new CircuitBreaker(
|
|
@@ -385,12 +398,12 @@ var FetchBrainClient = class {
|
|
|
385
398
|
);
|
|
386
399
|
this.batcher = new RequestBatcher(
|
|
387
400
|
(items) => this.executeBatchQuery(items),
|
|
388
|
-
this.config.batch,
|
|
401
|
+
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
389
402
|
this.logger
|
|
390
403
|
);
|
|
391
404
|
this.learnBatcher = new LearnBatcher(
|
|
392
405
|
(entries) => this.executeBatchLearn(entries),
|
|
393
|
-
this.config.batch,
|
|
406
|
+
clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
|
|
394
407
|
this.logger
|
|
395
408
|
);
|
|
396
409
|
}
|
|
@@ -409,19 +422,38 @@ var FetchBrainClient = class {
|
|
|
409
422
|
}
|
|
410
423
|
}
|
|
411
424
|
/**
|
|
412
|
-
* Recall multiple requests at once — returns ordered array matching input order
|
|
425
|
+
* Recall multiple requests at once — returns ordered array matching input order.
|
|
426
|
+
* Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
|
|
427
|
+
* failed chunk degrades to fallback results for its own items only.
|
|
413
428
|
*/
|
|
414
429
|
async recallBulk(requests) {
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
try {
|
|
419
|
-
const items = requests.map((request, i) => ({ ref: String(i), request }));
|
|
420
|
-
const results = await this.executeBatchQuery(items);
|
|
421
|
-
return items.map((i) => results.get(i.ref) ?? { known: false });
|
|
422
|
-
} catch {
|
|
423
|
-
return requests.map(() => ({ known: false, fallback: true }));
|
|
430
|
+
const chunks = [];
|
|
431
|
+
for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
|
|
432
|
+
chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
|
|
424
433
|
}
|
|
434
|
+
const chunkResults = new Array(chunks.length);
|
|
435
|
+
let next = 0;
|
|
436
|
+
const worker = async () => {
|
|
437
|
+
while (next < chunks.length) {
|
|
438
|
+
const idx = next++;
|
|
439
|
+
const chunk = chunks[idx];
|
|
440
|
+
if (this.circuitBreaker.isOpen()) {
|
|
441
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
try {
|
|
445
|
+
const items = chunk.map((request, i) => ({ ref: String(i), request }));
|
|
446
|
+
const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
|
|
447
|
+
chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
|
|
448
|
+
} catch {
|
|
449
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
await Promise.all(
|
|
454
|
+
Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
|
|
455
|
+
);
|
|
456
|
+
return chunkResults.flat();
|
|
425
457
|
}
|
|
426
458
|
/**
|
|
427
459
|
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
@@ -509,7 +541,7 @@ var FetchBrainClient = class {
|
|
|
509
541
|
/**
|
|
510
542
|
* Execute a batch query against the API
|
|
511
543
|
*/
|
|
512
|
-
async executeBatchQuery(items) {
|
|
544
|
+
async executeBatchQuery(items, timeout) {
|
|
513
545
|
const results = /* @__PURE__ */ new Map();
|
|
514
546
|
const request = {
|
|
515
547
|
items,
|
|
@@ -520,10 +552,14 @@ var FetchBrainClient = class {
|
|
|
520
552
|
request.build = platformBuildId;
|
|
521
553
|
}
|
|
522
554
|
try {
|
|
523
|
-
const response = await this.makeRequest(
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
555
|
+
const response = await this.makeRequest(
|
|
556
|
+
"/v1/recall",
|
|
557
|
+
{
|
|
558
|
+
method: "POST",
|
|
559
|
+
body: JSON.stringify(request)
|
|
560
|
+
},
|
|
561
|
+
timeout
|
|
562
|
+
);
|
|
527
563
|
this.circuitBreaker.recordSuccess();
|
|
528
564
|
for (const item of response.known) {
|
|
529
565
|
results.set(item.ref, { known: true, data: item.data });
|
|
@@ -826,6 +862,7 @@ var TelemetryBuffer = class {
|
|
|
826
862
|
// src/enhance.ts
|
|
827
863
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
828
864
|
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
865
|
+
var MAX_STASH_ENTRIES = 5e3;
|
|
829
866
|
function buildRawRequest(request) {
|
|
830
867
|
const r = request;
|
|
831
868
|
let headers;
|
|
@@ -929,6 +966,10 @@ var FetchBrain = class {
|
|
|
929
966
|
learned: 0,
|
|
930
967
|
scraped: 0,
|
|
931
968
|
// Actually ran handler
|
|
969
|
+
bypassed: 0,
|
|
970
|
+
// skipLabels match — ran handler outside FetchBrain
|
|
971
|
+
dropped: 0,
|
|
972
|
+
// enqueue-time fetch skipped, but remembered data gone by execution
|
|
932
973
|
startTime: 0
|
|
933
974
|
};
|
|
934
975
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
@@ -938,12 +979,38 @@ var FetchBrain = class {
|
|
|
938
979
|
}
|
|
939
980
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
940
981
|
const warnedKeys = /* @__PURE__ */ new Set();
|
|
982
|
+
const preRecalledData = /* @__PURE__ */ new Map();
|
|
983
|
+
const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
|
|
984
|
+
const stashSet = (key, data) => {
|
|
985
|
+
if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
|
|
986
|
+
const oldest = preRecalledData.keys().next().value;
|
|
987
|
+
if (oldest !== void 0) preRecalledData.delete(oldest);
|
|
988
|
+
}
|
|
989
|
+
preRecalledData.set(key, data);
|
|
990
|
+
};
|
|
991
|
+
const stashTake = (r) => {
|
|
992
|
+
for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
|
|
993
|
+
const data = preRecalledData.get(key);
|
|
994
|
+
if (data) {
|
|
995
|
+
preRecalledData.delete(key);
|
|
996
|
+
return data;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return void 0;
|
|
1000
|
+
};
|
|
1001
|
+
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
941
1002
|
const wrappedHandler = async (context) => {
|
|
942
1003
|
const { request } = context;
|
|
943
1004
|
const url = request.url;
|
|
944
1005
|
const label = request.label;
|
|
945
1006
|
const startTime = Date.now();
|
|
946
1007
|
runStats.totalRequests++;
|
|
1008
|
+
if (skipLabels && skipLabels.has(label || "default")) {
|
|
1009
|
+
runStats.bypassed++;
|
|
1010
|
+
logger.debug(`Bypassing FetchBrain for [${label || "default"}]: ${url}`);
|
|
1011
|
+
await originalHandler.call(crawler, context);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
947
1014
|
setScrapeContext({
|
|
948
1015
|
crawler: crawlerType,
|
|
949
1016
|
label,
|
|
@@ -951,10 +1018,50 @@ var FetchBrain = class {
|
|
|
951
1018
|
});
|
|
952
1019
|
const rawRequest = buildRawRequest(request);
|
|
953
1020
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
1021
|
+
let consumedStash;
|
|
954
1022
|
try {
|
|
955
|
-
const
|
|
1023
|
+
const preRecalled = request.userData?.__fetchBrainResult;
|
|
1024
|
+
let aiResult;
|
|
1025
|
+
if (preRecalled?.known) {
|
|
1026
|
+
const stashedData = stashTake(rawRequest);
|
|
1027
|
+
if (stashedData) {
|
|
1028
|
+
consumedStash = stashedData;
|
|
1029
|
+
aiResult = { known: true, data: stashedData };
|
|
1030
|
+
} else {
|
|
1031
|
+
aiResult = await client.recall(rawRequest);
|
|
1032
|
+
}
|
|
1033
|
+
} else if (preRecalled) {
|
|
1034
|
+
aiResult = preRecalled;
|
|
1035
|
+
} else {
|
|
1036
|
+
aiResult = await client.recall(rawRequest);
|
|
1037
|
+
}
|
|
1038
|
+
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1039
|
+
if (aiResult.fallback) {
|
|
1040
|
+
throw new Error(
|
|
1041
|
+
`FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
runStats.dropped++;
|
|
1045
|
+
request.noRetry = true;
|
|
1046
|
+
throw new Error(
|
|
1047
|
+
`FetchBrain: ${url} skipped its fetch at enqueue time but its remembered data is no longer available \u2014 failing without retries; it will be re-scraped on a future run.`
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
956
1050
|
let usedAIData = false;
|
|
957
1051
|
const originalPushData = context.pushData;
|
|
1052
|
+
const fireOnRecalled = async (data) => {
|
|
1053
|
+
if (!config.onRecalled) return;
|
|
1054
|
+
try {
|
|
1055
|
+
await config.onRecalled({
|
|
1056
|
+
url,
|
|
1057
|
+
label: request.label,
|
|
1058
|
+
userData: rawRequest.userData,
|
|
1059
|
+
data
|
|
1060
|
+
});
|
|
1061
|
+
} catch (hookErr) {
|
|
1062
|
+
logger.debug(`onRecalled hook error: ${hookErr}`);
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
958
1065
|
context.brain = {
|
|
959
1066
|
known: aiResult.known,
|
|
960
1067
|
data: aiResult.data,
|
|
@@ -963,6 +1070,7 @@ var FetchBrain = class {
|
|
|
963
1070
|
usedAIData = true;
|
|
964
1071
|
await originalPushData.call(context, aiResult.data);
|
|
965
1072
|
logger.info(`Used brain data: ${url}`);
|
|
1073
|
+
await fireOnRecalled(aiResult.data);
|
|
966
1074
|
}
|
|
967
1075
|
}
|
|
968
1076
|
};
|
|
@@ -980,6 +1088,7 @@ var FetchBrain = class {
|
|
|
980
1088
|
if (originalPushData) {
|
|
981
1089
|
await originalPushData.call(context, aiResult.data);
|
|
982
1090
|
}
|
|
1091
|
+
await fireOnRecalled(aiResult.data);
|
|
983
1092
|
return;
|
|
984
1093
|
}
|
|
985
1094
|
runStats.scraped++;
|
|
@@ -1052,6 +1161,9 @@ var FetchBrain = class {
|
|
|
1052
1161
|
}
|
|
1053
1162
|
}
|
|
1054
1163
|
} catch (err) {
|
|
1164
|
+
if (consumedStash) {
|
|
1165
|
+
stashSet(stashKey(rawRequest), consumedStash);
|
|
1166
|
+
}
|
|
1055
1167
|
if (telemetryConfig.enabled) {
|
|
1056
1168
|
try {
|
|
1057
1169
|
const telemetry = await collectTelemetry(
|
|
@@ -1108,13 +1220,83 @@ var FetchBrain = class {
|
|
|
1108
1220
|
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1109
1221
|
1
|
|
1110
1222
|
);
|
|
1111
|
-
const
|
|
1223
|
+
const managedRequests = runStats.totalRequests - runStats.bypassed;
|
|
1224
|
+
const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
1112
1225
|
logger.info(
|
|
1113
|
-
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${
|
|
1226
|
+
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + `, duration: ${duration}s`
|
|
1114
1227
|
);
|
|
1115
1228
|
}
|
|
1116
1229
|
};
|
|
1117
1230
|
}
|
|
1231
|
+
if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
1232
|
+
const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
|
|
1233
|
+
if (crawlerAny.retryOnBlocked) {
|
|
1234
|
+
logger.info(
|
|
1235
|
+
"preRecall: this crawler uses retryOnBlocked, whose blocked-check needs a fetched response \u2014 known requests will keep their fetch; recalled data still replaces the handler."
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
crawlerAny.addRequests = async (requests, options) => {
|
|
1239
|
+
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1240
|
+
return originalAddRequests(requests, options);
|
|
1241
|
+
}
|
|
1242
|
+
const retryOnBlocked = Boolean(
|
|
1243
|
+
crawlerAny.retryOnBlocked
|
|
1244
|
+
);
|
|
1245
|
+
const batch = requests.map((r) => {
|
|
1246
|
+
if (typeof r === "string") return { url: r };
|
|
1247
|
+
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1248
|
+
return { ...r };
|
|
1249
|
+
}
|
|
1250
|
+
return r;
|
|
1251
|
+
});
|
|
1252
|
+
try {
|
|
1253
|
+
const candidateIdx = [];
|
|
1254
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1255
|
+
const r = batch[i];
|
|
1256
|
+
if (!r || typeof r.url !== "string") continue;
|
|
1257
|
+
const prior = r.userData?.__fetchBrainResult;
|
|
1258
|
+
if (prior) {
|
|
1259
|
+
if (prior.known && r.skipNavigation) r.skipNavigation = false;
|
|
1260
|
+
const rest = { ...r.userData };
|
|
1261
|
+
delete rest.__fetchBrainResult;
|
|
1262
|
+
r.userData = rest;
|
|
1263
|
+
}
|
|
1264
|
+
if (r.skipNavigation) continue;
|
|
1265
|
+
if (skipLabels && skipLabels.has(r.label || "default")) continue;
|
|
1266
|
+
if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
|
|
1267
|
+
candidateIdx.push(i);
|
|
1268
|
+
}
|
|
1269
|
+
if (candidateIdx.length > 0) {
|
|
1270
|
+
const rawRequests = candidateIdx.map(
|
|
1271
|
+
(i) => buildRawRequest(batch[i])
|
|
1272
|
+
);
|
|
1273
|
+
const results = await client.recallBulk(rawRequests);
|
|
1274
|
+
let known = 0;
|
|
1275
|
+
candidateIdx.forEach((reqIdx, j) => {
|
|
1276
|
+
const result = results[j];
|
|
1277
|
+
if (!result || result.fallback) return;
|
|
1278
|
+
const r = batch[reqIdx];
|
|
1279
|
+
if (result.known && result.data) {
|
|
1280
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
|
|
1281
|
+
stashSet(stashKey(rawRequests[j]), result.data);
|
|
1282
|
+
if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
|
|
1283
|
+
r.skipNavigation = true;
|
|
1284
|
+
known++;
|
|
1285
|
+
}
|
|
1286
|
+
} else {
|
|
1287
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
|
|
1288
|
+
}
|
|
1289
|
+
});
|
|
1290
|
+
logger.debug(
|
|
1291
|
+
`Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
|
|
1292
|
+
);
|
|
1293
|
+
}
|
|
1294
|
+
} catch (err) {
|
|
1295
|
+
logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
|
|
1296
|
+
}
|
|
1297
|
+
return originalAddRequests(batch, options);
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1118
1300
|
return Object.assign(crawler, { fetchBrain: client });
|
|
1119
1301
|
}
|
|
1120
1302
|
};
|