@fetchbrain.com/sdk 0.4.0 → 0.5.1

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.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-D8djjVGS.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-D8djjVGS.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.mjs';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -15,13 +15,22 @@ declare class FetchBrainClient {
15
15
  private batcher;
16
16
  private learnBatcher;
17
17
  private logger;
18
+ /**
19
+ * Epoch ms until which learns are paused after the API reported the monthly
20
+ * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
+ */
22
+ private learnPausedUntil;
23
+ /** Warn about the learn cap once per pause, independent of the pause state. */
24
+ private learnCapWarnedUntil;
18
25
  constructor(config: FetchBrainConfig);
19
26
  /**
20
27
  * Recall if FetchBrain "knows" a request
21
28
  */
22
29
  recall(request: RawRequest): Promise<RecallResult>;
23
30
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
31
+ * Recall multiple requests at once — returns ordered array matching input order.
32
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
33
+ * failed chunk degrades to fallback results for its own items only.
25
34
  */
26
35
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
36
  /**
@@ -33,7 +42,7 @@ declare class FetchBrainClient {
33
42
  */
34
43
  stats(): Promise<StatsResponse | null>;
35
44
  /**
36
- * Ask a natural-language question against learned knowledge
45
+ * Ask a natural-language question, answered from everything the account has learned
37
46
  *
38
47
  * `model` picks the generation model for answer mode from the server's
39
48
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
@@ -125,7 +134,7 @@ interface FetchBrainContext {
125
134
  * FetchBrain main class
126
135
  *
127
136
  * Provides the static enhance() method to wrap Crawlee crawlers
128
- * with AI-powered optimization
137
+ * with brain recall and learning
129
138
  */
