@fetchbrain.com/sdk 0.1.7 → 0.2.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.mjs CHANGED
@@ -106,24 +106,23 @@ var RequestBatcher = class {
106
106
  constructor(executor, config = {}, logger) {
107
107
  this.queue = [];
108
108
  this.flushTimeout = null;
109
+ this.refSeq = 0;
109
110
  this.executor = executor;
110
111
  this.config = { ...DEFAULT_CONFIG2, ...config };
111
112
  this.logger = logger;
112
113
  }
113
114
  /**
114
- * Add a URL to the batch queue
115
+ * Add a request to the batch queue
115
116
  */
116
- async query(url) {
117
+ async query(request) {
117
118
  return new Promise((resolve, reject) => {
118
- this.queue.push({ url, resolve, reject });
119
+ this.queue.push({ ref: String(this.refSeq++), request, resolve, reject });
119
120
  if (this.queue.length >= this.config.maxSize) {
120
121
  this.flush();
121
122
  return;
122
123
  }
123
124
  if (!this.flushTimeout) {
124
- this.flushTimeout = setTimeout(() => {
125
- this.flush();
126
- }, this.config.maxWait);
125
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
127
126
  }
128
127
  });
129
128
  }
@@ -139,27 +138,20 @@ var RequestBatcher = class {
139
138
  return;
140
139
  }
141
140
  const batch = this.queue.splice(0, this.config.maxSize);
142
- const urls = batch.map((r) => r.url);
143
- this.logger.debug(`Flushing batch of ${urls.length} URLs`);
141
+ const items = batch.map((r) => ({ ref: r.ref, request: r.request }));
142
+ this.logger.debug(`Flushing batch of ${items.length} requests`);
144
143
  try {
145
- const results = await this.executor(urls);
146
- for (const request of batch) {
147
- const result = results.get(request.url);
148
- if (result) {
149
- request.resolve(result);
150
- } else {
151
- request.resolve({ known: false });
152
- }
144
+ const results = await this.executor(items);
145
+ for (const r of batch) {
146
+ r.resolve(results.get(r.ref) ?? { known: false });
153
147
  }
154
148
  } catch (error) {
155
- for (const request of batch) {
156
- request.reject(error);
149
+ for (const r of batch) {
150
+ r.reject(error);
157
151
  }
158
152
  }
159
153
  if (this.queue.length > 0) {
160
- this.flushTimeout = setTimeout(() => {
161
- this.flush();
162
- }, this.config.maxWait);
154
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
163
155
  }
164
156
  }
165
157
  /**
@@ -176,8 +168,8 @@ var RequestBatcher = class {
176
168
  clearTimeout(this.flushTimeout);
177
169
  this.flushTimeout = null;
178
170
  }
179
- for (const request of this.queue) {
180
- request.resolve({ known: false, fallback: true });
171
+ for (const r of this.queue) {
172
+ r.resolve({ known: false, fallback: true });
181
173
  }
182
174
  this.queue = [];
183
175
  }
@@ -193,17 +185,15 @@ var LearnBatcher = class {
193
185
  /**
194
186
  * Add a learn entry to the batch queue
195
187
  */
196
- async learn(url, data) {
188
+ async learn(request, data) {
197
189
  return new Promise((resolve, reject) => {
198
- this.queue.push({ entry: { url, data }, resolve, reject });
190
+ this.queue.push({ entry: { request, data }, resolve, reject });
199
191
  if (this.queue.length >= this.config.maxSize) {
200
192
  this.flush();
201
193
  return;
202
194
  }
203
195
  if (!this.flushTimeout) {
204
- this.flushTimeout = setTimeout(() => {
205
- this.flush();
206
- }, this.config.maxWait);
196
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
207
197
  }
208
198
  });
209
199
  }
@@ -223,18 +213,16 @@ var LearnBatcher = class {
223
213
  this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
224
214
  try {
225
215
  const result = await this.executor(entries);
226
- for (const request of batch) {
227
- request.resolve(result);
216
+ for (const r of batch) {
217
+ r.resolve(result);
228
218
  }
229
219
  } catch (error) {
230
- for (const request of batch) {
231
- request.reject(error);
220
+ for (const r of batch) {
221
+ r.reject(error);
232
222
  }
233
223
  }
234
224
  if (this.queue.length > 0) {
235
- this.flushTimeout = setTimeout(() => {
236
- this.flush();
237
- }, this.config.maxWait);
225
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
238
226
  }
239
227
  }
240
228
  /**
@@ -259,8 +247,8 @@ var LearnBatcher = class {
259
247
  clearTimeout(this.flushTimeout);
260
248
  this.flushTimeout = null;
261
249
  }
262
- for (const request of this.queue) {
263
- request.resolve({ status: "rejected", learned: 0 });
250
+ for (const r of this.queue) {
251
+ r.resolve({ status: "rejected", learned: 0 });
264
252
  }
265
253
  this.queue = [];
266
254
  }
@@ -361,7 +349,7 @@ var FetchBrainClient = class {
361
349
  this.logger
362
350
  );
363
351
  this.batcher = new RequestBatcher(
364
- (urls) => this.executeBatchQuery(urls),
352
+ (items) => this.executeBatchQuery(items),
365
353
  this.config.batch,
366
354
  this.logger
367
355
  );
@@ -372,56 +360,48 @@ var FetchBrainClient = class {
372
360
  );
373
361
  }
374
362
  /**
375
- * Query if FetchBrain "knows" a URL
363
+ * Query if FetchBrain "knows" a request
376
364
  */
377
- async query(url) {
365
+ async query(request) {
378
366
  if (this.circuitBreaker.isOpen()) {
379
- this.logger.debug(`Circuit open, skipping query for: ${url}`);
380
367
  return { known: false, fallback: true };
381
368
  }
382
369
  try {
383
- return await this.batcher.query(url);
370
+ return await this.batcher.query(request);
384
371
  } catch (error) {
385
- this.logger.debug(`Query failed for ${url}:`, error);
372
+ this.logger.debug("Query failed:", error);
386
373
  return { known: false, fallback: true };
387
374
  }
388
375
  }
389
376
  /**
390
- * Query multiple URLs at once (bypass batcher for bulk operations)
377
+ * Query multiple requests at once — returns ordered array matching input order
391
378
  */
392
- async queryBulk(urls) {
379
+ async queryBulk(requests) {
393
380
  if (this.circuitBreaker.isOpen()) {
394
- this.logger.debug(`Circuit open, skipping bulk query`);
395
- return new Map(
396
- urls.map((url) => [url, { known: false, fallback: true }])
397
- );
381
+ return requests.map(() => ({ known: false, fallback: true }));
398
382
  }
399
383
  try {
400
- return await this.executeBatchQuery(urls);
401
- } catch (error) {
402
- this.logger.debug(`Bulk query failed:`, error);
403
- return new Map(
404
- urls.map((url) => [url, { known: false, fallback: true }])
405
- );
384
+ const items = requests.map((request, i) => ({ ref: String(i), request }));
385
+ const results = await this.executeBatchQuery(items);
386
+ return items.map((i) => results.get(i.ref) ?? { known: false });
387
+ } catch {
388
+ return requests.map(() => ({ known: false, fallback: true }));
406
389
  }
407
390
  }
408
391
  /**
409
392
  * "Teach" FetchBrain new data (batched for high-concurrency)
410
393
  */
411
- async learn(url, data) {
394
+ async learn(request, data) {
412
395
  if (!this.config.learning) {
413
396
  return { status: "rejected", learned: 0 };
414
397
  }
415
398
  if (this.circuitBreaker.isOpen()) {
416
- this.logger.debug(`Circuit open, skipping learn for: ${url}`);
417
399
  return { status: "rejected", learned: 0 };
418
400
  }
419
401
  try {
420
- const response = await this.learnBatcher.learn(url, data);
421
- this.logger.debug(`Learned data for: ${url}`);
422
- return response;
402
+ return await this.learnBatcher.learn(request, data);
423
403
  } catch (error) {
424
- this.logger.warn(`Learn failed for ${url}:`, error);
404
+ this.logger.warn("Learn failed:", error);
425
405
  return { status: "rejected", learned: 0 };
426
406
  }
427
407
  }
@@ -447,10 +427,10 @@ var FetchBrainClient = class {
447
427
  /**
448
428
  * Execute a batch query against the API
449
429
  */
450
- async executeBatchQuery(urls) {
430
+ async executeBatchQuery(items) {
451
431
  const results = /* @__PURE__ */ new Map();
452
432
  const request = {
453
- urls,
433
+ items,
454
434
  intelligence: this.config.intelligence
455
435
  };
456
436
  if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
@@ -463,14 +443,10 @@ var FetchBrainClient = class {
463
443
  });
464
444
  this.circuitBreaker.recordSuccess();
465
445
  for (const item of response.known) {
466
- results.set(item.url, {
467
- known: true,
468
- data: item.data,
469
- confidence: item.confidence
470
- });
446
+ results.set(item.ref, { known: true, data: item.data, confidence: item.confidence });
471
447
  }
472
- for (const url of response.unknown) {
473
- results.set(url, { known: false });
448
+ for (const ref of response.unknown) {
449
+ results.set(ref, { known: false });
474
450
  }
475
451
  return results;
476
452
  } catch (error) {
@@ -482,23 +458,20 @@ var FetchBrainClient = class {
482
458
  * Execute a batch learn against the API
483
459
  */
484
460
  async executeBatchLearn(entries) {
485
- const processedEntries = entries.map((entry) => ({
486
- url: entry.url,
487
- data: this.config.extractForLearning ? this.config.extractForLearning(entry.data) : entry.data
461
+ const processed = entries.map((e) => ({
462
+ request: e.request,
463
+ data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
488
464
  }));
489
465
  try {
490
466
  const response = await this.makeRequest(
491
467
  "/v1/learn",
492
468
  {
493
469
  method: "POST",
494
- body: JSON.stringify({
495
- entries: processedEntries
496
- })
470
+ body: JSON.stringify({ entries: processed })
497
471
  },
498
472
  DEFAULT_LEARN_TIMEOUT
499
473
  );
500
474
  this.circuitBreaker.recordSuccess();
501
- this.logger.debug(`Batch learned ${entries.length} entries`);
502
475
  return response;
503
476
  } catch (error) {
504
477
  this.circuitBreaker.recordFailure();
@@ -762,6 +735,36 @@ var TelemetryBuffer = class {
762
735
  };
763
736
 
764
737
  // src/enhance.ts
738
+ var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
739
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainKnown", "fetchBrainData", "__fetchBrainResult"]);
740
+ function buildRawRequest(request) {
741
+ const r = request;
742
+ let headers;
743
+ if (r.headers) {
744
+ headers = {};
745
+ for (const [k, v] of Object.entries(r.headers)) {
746
+ if (!STRIP_HEADERS.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
747
+ }
748
+ if (Object.keys(headers).length === 0) headers = void 0;
749
+ }
750
+ let userData;
751
+ if (r.userData) {
752
+ userData = {};
753
+ for (const [k, v] of Object.entries(r.userData)) if (!SDK_USERDATA_KEYS.has(k)) userData[k] = v;
754
+ if (Object.keys(userData).length === 0) userData = void 0;
755
+ }
756
+ let body;
757
+ if (typeof r.payload === "string") body = r.payload;
758
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
759
+ }
760
+ function warnDefaultUniqueKey(request, logger, warned) {
761
+ const method = (request.method ?? "GET").toUpperCase();
762
+ const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
763
+ if (method !== "GET" && isDefault && !warned.has(request.url)) {
764
+ 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 be cached separately.`);
766
+ }
767
+ }
765
768
  var asyncContext = new AsyncLocalStorage();
766
769
  function getCurrentContext() {
767
770
  return asyncContext.getStore();
@@ -777,7 +780,6 @@ function shouldRunHandler(alwaysRun, label) {
777
780
  const requestLabel = label || "default";
778
781
  return labels.includes(requestLabel);
779
782
  }
780
- var requestContextMap = /* @__PURE__ */ new WeakMap();
781
783
  var FetchBrain = class {
782
784
  constructor(config) {
783
785
  this.client = new FetchBrainClient(config);
@@ -787,7 +789,7 @@ var FetchBrain = class {
787
789
  * Query if FetchBrain "knows" a URL
788
790
  */
789
791
  async query(options) {
790
- const result = await this.client.query(options.url);
792
+ const result = await this.client.query({ url: options.url });
791
793
  return {
792
794
  known: result.known,
793
795
  data: result.data,
@@ -798,7 +800,7 @@ var FetchBrain = class {
798
800
  * "Teach" FetchBrain new data
799
801
  */
800
802
  async learn(options) {
801
- return this.client.learn(options.url, options.data);
803
+ return this.client.learn({ url: options.url }, options.data);
802
804
  }
803
805
  /**
804
806
  * Get usage statistics
@@ -846,6 +848,7 @@ var FetchBrain = class {
846
848
  return Object.assign(crawler, { fetchBrain: client });
847
849
  }
848
850
  const crawlerType = crawler.constructor?.name || "Unknown";
851
+ const warnedKeys = /* @__PURE__ */ new Set();
849
852
  const wrappedHandler = async (context) => {
850
853
  const { request } = context;
851
854
  const url = request.url;
@@ -857,8 +860,10 @@ var FetchBrain = class {
857
860
  label,
858
861
  url
859
862
  });
863
+ const rawRequest = buildRawRequest(request);
864
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
860
865
  try {
861
- const aiResult = await client.query(url);
866
+ const aiResult = await client.query(rawRequest);
862
867
  let usedAIData = false;
863
868
  const originalPushData = context.pushData;
864
869
  context.ai = {
@@ -902,20 +907,18 @@ var FetchBrain = class {
902
907
  } else {
903
908
  logger.debug(`Learning: ${url}`);
904
909
  }
905
- requestContextMap.set(context, url);
906
910
  if (originalPushData && config.learning !== false) {
907
911
  context.pushData = async (data) => {
908
912
  const shouldLearn = !usedAIData && !aiResult.known;
909
913
  if (shouldLearn) {
910
914
  runStats.learned++;
911
- const requestUrl = requestContextMap.get(context) || url;
912
- await client.learn(requestUrl, data);
915
+ await client.learn(rawRequest, data);
913
916
  }
914
917
  return originalPushData.call(context, data);
915
918
  };
916
919
  }
917
920
  const requestContext = {
918
- url,
921
+ request: rawRequest,
919
922
  client,
920
923
  learning: config.learning !== false,
921
924
  aiKnown: aiResult.known
@@ -923,7 +926,6 @@ var FetchBrain = class {
923
926
  await asyncContext.run(requestContext, async () => {
924
927
  await originalHandler.call(crawler, context);
925
928
  });
926
- requestContextMap.delete(context);
927
929
  if (config.telemetry?.enabled) {
928
930
  try {
929
931
  const telemetry = await collectTelemetry(
@@ -1040,7 +1042,7 @@ async function pushData(data, dataset, datasetName) {
1040
1042
  if (ctx && ctx.learning && !ctx.aiKnown) {
1041
1043
  const items = Array.isArray(data) ? data : [data];
1042
1044
  for (const item of items) {
1043
- await ctx.client.learn(ctx.url, item);
1045
+ await ctx.client.learn(ctx.request, item);
1044
1046
  }
1045
1047
  }
1046
1048
  if (datasetName && dataset.open) {