@fetchbrain.com/sdk 0.5.1 → 0.7.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/dist/index.js CHANGED
@@ -99,6 +99,8 @@ var CircuitBreaker = class {
99
99
  };
100
100
 
101
101
  // src/batch.ts
102
+ var MAX_CONCURRENT_LEARN_FLUSHES = 3;
103
+ var MAX_QUEUED_LEARNS = 500;
102
104
  var DEFAULT_CONFIG2 = {
103
105
  maxSize: 50,
104
106
  maxWait: 50
@@ -180,6 +182,14 @@ var LearnBatcher = class {
180
182
  constructor(executor, config = {}, logger) {
181
183
  this.queue = [];
182
184
  this.flushTimeout = null;
185
+ /** Flushes whose API call has not settled yet (awaited by forceFlush). */
186
+ this.inFlight = /* @__PURE__ */ new Set();
187
+ /**
188
+ * Callers of waitForRoom(), oldest first. A settling flush wakes only as many
189
+ * as there are free backlog slots: waking all of them would tell each one
190
+ * "room" when only some fit, and the rest would then be dropped.
191
+ */
192
+ this.roomWaiters = [];
183
193
  this.executor = executor;
184
194
  this.config = { ...DEFAULT_CONFIG2, ...config };
185
195
  this.logger = logger;
@@ -188,6 +198,10 @@ var LearnBatcher = class {
188
198
  * Add a learn entry to the batch queue
189
199
  */
190
200
  async learn(request, data) {
201
+ if (this.queue.length >= MAX_QUEUED_LEARNS) {
202
+ this.logger.debug("Learn backlog full; not learning this entry");
203
+ return { status: "rejected", learned: 0, errors: ["backlog_full"] };
204
+ }
191
205
  return new Promise((resolve, reject) => {
192
206
  this.queue.push({ entry: { request, data }, resolve, reject });
193
207
  if (this.queue.length >= this.config.maxSize) {
@@ -199,10 +213,60 @@ var LearnBatcher = class {
199
213
  }
200
214
  });
201
215
  }
216
+ /** True when another learn() would be dropped for lack of backlog room. */
217
+ isBacklogFull() {
218
+ return this.queue.length >= MAX_QUEUED_LEARNS;
219
+ }
202
220
  /**
203
- * Flush the current batch
221
+ * Wait until the backlog has room, at most `timeoutMs`. Resolves true when
222
+ * there is room. Bounded so a slow API slows the crawl but never stalls it.
204
223
  */
205
- async flush() {
224
+ async waitForRoom(timeoutMs) {
225
+ const deadline = Date.now() + timeoutMs;
226
+ while (this.isBacklogFull()) {
227
+ const remaining = deadline - Date.now();
228
+ if (remaining <= 0) return false;
229
+ await new Promise((resolve) => {
230
+ const wake = () => {
231
+ clearTimeout(timer);
232
+ resolve();
233
+ };
234
+ const timer = setTimeout(() => {
235
+ const i = this.roomWaiters.indexOf(wake);
236
+ if (i !== -1) this.roomWaiters.splice(i, 1);
237
+ resolve();
238
+ }, remaining);
239
+ this.roomWaiters.push(wake);
240
+ });
241
+ }
242
+ return true;
243
+ }
244
+ /**
245
+ * Start sending the next batch, unless MAX_CONCURRENT_LEARN_FLUSHES are
246
+ * already in flight — a settling flush starts the next one.
247
+ */
248
+ flush() {
249
+ if (this.inFlight.size >= MAX_CONCURRENT_LEARN_FLUSHES) {
250
+ if (this.flushTimeout) {
251
+ clearTimeout(this.flushTimeout);
252
+ this.flushTimeout = null;
253
+ }
254
+ return;
255
+ }
256
+ const run = this.flushOnce();
257
+ this.inFlight.add(run);
258
+ void run.finally(() => {
259
+ this.inFlight.delete(run);
260
+ if (this.queue.length >= this.config.maxSize) {
261
+ this.flush();
262
+ } else if (this.queue.length > 0 && !this.flushTimeout) {
263
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
264
+ }
265
+ const free = MAX_QUEUED_LEARNS - this.queue.length;
266
+ for (const wake of this.roomWaiters.splice(0, Math.max(0, free))) wake();
267
+ });
268
+ }
269
+ async flushOnce() {
206
270
  if (this.flushTimeout) {
207
271
  clearTimeout(this.flushTimeout);
208
272
  this.flushTimeout = null;
@@ -223,16 +287,14 @@ var LearnBatcher = class {
223
287
  r.reject(error);
224
288
  }
225
289
  }
226
- if (this.queue.length > 0) {
227
- this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
228
- }
229
290
  }
230
291
  /**
231
292
  * Force flush and wait for completion (for cleanup/shutdown)
232
293
  */
233
294
  async forceFlush() {
234
- if (this.queue.length > 0) {
235
- await this.flush();
295
+ while (this.queue.length > 0 || this.inFlight.size > 0) {
296
+ if (this.queue.length > 0) this.flush();
297
+ await Promise.allSettled([...this.inFlight]);
236
298
  }
237
299
  }
238
300
  /**
@@ -323,16 +385,38 @@ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
323
385
  var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
324
386
  var MAX_VALUE_LENGTH = 256;
325
387
  var MAX_HEADER_LENGTH = 2048;
326
- function buildNativeContext(env = process.env) {
388
+ var SCRAPER_NAME_VAR = "FETCHBRAIN_SCRAPER_ID";
389
+ var SCRAPER_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
390
+ function normalizeScraperName(raw) {
391
+ const name = raw?.trim().toLowerCase();
392
+ return name && SCRAPER_NAME.test(name) ? name : void 0;
393
+ }
394
+ function resolveScraperName(option, env = process.env) {
395
+ const rejected = [];
396
+ const candidates = [
397
+ ["option", option],
398
+ [SCRAPER_NAME_VAR, env[SCRAPER_NAME_VAR]]
399
+ ];
400
+ for (const [source, raw] of candidates) {
401
+ if (raw === void 0 || raw.trim() === "") continue;
402
+ const name = normalizeScraperName(raw);
403
+ if (name) return { name, rejected };
404
+ rejected.push(source);
405
+ }
406
+ return { rejected };
407
+ }
408
+ function buildNativeContext(env = process.env, scraper) {
327
409
  const context = {};
328
- const names = Object.keys(env).filter((name) => ALLOWED_NAME.test(name) && !DENYLIST.test(name)).sort();
329
- for (const name of names) {
330
- const value = env[name];
410
+ const name = normalizeScraperName(scraper);
411
+ if (name) context[SCRAPER_NAME_VAR] = name;
412
+ const names = Object.keys(env).filter((n) => n !== SCRAPER_NAME_VAR && ALLOWED_NAME.test(n) && !DENYLIST.test(n)).sort();
413
+ for (const varName of names) {
414
+ const value = env[varName];
331
415
  if (!value || value.length > MAX_VALUE_LENGTH) continue;
332
416
  if (CREDENTIAL_VALUE.test(value)) continue;
333
- const candidate = { ...context, [name]: value };
417
+ const candidate = { ...context, [varName]: value };
334
418
  if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
335
- context[name] = value;
419
+ context[varName] = value;
336
420
  }
337
421
  if (Object.keys(context).length === 0) return void 0;
338
422
  return JSON.stringify(context);
@@ -344,12 +428,17 @@ function getPlatformBuildId(env = process.env) {
344
428
 
345
429
  // src/client.ts
346
430
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
347
- var DEFAULT_TIMEOUT = 500;
431
+ var DEFAULT_TIMEOUT = 1500;
348
432
  var DEFAULT_LEARN_TIMEOUT = 5e3;
349
433
  var BULK_RECALL_TIMEOUT = 3e3;
350
- var MAX_BULK_ITEMS = 100;
434
+ var MAX_BULK_ITEMS = 90;
435
+ var KEY_REJECTED_PAUSE_MS = 6e4;
351
436
  var BULK_RECALL_CONCURRENCY = 5;
352
437
  var MAX_LEARN_ENTRIES = 50;
438
+ var MAX_LEARN_DATA_BYTES = 100 * 1024;
439
+ function isOutage(error) {
440
+ return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
441
+ }
353
442
  var ASK_TIMEOUT = 1e4;
354
443
  function clampBatch(batch, cap) {
355
444
  return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
@@ -387,6 +476,16 @@ var FetchBrainClient = class {
387
476
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
388
477
  */
389
478
  this.learnPausedUntil = 0;
479
+ /**
480
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
481
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
482
+ * a key used right after it is created can see a brief 401 while the key
483
+ * propagates, and that must not switch FetchBrain off for a whole run.
484
+ */
485
+ this.keyRejectedUntil = 0;
486
+ this.keyRejectedWarned = false;
487
+ /** The oversized-page warning is shown once per client, then logged at debug. */
488
+ this.warnedOversizeLearn = false;
390
489
  /** Warn about the learn cap once per pause, independent of the pause state. */
391
490
  this.learnCapWarnedUntil = 0;
392
491
  this.config = {
@@ -408,10 +507,18 @@ var FetchBrainClient = class {
408
507
  // enhance-only; stored so getConfig() round-trips
409
508
  preRecall: config.preRecall,
410
509
  // enhance-only; stored so getConfig() round-trips
411
- onRecalled: config.onRecalled
510
+ onRecalled: config.onRecalled,
412
511
  // enhance-only; stored so getConfig() round-trips
512
+ scraper: config.scraper
413
513
  };
414
514
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
515
+ const scraper = resolveScraperName(config.scraper);
516
+ this.scraperName = scraper.name;
517
+ for (const source of scraper.rejected) {
518
+ this.logger.warn(
519
+ `ignoring invalid scraper name from ${source === "option" ? "the scraper option" : source}; use 1-64 lowercase letters, digits, '.', '_' or '-', starting with a letter or digit. ` + (scraper.name ? `Using "${scraper.name}" instead.` : "This scraper uses the shared default memory.")
520
+ );
521
+ }
415
522
  this.circuitBreaker = new CircuitBreaker(
416
523
  this.config.circuitBreaker,
417
524
  this.logger
@@ -427,11 +534,35 @@ var FetchBrainClient = class {
427
534
  this.logger
428
535
  );
429
536
  }
537
+ /** True when recalls must not reach the API right now (crawl continues without). */
538
+ recallBlocked() {
539
+ return this.isKeyRejected() || this.circuitBreaker.isOpen();
540
+ }
541
+ isKeyRejected() {
542
+ return Date.now() < this.keyRejectedUntil;
543
+ }
544
+ /**
545
+ * React to a 4xx the API returned. These are not outages (they don't open the
546
+ * shared breaker). A 401 means the next calls would fail the same way, so all
547
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
548
+ * pause recalls locally: a locally refused handler-time recall fails a
549
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
550
+ */
551
+ noteRefusal(error) {
552
+ if (!(error instanceof ApiError) || error.status !== 401) return;
553
+ this.keyRejectedUntil = Date.now() + KEY_REJECTED_PAUSE_MS;
554
+ if (!this.keyRejectedWarned) {
555
+ this.keyRejectedWarned = true;
556
+ this.logger.warn(
557
+ "FetchBrain API key was rejected (401: invalid or revoked). FetchBrain pauses for 60s at a time while it is; the crawl continues without it."
558
+ );
559
+ }
560
+ }
430
561
  /**
431
562
  * Recall if FetchBrain "knows" a request
432
563
  */
433
564
  async recall(request) {
434
- if (this.circuitBreaker.isOpen()) {
565
+ if (this.recallBlocked()) {
435
566
  return { known: false, fallback: true };
436
567
  }
437
568
  try {
@@ -443,7 +574,7 @@ var FetchBrainClient = class {
443
574
  }
444
575
  /**
445
576
  * 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
577
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
447
578
  * failed chunk degrades to fallback results for its own items only.
448
579
  */
449
580
  async recallBulk(requests) {
@@ -457,7 +588,7 @@ var FetchBrainClient = class {
457
588
  while (next < chunks.length) {
458
589
  const idx = next++;
459
590
  const chunk = chunks[idx];
460
- if (this.circuitBreaker.isOpen()) {
591
+ if (this.recallBlocked()) {
461
592
  chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
462
593
  continue;
463
594
  }
@@ -482,11 +613,19 @@ var FetchBrainClient = class {
482
613
  if (!this.config.learning) {
483
614
  return { status: "rejected", learned: 0 };
484
615
  }
485
- if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
616
+ if (this.isKeyRejected() || Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
486
617
  return { status: "rejected", learned: 0 };
487
618
  }
619
+ const processed = this.extractForLearning(data);
620
+ if (JSON.stringify(processed).length > MAX_LEARN_DATA_BYTES) {
621
+ const message = `A page's data is over the ${MAX_LEARN_DATA_BYTES / 1024}KB learn limit, so it was not learned and will be fetched again on later runs. Use extractForLearning to keep only the fields you need.`;
622
+ if (this.warnedOversizeLearn) this.logger.debug(message);
623
+ else this.logger.warn(message);
624
+ this.warnedOversizeLearn = true;
625
+ return { status: "rejected", learned: 0, errors: ["too_large"] };
626
+ }
488
627
  try {
489
- return await this.learnBatcher.learn(request, data);
628
+ return await this.learnBatcher.learn(request, processed);
490
629
  } catch (error) {
491
630
  if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
492
631
  return { status: "rejected", learned: 0 };
@@ -509,7 +648,7 @@ var FetchBrainClient = class {
509
648
  this.circuitBreaker.recordSuccess();
510
649
  return response;
511
650
  } catch (error) {
512
- this.circuitBreaker.recordFailure();
651
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
513
652
  this.logger.warn("Stats request failed:", error);
514
653
  return null;
515
654
  }
@@ -592,19 +731,23 @@ var FetchBrainClient = class {
592
731
  }
593
732
  return results;
594
733
  } catch (error) {
595
- this.circuitBreaker.recordFailure();
734
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
735
+ else this.noteRefusal(error);
596
736
  throw error;
597
737
  }
598
738
  }
739
+ /** Apply the user's extractForLearning hook to each learned record. */
740
+ extractForLearning(data) {
741
+ const extract = this.config.extractForLearning;
742
+ if (!extract) return data;
743
+ return Array.isArray(data) ? data.map((d) => extract(d)) : extract(data);
744
+ }
599
745
  /**
600
746
  * Execute a batch learn against the API
601
747
  */
602
748
  async executeBatchLearn(entries) {
603
- const processed = entries.map((e) => ({
604
- request: e.request,
605
- data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
606
- }));
607
- const request = { entries: processed };
749
+ if (entries.length === 0) return { status: "rejected", learned: 0 };
750
+ const request = { entries };
608
751
  const platformBuildId = getPlatformBuildId();
609
752
  if (this.config.refreshOnRebuild && platformBuildId) {
610
753
  request.build = platformBuildId;
@@ -622,6 +765,7 @@ var FetchBrainClient = class {
622
765
  return response;
623
766
  } catch (error) {
624
767
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
768
+ this.noteRefusal(error);
625
769
  if (error.code === "LEARN_CAP_EXCEEDED") {
626
770
  const now = /* @__PURE__ */ new Date();
627
771
  const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
@@ -661,7 +805,7 @@ var FetchBrainClient = class {
661
805
  if (process.env.NODE_ENV) {
662
806
  contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
663
807
  }
664
- const nativeContext = buildNativeContext();
808
+ const nativeContext = buildNativeContext(process.env, this.scraperName);
665
809
  if (nativeContext) {
666
810
  contextHeaders["X-FB-Context"] = nativeContext;
667
811
  }
@@ -733,6 +877,13 @@ var FetchBrainClient = class {
733
877
  /**
734
878
  * Flush pending learn requests (call before shutdown)
735
879
  */
880
+ /**
881
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
882
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
883
+ */
884
+ async waitForLearnRoom(timeoutMs) {
885
+ return this.learnBatcher.waitForRoom(timeoutMs);
886
+ }
736
887
  async flushLearnBatch() {
737
888
  await this.learnBatcher.forceFlush();
738
889
  }
@@ -897,6 +1048,7 @@ var TelemetryBuffer = class {
897
1048
  this.flushTimer = setInterval(() => {
898
1049
  this.flush();
899
1050
  }, this.flushInterval);
1051
+ this.flushTimer.unref?.();
900
1052
  }
901
1053
  /**
902
1054
  * Stop the flush timer and flush remaining entries
@@ -913,6 +1065,16 @@ var TelemetryBuffer = class {
913
1065
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
914
1066
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
915
1067
  var MAX_STASH_ENTRIES = 5e3;
1068
+ var MAX_STASH_BYTES = 256 * 1024 * 1024;
1069
+ var stashBytesCap = MAX_STASH_BYTES;
1070
+ var PRE_RECALL_SLICE = 500;
1071
+ var PRE_RECALL_STASH_WAIT_MS = 3e4;
1072
+ var LEARN_ROOM_WAIT_MS = 5e3;
1073
+ function isIterableInputRejection(err) {
1074
+ if (err instanceof TypeError) return true;
1075
+ const message = err instanceof Error ? err.message : String(err);
1076
+ return /iterable|\barray\b/i.test(message);
1077
+ }
916
1078
  function buildRawRequest(request) {
917
1079
  const r = request;
918
1080
  let headers;
@@ -1022,6 +1184,7 @@ var FetchBrain = class {
1022
1184
  // enqueue-time fetch skipped, but remembered data gone by execution
1023
1185
  startTime: 0
1024
1186
  };
1187
+ const pendingLearns = /* @__PURE__ */ new Set();
1025
1188
  const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
1026
1189
  if (!originalHandler) {
1027
1190
  logger.warn("No request handler found on crawler, returning unmodified");
@@ -1030,26 +1193,40 @@ var FetchBrain = class {
1030
1193
  const crawlerType = crawler.constructor?.name || "Unknown";
1031
1194
  const warnedKeys = /* @__PURE__ */ new Set();
1032
1195
  const preRecalledData = /* @__PURE__ */ new Map();
1196
+ let stashBytes = 0;
1197
+ let crawlStarted = false;
1198
+ const stashDelete = (key) => {
1199
+ const entry = preRecalledData.get(key);
1200
+ if (!entry) return false;
1201
+ preRecalledData.delete(key);
1202
+ stashBytes -= entry.bytes;
1203
+ return true;
1204
+ };
1033
1205
  const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
1034
1206
  const stashSet = (key, data) => {
1035
- if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
1207
+ const reStash = stashDelete(key);
1208
+ const bytes = JSON.stringify(data).length;
1209
+ while (preRecalledData.size > 0 && (!reStash && preRecalledData.size >= MAX_STASH_ENTRIES || stashBytes + bytes > stashBytesCap)) {
1036
1210
  const oldest = preRecalledData.keys().next().value;
1037
- if (oldest !== void 0) preRecalledData.delete(oldest);
1211
+ if (oldest === void 0) break;
1212
+ stashDelete(oldest);
1038
1213
  }
1039
- preRecalledData.set(key, data);
1214
+ preRecalledData.set(key, { data, bytes });
1215
+ stashBytes += bytes;
1040
1216
  };
1041
1217
  const stashTake = (r) => {
1042
1218
  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;
1219
+ const entry = preRecalledData.get(key);
1220
+ if (entry) {
1221
+ stashDelete(key);
1222
+ return entry.data;
1047
1223
  }
1048
1224
  }
1049
1225
  return void 0;
1050
1226
  };
1051
1227
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
1052
1228
  const wrappedHandler = async (context) => {
1229
+ crawlStarted = true;
1053
1230
  const { request } = context;
1054
1231
  const url = request.url;
1055
1232
  const label = request.label;
@@ -1150,12 +1327,11 @@ var FetchBrain = class {
1150
1327
  } else {
1151
1328
  logger.debug(`Learning: ${url}`);
1152
1329
  }
1330
+ const learnItems = [];
1153
1331
  if (originalPushData && config.learning !== false) {
1154
1332
  context.pushData = async (data) => {
1155
- const shouldLearn = !usedAIData && !aiResult.known;
1156
- if (shouldLearn) {
1157
- runStats.learned++;
1158
- await client.learn(rawRequest, data);
1333
+ if (!usedAIData && !aiResult.known) {
1334
+ learnItems.push(...Array.isArray(data) ? data : [data]);
1159
1335
  }
1160
1336
  return originalPushData.call(context, data);
1161
1337
  };
@@ -1164,11 +1340,20 @@ var FetchBrain = class {
1164
1340
  request: rawRequest,
1165
1341
  client,
1166
1342
  learning: config.learning !== false,
1167
- aiKnown: aiResult.known
1343
+ aiKnown: aiResult.known,
1344
+ items: learnItems
1168
1345
  };
1169
1346
  await asyncContext.run(requestContext, async () => {
1170
1347
  await originalHandler.call(crawler, context);
1171
1348
  });
1349
+ if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
1350
+ await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
1351
+ const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
1352
+ if (res.status !== "rejected") runStats.learned += learnItems.length;
1353
+ }).catch((learnErr) => logger.debug(`Learn failed: ${learnErr}`));
1354
+ pendingLearns.add(pending);
1355
+ void pending.finally(() => pendingLearns.delete(pending));
1356
+ }
1172
1357
  if (telemetryConfig.enabled) {
1173
1358
  try {
1174
1359
  const telemetry = await collectTelemetry(
@@ -1263,6 +1448,7 @@ var FetchBrain = class {
1263
1448
  } finally {
1264
1449
  logger.debug("Flushing pending learn requests on crawl complete");
1265
1450
  await client.flushLearnBatch();
1451
+ await Promise.allSettled([...pendingLearns]);
1266
1452
  if (telemetryConfig.enabled) {
1267
1453
  logger.debug("Telemetry: flushing on crawl complete");
1268
1454
  await telemetryBuffer.stop();
@@ -1285,24 +1471,11 @@ var FetchBrain = class {
1285
1471
  "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
1472
  );
1287
1473
  }
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
- });
1474
+ const preRecallSlice = async (slice, retryOnBlocked) => {
1302
1475
  try {
1303
1476
  const candidateIdx = [];
1304
- for (let i = 0; i < batch.length; i++) {
1305
- const r = batch[i];
1477
+ for (let i = 0; i < slice.length; i++) {
1478
+ const r = slice[i];
1306
1479
  if (!r || typeof r.url !== "string") continue;
1307
1480
  const prior = r.userData?.__fetchBrainResult;
1308
1481
  if (prior) {
@@ -1318,14 +1491,14 @@ var FetchBrain = class {
1318
1491
  }
1319
1492
  if (candidateIdx.length > 0) {
1320
1493
  const rawRequests = candidateIdx.map(
1321
- (i) => buildRawRequest(batch[i])
1494
+ (i) => buildRawRequest(slice[i])
1322
1495
  );
1323
1496
  const results = await client.recallBulk(rawRequests);
1324
1497
  let known = 0;
1325
1498
  candidateIdx.forEach((reqIdx, j) => {
1326
1499
  const result = results[j];
1327
1500
  if (!result || result.fallback) return;
1328
- const r = batch[reqIdx];
1501
+ const r = slice[reqIdx];
1329
1502
  if (result.known && result.data) {
1330
1503
  r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
1331
1504
  stashSet(stashKey(rawRequests[j]), result.data);
@@ -1344,7 +1517,62 @@ var FetchBrain = class {
1344
1517
  } catch (err) {
1345
1518
  logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
1346
1519
  }
1347
- return originalAddRequests(batch, options);
1520
+ };
1521
+ const waitForStashRoom = async (needed, state) => {
1522
+ if (!crawlStarted) return;
1523
+ const deadline = Date.now() + PRE_RECALL_STASH_WAIT_MS;
1524
+ const hasRoom = () => preRecalledData.size + needed <= MAX_STASH_ENTRIES && stashBytes < stashBytesCap;
1525
+ while (!state.gaveUp && !hasRoom()) {
1526
+ if (Date.now() >= deadline) {
1527
+ state.gaveUp = true;
1528
+ logger.debug("preRecall: stash still full after waiting; continuing (oldest payloads may be evicted)");
1529
+ return;
1530
+ }
1531
+ await new Promise((r) => setTimeout(r, 50));
1532
+ }
1533
+ };
1534
+ crawlerAny.addRequests = async (requests, options) => {
1535
+ if (!Array.isArray(requests) || requests.length === 0) {
1536
+ return originalAddRequests(requests, options);
1537
+ }
1538
+ const retryOnBlocked = Boolean(
1539
+ crawlerAny.retryOnBlocked
1540
+ );
1541
+ const batch = requests.map((r) => {
1542
+ if (typeof r === "string") return { url: r };
1543
+ if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1544
+ return { ...r };
1545
+ }
1546
+ return r;
1547
+ });
1548
+ if (batch.length <= PRE_RECALL_SLICE) {
1549
+ await preRecallSlice(batch, retryOnBlocked);
1550
+ return originalAddRequests(batch, options);
1551
+ }
1552
+ const state = { gaveUp: false };
1553
+ let started = false;
1554
+ async function* lazilyRecalled() {
1555
+ started = true;
1556
+ for (let i = 0; i < batch.length; i += PRE_RECALL_SLICE) {
1557
+ const slice = batch.slice(i, i + PRE_RECALL_SLICE);
1558
+ await waitForStashRoom(slice.length, state);
1559
+ await preRecallSlice(slice, retryOnBlocked);
1560
+ yield* slice;
1561
+ }
1562
+ }
1563
+ try {
1564
+ return await originalAddRequests(lazilyRecalled(), options);
1565
+ } catch (err) {
1566
+ if (started || !isIterableInputRejection(err)) throw err;
1567
+ logger.debug(
1568
+ "preRecall: this Crawlee version does not accept lazy request lists; pre-recalling eagerly"
1569
+ );
1570
+ const eager = batch.slice(0, MAX_STASH_ENTRIES);
1571
+ for (let i = 0; i < eager.length && stashBytes < stashBytesCap; i += PRE_RECALL_SLICE) {
1572
+ await preRecallSlice(eager.slice(i, i + PRE_RECALL_SLICE), retryOnBlocked);
1573
+ }
1574
+ return originalAddRequests(batch, options);
1575
+ }
1348
1576
  };
1349
1577
  }
1350
1578
  return Object.assign(crawler, { fetchBrain: client });
@@ -1356,10 +1584,7 @@ function createFetchBrain(config) {
1356
1584
  async function pushData(data, dataset, datasetName) {
1357
1585
  const ctx = getCurrentContext();
1358
1586
  if (ctx && ctx.learning && !ctx.aiKnown) {
1359
- const items = Array.isArray(data) ? data : [data];
1360
- for (const item of items) {
1361
- await ctx.client.learn(ctx.request, item);
1362
- }
1587
+ ctx.items.push(...Array.isArray(data) ? data : [data]);
1363
1588
  }
1364
1589
  if (datasetName && dataset.open) {
1365
1590
  const namedDataset = await dataset.open(datasetName);