130
139
  declare class FetchBrain {
131
140
  private client;
@@ -179,9 +188,9 @@ interface DatasetLike {
179
188
  open?: (name?: string | null) => Promise<DatasetLike>;
180
189
  }
181
190
  /**
182
- * AI-aware pushData wrapper
191
+ * Learning-aware pushData wrapper
183
192
  *
184
- * Use this instead of Dataset.pushData() for automatic AI learning.
193
+ * Use this instead of Dataset.pushData() so the brain learns from what you push.
185
194
  * Works with both static Dataset class and dataset instances.
186
195
  *
187
196
  * @example
@@ -293,8 +302,9 @@ declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
293
302
  /**
294
303
  * Telemetry Collection Module
295
304
  *
296
- * Collects anonymized performance and behavior data from Crawlee contexts.
297
- * All data is sanitized - no PII, credentials, or raw content is ever collected.
305
+ * Collects opt-in, pseudonymous performance and behavior data from Crawlee contexts
306
+ * (sent with the API key, so linked to the account). Raw URLs, bodies, proxy URLs/IPs
307
+ * and error messages are not collected; hostname, path pattern and label are.
298
308
  */
299
309
 
300
310
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-D8djjVGS.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-D8djjVGS.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.js';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -15,13 +15,22 @@ declare class FetchBrainClient {
15
15
  private batcher;
16
16
  private learnBatcher;
17
17
  private logger;
18
+ /**
19
+ * Epoch ms until which learns are paused after the API reported the monthly
20
+ * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
+ */
22
+ private learnPausedUntil;
23
+ /** Warn about the learn cap once per pause, independent of the pause state. */
24
+ private learnCapWarnedUntil;
18
25
  constructor(config: FetchBrainConfig);
19
26
  /**
20
27
  * Recall if FetchBrain "knows" a request
21
28
  */
22
29
  recall(request: RawRequest): Promise<RecallResult>;
23
30
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
31
+ * Recall multiple requests at once — returns ordered array matching input order.
32
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
33
+ * failed chunk degrades to fallback results for its own items only.
25
34
  */
26
35
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
36
  /**
@@ -33,7 +42,7 @@ declare class FetchBrainClient {
33
42
  */
34
43
  stats(): Promise<StatsResponse | null>;
35
44
  /**
36
- * Ask a natural-language question against learned knowledge
45
+ * Ask a natural-language question, answered from everything the account has learned
37
46
  *
38
47
  * `model` picks the generation model for answer mode from the server's
39
48
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
@@ -125,7 +134,7 @@ interface FetchBrainContext {
125
134
  * FetchBrain main class
126
135
  *
127
136
  * Provides the static enhance() method to wrap Crawlee crawlers
128
- * with AI-powered optimization
137
+ * with brain recall and learning
129
138
  */
130
139
  declare class FetchBrain {
131
140
  private client;
@@ -179,9 +188,9 @@ interface DatasetLike {
179
188
  open?: (name?: string | null) => Promise<DatasetLike>;
180
189
  }
181
190
  /**
182
- * AI-aware pushData wrapper
191
+ * Learning-aware pushData wrapper
183
192
  *
184
- * Use this instead of Dataset.pushData() for automatic AI learning.
193
+ * Use this instead of Dataset.pushData() so the brain learns from what you push.
185
194
  * Works with both static Dataset class and dataset instances.
186
195
  *
187
196
  * @example
@@ -293,8 +302,9 @@ declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
293
302
  /**
294
303
  * Telemetry Collection Module
295
304
  *
296
- * Collects anonymized performance and behavior data from Crawlee contexts.
297
- * All data is sanitized - no PII, credentials, or raw content is ever collected.
305
+ * Collects opt-in, pseudonymous performance and behavior data from Crawlee contexts
306
+ * (sent with the API key, so linked to the account). Raw URLs, bodies, proxy URLs/IPs
307
+ * and error messages are not collected; hostname, path pattern and label are.
298
308
  */
299
309
 
300
310
  /**
package/dist/index.js CHANGED
@@ -346,15 +346,33 @@ function getPlatformBuildId(env = process.env) {
346
346
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
347
347
  var DEFAULT_TIMEOUT = 500;
348
348
  var DEFAULT_LEARN_TIMEOUT = 5e3;
349
+ var BULK_RECALL_TIMEOUT = 3e3;
350
+ var MAX_BULK_ITEMS = 100;
351
+ var BULK_RECALL_CONCURRENCY = 5;
352
+ var MAX_LEARN_ENTRIES = 50;
349
353
  var ASK_TIMEOUT = 1e4;
354
+ function clampBatch(batch, cap) {
355
+ return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
356
+ }
350
357
  var ApiError = class extends Error {
351
- constructor(status, statusText, serverError) {
358
+ constructor(status, statusText, serverError, code, retryAfterSec) {
352
359
  super(`API error: ${status} ${statusText}`);
353
360
  this.status = status;
354
361
  this.serverError = serverError;
362
+ this.code = code;
363
+ this.retryAfterSec = retryAfterSec;
355
364
  this.name = "ApiError";
356
365
  }
357
366
  };
367
+ function parseRetryAfter(header) {
368
+ if (!header) return void 0;
369
+ const secs = Number(header);
370
+ if (Number.isFinite(secs)) return secs > 0 ? secs : void 0;
371
+ const at = Date.parse(header);
372
+ if (Number.isNaN(at)) return void 0;
373
+ const delta = (at - Date.now()) / 1e3;
374
+ return delta > 0 ? delta : void 0;
375
+ }
358
376
  var currentContext = {};
359
377
  function setScrapeContext(ctx) {
360
378
  currentContext = ctx;
@@ -364,6 +382,13 @@ function clearScrapeContext() {
364
382
  }
365
383
  var FetchBrainClient = class {
366
384
  constructor(config) {
385
+ /**
386
+ * Epoch ms until which learns are paused after the API reported the monthly
387
+ * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
388
+ */
389
+ this.learnPausedUntil = 0;
390
+ /** Warn about the learn cap once per pause, independent of the pause state. */
391
+ this.learnCapWarnedUntil = 0;
367
392
  this.config = {
368
393
  apiKey: config.apiKey,
369
394
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -379,7 +404,11 @@ var FetchBrainClient = class {
379
404
  // opt-in
380
405
  batch: config.batch,
381
406
  circuitBreaker: config.circuitBreaker,
382
- skipLabels: config.skipLabels
407
+ skipLabels: config.skipLabels,
408
+ // enhance-only; stored so getConfig() round-trips
409
+ preRecall: config.preRecall,
410
+ // enhance-only; stored so getConfig() round-trips
411
+ onRecalled: config.onRecalled
383
412
  // enhance-only; stored so getConfig() round-trips
384
413
  };
385
414
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
@@ -389,12 +418,12 @@ var FetchBrainClient = class {
389
418
  );
390
419
  this.batcher = new RequestBatcher(
391
420
  (items) => this.executeBatchQuery(items),
392
- this.config.batch,
421
+ clampBatch(this.config.batch, MAX_BULK_ITEMS),
393
422
  this.logger
394
423
  );
395
424
  this.learnBatcher = new LearnBatcher(
396
425
  (entries) => this.executeBatchLearn(entries),
397
- this.config.batch,
426
+ clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
398
427
  this.logger
399
428
  );
400
429
  }
@@ -413,19 +442,38 @@ var FetchBrainClient = class {
413
442
  }
414
443
  }
415
444
  /**
416
- * Recall multiple requests at once — returns ordered array matching input order
445
+ * Recall multiple requests at once — returns ordered array matching input order.
446
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
447
+ * failed chunk degrades to fallback results for its own items only.
417
448
  */
418
449
  async recallBulk(requests) {
419
- if (this.circuitBreaker.isOpen()) {
420
- return requests.map(() => ({ known: false, fallback: true }));
421
- }
422
- try {
423
- const items = requests.map((request, i) => ({ ref: String(i), request }));
424
- const results = await this.executeBatchQuery(items);
425
- return items.map((i) => results.get(i.ref) ?? { known: false });
426
- } catch {
427
- return requests.map(() => ({ known: false, fallback: true }));
450
+ const chunks = [];
451
+ for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
452
+ chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
428
453
  }
454
+ const chunkResults = new Array(chunks.length);
455
+ let next = 0;
456
+ const worker = async () => {
457
+ while (next < chunks.length) {
458
+ const idx = next++;
459
+ const chunk = chunks[idx];
460
+ if (this.circuitBreaker.isOpen()) {
461
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
462
+ continue;
463
+ }
464
+ try {
465
+ const items = chunk.map((request, i) => ({ ref: String(i), request }));
466
+ const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
467
+ chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
468
+ } catch {
469
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
470
+ }
471
+ }
472
+ };
473
+ await Promise.all(
474
+ Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
475
+ );
476
+ return chunkResults.flat();
429
477
  }
430
478
  /**
431
479
  * "Teach" FetchBrain new data (batched for high-concurrency)
@@ -434,12 +482,15 @@ var FetchBrainClient = class {
434
482
  if (!this.config.learning) {
435
483
  return { status: "rejected", learned: 0 };
436
484
  }
437
- if (this.circuitBreaker.isOpen()) {
485
+ if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
438
486
  return { status: "rejected", learned: 0 };
439
487
  }
440
488
  try {
441
489
  return await this.learnBatcher.learn(request, data);
442
490
  } catch (error) {
491
+ if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
492
+ return { status: "rejected", learned: 0 };
493
+ }
443
494
  this.logger.warn("Learn failed:", error);
444
495
  return { status: "rejected", learned: 0 };
445
496
  }
@@ -464,7 +515,7 @@ var FetchBrainClient = class {
464
515
  }
465
516
  }
466
517
  /**
467
- * Ask a natural-language question against learned knowledge
518
+ * Ask a natural-language question, answered from everything the account has learned
468
519
  *
469
520
  * `model` picks the generation model for answer mode from the server's
470
521
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
@@ -513,7 +564,7 @@ var FetchBrainClient = class {
513
564
  /**
514
565
  * Execute a batch query against the API
515
566
  */
516
- async executeBatchQuery(items) {
567
+ async executeBatchQuery(items, timeout) {
517
568
  const results = /* @__PURE__ */ new Map();
518
569
  const request = {
519
570
  items,
@@ -524,10 +575,14 @@ var FetchBrainClient = class {
524
575
  request.build = platformBuildId;
525
576
  }
526
577
  try {
527
- const response = await this.makeRequest("/v1/recall", {
528
- method: "POST",
529
- body: JSON.stringify(request)
530
- });
578
+ const response = await this.makeRequest(
579
+ "/v1/recall",
580
+ {
581
+ method: "POST",
582
+ body: JSON.stringify(request)
583
+ },
584
+ timeout
585
+ );
531
586
  this.circuitBreaker.recordSuccess();
532
587
  for (const item of response.known) {
533
588
  results.set(item.ref, { known: true, data: item.data });
@@ -566,6 +621,24 @@ var FetchBrainClient = class {
566
621
  this.circuitBreaker.recordSuccess();
567
622
  return response;
568
623
  } catch (error) {
624
+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
625
+ if (error.code === "LEARN_CAP_EXCEEDED") {
626
+ const now = /* @__PURE__ */ new Date();
627
+ const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
628
+ this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
629
+ if (this.learnCapWarnedUntil < monthStart) {
630
+ this.learnCapWarnedUntil = monthStart;
631
+ this.logger.warn(
632
+ "FetchBrain monthly learning limit reached \u2014 learning is paused until the 1st (UTC); recall keeps working."
633
+ );
634
+ }
635
+ } else if (error.status === 429) {
636
+ const waitMs = Math.min(Math.max(error.retryAfterSec ?? 30, 1), 3600) * 1e3;
637
+ this.learnPausedUntil = Math.max(this.learnPausedUntil, Date.now() + waitMs);
638
+ this.logger.debug(`Learn rate-limited; pausing learns for ${waitMs / 1e3}s`);
639
+ }
640
+ throw error;
641
+ }
569
642
  this.circuitBreaker.recordFailure();
570
643
  throw error;
571
644
  }
@@ -611,12 +684,21 @@ var FetchBrainClient = class {
611
684
  });
612
685
  if (!response.ok) {
613
686
  let serverError;
687
+ let code;
614
688
  try {
615
689
  const errBody = await response.json();
616
690
  if (typeof errBody.error === "string") serverError = errBody.error;
691
+ const specific = errBody.details?.code ?? errBody.code;
692
+ if (typeof specific === "string") code = specific;
617
693
  } catch {
618
694
  }
619
- throw new ApiError(response.status, response.statusText, serverError);
695
+ throw new ApiError(
696
+ response.status,
697
+ response.statusText,
698
+ serverError,
699
+ code,
700
+ parseRetryAfter(response.headers.get("Retry-After"))
701
+ );
620
702
  }
621
703
  return await response.json();
622
704
  } finally {
@@ -830,6 +912,7 @@ var TelemetryBuffer = class {
830
912
  // src/enhance.ts
831
913
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
832
914
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
915
+ var MAX_STASH_ENTRIES = 5e3;
833
916
  function buildRawRequest(request) {
834
917
  const r = request;
835
918
  let headers;
@@ -935,6 +1018,8 @@ var FetchBrain = class {
935
1018
  // Actually ran handler
936
1019
  bypassed: 0,
937
1020
  // skipLabels match — ran handler outside FetchBrain
1021
+ dropped: 0,
1022
+ // enqueue-time fetch skipped, but remembered data gone by execution
938
1023
  startTime: 0
939
1024
  };
940
1025
  const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
@@ -944,6 +1029,25 @@ var FetchBrain = class {
944
1029
  }
945
1030
  const crawlerType = crawler.constructor?.name || "Unknown";
946
1031
  const warnedKeys = /* @__PURE__ */ new Set();
1032
+ const preRecalledData = /* @__PURE__ */ new Map();
1033
+ const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
1034
+ const stashSet = (key, data) => {
1035
+ if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
1036
+ const oldest = preRecalledData.keys().next().value;
1037
+ if (oldest !== void 0) preRecalledData.delete(oldest);
1038
+ }
1039
+ preRecalledData.set(key, data);
1040
+ };
1041
+ const stashTake = (r) => {
1042
+ for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
1043
+ const data = preRecalledData.get(key);
1044
+ if (data) {
1045
+ preRecalledData.delete(key);
1046
+ return data;
1047
+ }
1048
+ }
1049
+ return void 0;
1050
+ };
947
1051
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
948
1052
  const wrappedHandler = async (context) => {
949
1053
  const { request } = context;
@@ -964,10 +1068,50 @@ var FetchBrain = class {
964
1068
  });
965
1069
  const rawRequest = buildRawRequest(request);
966
1070
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1071
+ let consumedStash;
967
1072
  try {
968
- const aiResult = await client.recall(rawRequest);
1073
+ const preRecalled = request.userData?.__fetchBrainResult;
1074
+ let aiResult;
1075
+ if (preRecalled?.known) {
1076
+ const stashedData = stashTake(rawRequest);
1077
+ if (stashedData) {
1078
+ consumedStash = stashedData;
1079
+ aiResult = { known: true, data: stashedData };
1080
+ } else {
1081
+ aiResult = await client.recall(rawRequest);
1082
+ }
1083
+ } else if (preRecalled) {
1084
+ aiResult = preRecalled;
1085
+ } else {
1086
+ aiResult = await client.recall(rawRequest);
1087
+ }
1088
+ if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1089
+ if (aiResult.fallback) {
1090
+ throw new Error(
1091
+ `FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1092
+ );
1093
+ }
1094
+ runStats.dropped++;
1095
+ request.noRetry = true;
1096
+ throw new Error(
1097
+ `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.`
1098
+ );
1099
+ }
969
1100
  let usedAIData = false;
970
1101
  const originalPushData = context.pushData;
1102
+ const fireOnRecalled = async (data) => {
1103
+ if (!config.onRecalled) return;
1104
+ try {
1105
+ await config.onRecalled({
1106
+ url,
1107
+ label: request.label,
1108
+ userData: rawRequest.userData,
1109
+ data
1110
+ });
1111
+ } catch (hookErr) {
1112
+ logger.debug(`onRecalled hook error: ${hookErr}`);
1113
+ }
1114
+ };
971
1115
  context.brain = {
972
1116
  known: aiResult.known,
973
1117
  data: aiResult.data,
@@ -976,6 +1120,7 @@ var FetchBrain = class {
976
1120
  usedAIData = true;
977
1121
  await originalPushData.call(context, aiResult.data);
978
1122
  logger.info(`Used brain data: ${url}`);
1123
+ await fireOnRecalled(aiResult.data);
979
1124
  }
980
1125
  }
981
1126
  };
@@ -993,6 +1138,7 @@ var FetchBrain = class {
993
1138
  if (originalPushData) {
994
1139
  await originalPushData.call(context, aiResult.data);
995
1140
  }
1141
+ await fireOnRecalled(aiResult.data);
996
1142
  return;
997
1143
  }
998
1144
  runStats.scraped++;
@@ -1065,6 +1211,9 @@ var FetchBrain = class {
1065
1211
  }
1066
1212
  }
1067
1213
  } catch (err) {
1214
+ if (consumedStash) {
1215
+ stashSet(stashKey(rawRequest), consumedStash);
1216
+ }
1068
1217
  if (telemetryConfig.enabled) {
1069
1218
  try {
1070
1219
  const telemetry = await collectTelemetry(
@@ -1124,11 +1273,80 @@ var FetchBrain = class {
1124
1273
  const managedRequests = runStats.totalRequests - runStats.bypassed;
1125
1274
  const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1126
1275
  logger.info(
1127
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + `, duration: ${duration}s`
1276
+ `\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`
1128
1277
  );
1129
1278
  }
1130
1279
  };
1131
1280
  }
1281
+ if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
1282
+ const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
1283
+ if (crawlerAny.retryOnBlocked) {
1284
+ logger.info(
1285
+ "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."
1286
+ );
1287
+ }
1288
+ crawlerAny.addRequests = async (requests, options) => {
1289
+ if (!Array.isArray(requests) || requests.length === 0) {
1290
+ return originalAddRequests(requests, options);
1291
+ }
1292
+ const retryOnBlocked = Boolean(
1293
+ crawlerAny.retryOnBlocked
1294
+ );
1295
+ const batch = requests.map((r) => {
1296
+ if (typeof r === "string") return { url: r };
1297
+ if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1298
+ return { ...r };
1299
+ }
1300
+ return r;
1301
+ });
1302
+ try {
1303
+ const candidateIdx = [];
1304
+ for (let i = 0; i < batch.length; i++) {
1305
+ const r = batch[i];
1306
+ if (!r || typeof r.url !== "string") continue;
1307
+ const prior = r.userData?.__fetchBrainResult;
1308
+ if (prior) {
1309
+ if (prior.known && r.skipNavigation) r.skipNavigation = false;
1310
+ const rest = { ...r.userData };
1311
+ delete rest.__fetchBrainResult;
1312
+ r.userData = rest;
1313
+ }
1314
+ if (r.skipNavigation) continue;
1315
+ if (skipLabels && skipLabels.has(r.label || "default")) continue;
1316
+ if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
1317
+ candidateIdx.push(i);
1318
+ }
1319
+ if (candidateIdx.length > 0) {
1320
+ const rawRequests = candidateIdx.map(
1321
+ (i) => buildRawRequest(batch[i])
1322
+ );
1323
+ const results = await client.recallBulk(rawRequests);
1324
+ let known = 0;
1325
+ candidateIdx.forEach((reqIdx, j) => {
1326
+ const result = results[j];
1327
+ if (!result || result.fallback) return;
1328
+ const r = batch[reqIdx];
1329
+ if (result.known && result.data) {
1330
+ r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
1331
+ stashSet(stashKey(rawRequests[j]), result.data);
1332
+ if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
1333
+ r.skipNavigation = true;
1334
+ known++;
1335
+ }
1336
+ } else {
1337
+ r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
1338
+ }
1339
+ });
1340
+ logger.debug(
1341
+ `Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
1342
+ );
1343
+ }
1344
+ } catch (err) {
1345
+ logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
1346
+ }
1347
+ return originalAddRequests(batch, options);
1348
+ };
1349
+ }
1132
1350
  return Object.assign(crawler, { fetchBrain: client });
1133
1351
  }
1134
1352
  };