@fetchbrain.com/sdk 0.2.0 → 0.3.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 +259 -122
- package/dist/index.d.mts +26 -22
- package/dist/index.d.ts +26 -22
- package/dist/index.js +109 -63
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +110 -63
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +19 -7
- package/dist/mock/index.d.ts +19 -7
- package/dist/mock/index.js +35 -15
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +35 -15
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-Ddu_K1Nn.d.mts → types-CSX4KGoU.d.mts} +30 -30
- package/dist/{types-Ddu_K1Nn.d.ts → types-CSX4KGoU.d.ts} +30 -30
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -315,10 +315,43 @@ function createLogger(minLevel = "info", enabled = true) {
|
|
|
315
315
|
};
|
|
316
316
|
}
|
|
317
317
|
|
|
318
|
+
// src/native-context.ts
|
|
319
|
+
var ALLOWED_NAME = /_ID$|^(NODE_ENV|REGION|CI)$/;
|
|
320
|
+
var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
|
|
321
|
+
var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
|
|
322
|
+
var MAX_VALUE_LENGTH = 256;
|
|
323
|
+
var MAX_HEADER_LENGTH = 2048;
|
|
324
|
+
function buildNativeContext(env = process.env) {
|
|
325
|
+
const context = {};
|
|
326
|
+
const names = Object.keys(env).filter((name) => ALLOWED_NAME.test(name) && !DENYLIST.test(name)).sort();
|
|
327
|
+
for (const name of names) {
|
|
328
|
+
const value = env[name];
|
|
329
|
+
if (!value || value.length > MAX_VALUE_LENGTH) continue;
|
|
330
|
+
if (CREDENTIAL_VALUE.test(value)) continue;
|
|
331
|
+
const candidate = { ...context, [name]: value };
|
|
332
|
+
if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
|
|
333
|
+
context[name] = value;
|
|
334
|
+
}
|
|
335
|
+
if (Object.keys(context).length === 0) return void 0;
|
|
336
|
+
return JSON.stringify(context);
|
|
337
|
+
}
|
|
338
|
+
function getPlatformBuildId(env = process.env) {
|
|
339
|
+
const key = Object.keys(env).find((name) => name.endsWith("BUILD_ID"));
|
|
340
|
+
return key ? env[key] || void 0 : void 0;
|
|
341
|
+
}
|
|
342
|
+
|
|
318
343
|
// src/client.ts
|
|
319
344
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
320
345
|
var DEFAULT_TIMEOUT = 500;
|
|
321
346
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
347
|
+
var ASK_TIMEOUT = 1e4;
|
|
348
|
+
var ApiError = class extends Error {
|
|
349
|
+
constructor(status, statusText) {
|
|
350
|
+
super(`API error: ${status} ${statusText}`);
|
|
351
|
+
this.status = status;
|
|
352
|
+
this.name = "ApiError";
|
|
353
|
+
}
|
|
354
|
+
};
|
|
322
355
|
var currentContext = {};
|
|
323
356
|
function setScrapeContext(ctx) {
|
|
324
357
|
currentContext = ctx;
|
|
@@ -331,7 +364,7 @@ var FetchBrainClient = class {
|
|
|
331
364
|
this.config = {
|
|
332
365
|
apiKey: config.apiKey,
|
|
333
366
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
334
|
-
|
|
367
|
+
memory: config.memory || "recent",
|
|
335
368
|
learning: config.learning ?? true,
|
|
336
369
|
alwaysRun: config.alwaysRun ?? false,
|
|
337
370
|
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
@@ -339,7 +372,8 @@ var FetchBrainClient = class {
|
|
|
339
372
|
debug: config.debug || false,
|
|
340
373
|
extractForLearning: config.extractForLearning,
|
|
341
374
|
learnUrlField: config.learnUrlField,
|
|
342
|
-
telemetry: config.telemetry ?? { enabled:
|
|
375
|
+
telemetry: config.telemetry ?? { enabled: false },
|
|
376
|
+
// opt-in
|
|
343
377
|
batch: config.batch,
|
|
344
378
|
circuitBreaker: config.circuitBreaker
|
|
345
379
|
};
|
|
@@ -360,23 +394,23 @@ var FetchBrainClient = class {
|
|
|
360
394
|
);
|
|
361
395
|
}
|
|
362
396
|
/**
|
|
363
|
-
*
|
|
397
|
+
* Recall if FetchBrain "knows" a request
|
|
364
398
|
*/
|
|
365
|
-
async
|
|
399
|
+
async recall(request) {
|
|
366
400
|
if (this.circuitBreaker.isOpen()) {
|
|
367
401
|
return { known: false, fallback: true };
|
|
368
402
|
}
|
|
369
403
|
try {
|
|
370
404
|
return await this.batcher.query(request);
|
|
371
405
|
} catch (error) {
|
|
372
|
-
this.logger.debug("
|
|
406
|
+
this.logger.debug("Recall failed:", error);
|
|
373
407
|
return { known: false, fallback: true };
|
|
374
408
|
}
|
|
375
409
|
}
|
|
376
410
|
/**
|
|
377
|
-
*
|
|
411
|
+
* Recall multiple requests at once — returns ordered array matching input order
|
|
378
412
|
*/
|
|
379
|
-
async
|
|
413
|
+
async recallBulk(requests) {
|
|
380
414
|
if (this.circuitBreaker.isOpen()) {
|
|
381
415
|
return requests.map(() => ({ known: false, fallback: true }));
|
|
382
416
|
}
|
|
@@ -424,6 +458,37 @@ var FetchBrainClient = class {
|
|
|
424
458
|
return null;
|
|
425
459
|
}
|
|
426
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* Ask a natural-language question against learned knowledge
|
|
463
|
+
*/
|
|
464
|
+
async ask(question, opts) {
|
|
465
|
+
if (this.circuitBreaker.isOpen()) {
|
|
466
|
+
return { sources: [], status: "unavailable" };
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
const response = await this.makeRequest(
|
|
470
|
+
"/v1/ask",
|
|
471
|
+
{
|
|
472
|
+
method: "POST",
|
|
473
|
+
body: JSON.stringify({
|
|
474
|
+
query: question,
|
|
475
|
+
answer: opts?.answer,
|
|
476
|
+
limit: opts?.limit
|
|
477
|
+
})
|
|
478
|
+
},
|
|
479
|
+
ASK_TIMEOUT
|
|
480
|
+
);
|
|
481
|
+
this.circuitBreaker.recordSuccess();
|
|
482
|
+
return response;
|
|
483
|
+
} catch (error) {
|
|
484
|
+
const isClientError = error instanceof ApiError && error.status >= 400 && error.status < 500;
|
|
485
|
+
if (!isClientError) {
|
|
486
|
+
this.circuitBreaker.recordFailure();
|
|
487
|
+
}
|
|
488
|
+
this.logger.debug("Ask request failed:", error);
|
|
489
|
+
return { sources: [], status: "unavailable" };
|
|
490
|
+
}
|
|
491
|
+
}
|
|
427
492
|
/**
|
|
428
493
|
* Execute a batch query against the API
|
|
429
494
|
*/
|
|
@@ -431,19 +496,20 @@ var FetchBrainClient = class {
|
|
|
431
496
|
const results = /* @__PURE__ */ new Map();
|
|
432
497
|
const request = {
|
|
433
498
|
items,
|
|
434
|
-
|
|
499
|
+
memory: this.config.memory
|
|
435
500
|
};
|
|
436
|
-
|
|
437
|
-
|
|
501
|
+
const platformBuildId = getPlatformBuildId();
|
|
502
|
+
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
503
|
+
request.build = platformBuildId;
|
|
438
504
|
}
|
|
439
505
|
try {
|
|
440
|
-
const response = await this.makeRequest("/v1/
|
|
506
|
+
const response = await this.makeRequest("/v1/recall", {
|
|
441
507
|
method: "POST",
|
|
442
508
|
body: JSON.stringify(request)
|
|
443
509
|
});
|
|
444
510
|
this.circuitBreaker.recordSuccess();
|
|
445
511
|
for (const item of response.known) {
|
|
446
|
-
results.set(item.ref, { known: true, data: item.data
|
|
512
|
+
results.set(item.ref, { known: true, data: item.data });
|
|
447
513
|
}
|
|
448
514
|
for (const ref of response.unknown) {
|
|
449
515
|
results.set(ref, { known: false });
|
|
@@ -496,14 +562,9 @@ var FetchBrainClient = class {
|
|
|
496
562
|
if (process.env.NODE_ENV) {
|
|
497
563
|
contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
|
|
498
564
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
if (process.env.APIFY_ACTOR_BUILD_ID) {
|
|
503
|
-
contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
|
|
504
|
-
}
|
|
505
|
-
if (process.env.APIFY_ACTOR_RUN_ID) {
|
|
506
|
-
contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
|
|
565
|
+
const nativeContext = buildNativeContext();
|
|
566
|
+
if (nativeContext) {
|
|
567
|
+
contextHeaders["X-FB-Context"] = nativeContext;
|
|
507
568
|
}
|
|
508
569
|
if (currentContext.crawler) {
|
|
509
570
|
contextHeaders["X-FB-Crawler"] = currentContext.crawler;
|
|
@@ -523,7 +584,7 @@ var FetchBrainClient = class {
|
|
|
523
584
|
signal: controller.signal
|
|
524
585
|
});
|
|
525
586
|
if (!response.ok) {
|
|
526
|
-
throw new
|
|
587
|
+
throw new ApiError(response.status, response.statusText);
|
|
527
588
|
}
|
|
528
589
|
return await response.json();
|
|
529
590
|
} finally {
|
|
@@ -736,7 +797,7 @@ var TelemetryBuffer = class {
|
|
|
736
797
|
|
|
737
798
|
// src/enhance.ts
|
|
738
799
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
739
|
-
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["
|
|
800
|
+
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
740
801
|
function buildRawRequest(request) {
|
|
741
802
|
const r = request;
|
|
742
803
|
let headers;
|
|
@@ -762,7 +823,7 @@ function warnDefaultUniqueKey(request, logger, warned) {
|
|
|
762
823
|
const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
|
|
763
824
|
if (method !== "GET" && isDefault && !warned.has(request.url)) {
|
|
764
825
|
warned.add(request.url);
|
|
765
|
-
logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't
|
|
826
|
+
logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't get their own memory.`);
|
|
766
827
|
}
|
|
767
828
|
}
|
|
768
829
|
var asyncContext = new AsyncLocalStorage();
|
|
@@ -786,14 +847,13 @@ var FetchBrain = class {
|
|
|
786
847
|
this.logger = createLogger(config.debug ? "debug" : "info", true);
|
|
787
848
|
}
|
|
788
849
|
/**
|
|
789
|
-
*
|
|
850
|
+
* Recall whether FetchBrain "knows" a URL
|
|
790
851
|
*/
|
|
791
|
-
async
|
|
792
|
-
const result = await this.client.
|
|
852
|
+
async recall(options) {
|
|
853
|
+
const result = await this.client.recall({ url: options.url });
|
|
793
854
|
return {
|
|
794
855
|
known: result.known,
|
|
795
|
-
data: result.data
|
|
796
|
-
confidence: result.confidence
|
|
856
|
+
data: result.data
|
|
797
857
|
};
|
|
798
858
|
}
|
|
799
859
|
/**
|
|
@@ -812,8 +872,8 @@ var FetchBrain = class {
|
|
|
812
872
|
* Enhance a Crawlee crawler with FetchBrain optimization
|
|
813
873
|
*
|
|
814
874
|
* This wraps the crawler's request handler to:
|
|
815
|
-
* 1.
|
|
816
|
-
* 2. Teach
|
|
875
|
+
* 1. Recall the brain before making requests (brain knows = skip request)
|
|
876
|
+
* 2. Teach the brain after successful requests (learning)
|
|
817
877
|
*
|
|
818
878
|
* @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
|
|
819
879
|
* @param config - FetchBrain configuration
|
|
@@ -822,11 +882,12 @@ var FetchBrain = class {
|
|
|
822
882
|
static enhance(crawler, config) {
|
|
823
883
|
const client = new FetchBrainClient(config);
|
|
824
884
|
const logger = createLogger(config.debug ? "debug" : "info", true);
|
|
885
|
+
const telemetryConfig = config.telemetry ?? { enabled: false };
|
|
825
886
|
const telemetryBuffer = new TelemetryBuffer({
|
|
826
887
|
maxSize: 50,
|
|
827
888
|
flushInterval: 3e4,
|
|
828
889
|
onFlush: async (entries) => {
|
|
829
|
-
if (
|
|
890
|
+
if (telemetryConfig.enabled) {
|
|
830
891
|
await client.sendTelemetry(entries);
|
|
831
892
|
logger.debug(`Telemetry: sent ${entries.length} entries`);
|
|
832
893
|
}
|
|
@@ -834,9 +895,9 @@ var FetchBrain = class {
|
|
|
834
895
|
});
|
|
835
896
|
const runStats = {
|
|
836
897
|
totalRequests: 0,
|
|
837
|
-
|
|
898
|
+
recalled: 0,
|
|
838
899
|
aiSkipped: 0,
|
|
839
|
-
//
|
|
900
|
+
// brain knew + skipped scraping
|
|
840
901
|
learned: 0,
|
|
841
902
|
scraped: 0,
|
|
842
903
|
// Actually ran handler
|
|
@@ -863,36 +924,31 @@ var FetchBrain = class {
|
|
|
863
924
|
const rawRequest = buildRawRequest(request);
|
|
864
925
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
865
926
|
try {
|
|
866
|
-
const aiResult = await client.
|
|
927
|
+
const aiResult = await client.recall(rawRequest);
|
|
867
928
|
let usedAIData = false;
|
|
868
929
|
const originalPushData = context.pushData;
|
|
869
|
-
context.
|
|
930
|
+
context.brain = {
|
|
870
931
|
known: aiResult.known,
|
|
871
932
|
data: aiResult.data,
|
|
872
|
-
|
|
873
|
-
useAIData: async () => {
|
|
933
|
+
use: async () => {
|
|
874
934
|
if (aiResult.known && aiResult.data && originalPushData) {
|
|
875
935
|
usedAIData = true;
|
|
876
936
|
await originalPushData.call(context, aiResult.data);
|
|
877
|
-
logger.info(
|
|
878
|
-
`Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
879
|
-
);
|
|
937
|
+
logger.info(`Used brain data: ${url}`);
|
|
880
938
|
}
|
|
881
939
|
}
|
|
882
940
|
};
|
|
883
941
|
request.userData = {
|
|
884
942
|
...request.userData,
|
|
885
|
-
|
|
943
|
+
fetchBrainRecalled: aiResult.known,
|
|
886
944
|
fetchBrainData: aiResult.data
|
|
887
945
|
};
|
|
888
946
|
const handlerLabel = request.label;
|
|
889
947
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
890
948
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
891
|
-
runStats.
|
|
949
|
+
runStats.recalled++;
|
|
892
950
|
runStats.aiSkipped++;
|
|
893
|
-
logger.info(
|
|
894
|
-
`AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
895
|
-
);
|
|
951
|
+
logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
|
|
896
952
|
if (originalPushData) {
|
|
897
953
|
await originalPushData.call(context, aiResult.data);
|
|
898
954
|
}
|
|
@@ -900,9 +956,9 @@ var FetchBrain = class {
|
|
|
900
956
|
}
|
|
901
957
|
runStats.scraped++;
|
|
902
958
|
if (aiResult.known) {
|
|
903
|
-
runStats.
|
|
959
|
+
runStats.recalled++;
|
|
904
960
|
logger.info(
|
|
905
|
-
`Running handler [${handlerLabel || "default"}] with
|
|
961
|
+
`Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
|
|
906
962
|
);
|
|
907
963
|
} else {
|
|
908
964
|
logger.debug(`Learning: ${url}`);
|
|
@@ -926,7 +982,7 @@ var FetchBrain = class {
|
|
|
926
982
|
await asyncContext.run(requestContext, async () => {
|
|
927
983
|
await originalHandler.call(crawler, context);
|
|
928
984
|
});
|
|
929
|
-
if (
|
|
985
|
+
if (telemetryConfig.enabled) {
|
|
930
986
|
try {
|
|
931
987
|
const telemetry = await collectTelemetry(
|
|
932
988
|
{
|
|
@@ -958,7 +1014,7 @@ var FetchBrain = class {
|
|
|
958
1014
|
responseTime: Date.now() - startTime,
|
|
959
1015
|
contentSize: context.response?.body?.length
|
|
960
1016
|
},
|
|
961
|
-
|
|
1017
|
+
telemetryConfig
|
|
962
1018
|
);
|
|
963
1019
|
if (telemetry) {
|
|
964
1020
|
telemetryBuffer.add(telemetry);
|
|
@@ -968,7 +1024,7 @@ var FetchBrain = class {
|
|
|
968
1024
|
}
|
|
969
1025
|
}
|
|
970
1026
|
} catch (err) {
|
|
971
|
-
if (
|
|
1027
|
+
if (telemetryConfig.enabled) {
|
|
972
1028
|
try {
|
|
973
1029
|
const telemetry = await collectTelemetry(
|
|
974
1030
|
{
|
|
@@ -986,7 +1042,7 @@ var FetchBrain = class {
|
|
|
986
1042
|
endTime: Date.now(),
|
|
987
1043
|
responseTime: Date.now() - startTime
|
|
988
1044
|
},
|
|
989
|
-
|
|
1045
|
+
telemetryConfig,
|
|
990
1046
|
err instanceof Error ? err : new Error(String(err))
|
|
991
1047
|
);
|
|
992
1048
|
if (telemetry) {
|
|
@@ -1017,7 +1073,7 @@ var FetchBrain = class {
|
|
|
1017
1073
|
} finally {
|
|
1018
1074
|
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1019
1075
|
await client.flushLearnBatch();
|
|
1020
|
-
if (
|
|
1076
|
+
if (telemetryConfig.enabled) {
|
|
1021
1077
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
1022
1078
|
await telemetryBuffer.stop();
|
|
1023
1079
|
}
|
|
@@ -1026,7 +1082,7 @@ var FetchBrain = class {
|
|
|
1026
1082
|
);
|
|
1027
1083
|
const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
|
|
1028
1084
|
logger.info(
|
|
1029
|
-
|
|
1085
|
+
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
|
|
1030
1086
|
);
|
|
1031
1087
|
}
|
|
1032
1088
|
};
|
|
@@ -1053,15 +1109,6 @@ async function pushData(data, dataset, datasetName) {
|
|
|
1053
1109
|
}
|
|
1054
1110
|
}
|
|
1055
1111
|
|
|
1056
|
-
|
|
1057
|
-
var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
|
|
1058
|
-
AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
|
|
1059
|
-
AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
|
|
1060
|
-
AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
|
|
1061
|
-
AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
|
|
1062
|
-
return AIMemoryDepth2;
|
|
1063
|
-
})(AIMemoryDepth || {});
|
|
1064
|
-
|
|
1065
|
-
export { AIMemoryDepth, CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
|
|
1112
|
+
export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
|
|
1066
1113
|
//# sourceMappingURL=index.mjs.map
|
|
1067
1114
|
//# sourceMappingURL=index.mjs.map
|